AWS EC2 PHP SDK credentials not working - php

I am trying to create a way to programatically start/stop my EC2 instances. This is the code I am using:
<?php
$ec2 = new \Aws\Ec2\Ec2Client([
'credentials' => [
'key' => 'KEY_HERE',
'secret' => 'SECRET_HERE'
],
'region' => env('AWS_REGION', 'us-west-2'),
'version' => 'latest',
'ua_append' => [
'L5MOD/' . AwsServiceProvider::VERSION,
]
]);
$result = $ec2->describeInstanceStatus([
'InstanceIds' => ['i-c21a366e']
]);
?>
Of course I am using my actual keys instead of 'KEY_HERE' and 'SECRET_HERE'.
I am getting this error as you can see in this screenshot:
I want to mention that if I use the S3 service, everything works fine. I am having this problem with the EC2 service only.
Any idea what could be wrong?

I finally found out what is going on and I was able to fix it.
Looks like AWS is using server clock for authorizing access and I needed to install the ntp service and update it so that the clock is properly synced.
I installed the ntp server by running:
sudo apt-get install ntp
Then I updated the services with these commands:
sudo service ntp stop
sudo ntpd -gq
sudo service ntp start
And problem was fixed.

Related

cUrl - Host can not be resolved while ping is working fine

After running an apt upgrade and a restart of my ubuntu server, cUrl (via Guzzle) repots an error that the host cannot be resolved.
cURL error 6: Could not resolve host: xx.xx (see http:\/\/curl.haxx.se\/libcurl\/c\/libcurl-errors.html)
My code is
$client = new Client();
$response = $client->post("https://xx.xx?r=/center/api", [
RequestOptions::HEADERS => [
'X-Requested-With' => 'XMLHttpRequest'
]
]);
This happens randomly and with multiple domains. Meanwhile i was running pings for those domains on the terminal and they were working.
On StackOverflow and Google I could only find solutions that were adding the host to the hosts file but for me that seems to be not a real solution.

Error retrieving credentials from the instance profile metadata server. Laravel S3

Issue
The same code, on almost identical servers, fails locally and on production, however works on our staging server. When we attempt to interact with an item in a bucket, we get an Error retrieving credentials....
- Both servers, staging and production, are deployed by Envoyer and provisioned by Forge to AWS EC2 instances.
- Both instances hit the same bucket with the same bucket policy.
- .env settings are same for all, minus the server name and debugging
Error on production:
Aws\Exception\CredentialsException
Error retrieving credentials from the instance profile metadata server. (cURL error 28: Connection timed out after 1003 milliseconds (see http://curl.haxx.se/libcurl/c/libcurl-errors.html))
Server settings
Staging
Ubuntu 16.04.2 LTS on AWS
PHP 7.1.3-3
NPM 3.10.10
Node v6.10.1
Production
Ubuntu 16.04.1 LTS on AWS EC2
PHP 7.1.6-1
npm 3.10.10
Node v6.10.1
Composer.json packages
"laravel/framework": "5.4.*", // 5.4.25
"aws/aws-sdk-php-laravel": "~3.0", // 3.1.0
"guzzlehttp/guzzle": "~6.0", // 6.2.3
Code sample
function getPhoto($personID)
{
$contents = '';
$id = $personID;
$cloudFront = env('AWS_CLOUDFRONT_PHOTO'); // d212rosgvhtylp.cloudfront.net
$fileKey = filePath($id) . '_t.jpg'; // 9ae299a1990e79d62f07c28bb60ecf6f_t.jpg
$fileURL = $cloudFront . '/' . filePath($id) . '_t.jpg'; // d212rosgvhtylp.cloudfront.net/9ae299a1990e79d62f07c28bb60ecf6f_t.jpg
// check if in remote storage then get contents
$contents = Storage::disk('s3photo')->get($fileKey); /* ****** FAILS HERE ****** */
// stream bioPhoto
header('Content-Type: image/jpeg');
echo $contents;
}
After ensuring your .env files contain the correct values for the AWS client, run the following command:
php artisan config:clear
This should clear up your issue if it is caused by initially having incorrect or missing env data, not sure when the cache is updated on it's own but the config cache seems to be pretty persistent.
I encountered this issue after I accedentially had entered the AWS_ACCESS_KEY_ID in the .env file twice.
.env:
AWS_ACCESS_KEY_ID=MYREALID
AWS_SECRET_ACCESS_KEY=myrealkey
...
...a lot of variables..
...
AWS_ACCESS_KEY_ID=
AWS_SECRET_ACCESS_KEY=
The AWS sdk therefor tries to search for these credentials elsewhere, at that's have the error occures.
I recently had this problem. In my case, it worked locally and not on the EC2 instance. I did not understand too much. In the end I realized that I had set up IAM locally in the default folder ~/.aws/credentials, so in local everything was good. So I poked in the laravel sources and I noticed that laravel was going to take the connection configs in the file services.php config folder.
Edit config/services.php and put in the AWS IAM keys.
'mailgun' => [
'domain' => env('MAILGUN_DOMAIN'),
'secret' => env('MAILGUN_SECRET'),
],
'ses' => [
'key' => env('AWS_KEY'),
'secret' => env('AWS_SECRET'),
'region' => env('AWS_REGION'),
],
'sparkpost' => [
'secret' => env('SPARKPOST_SECRET'),
],
'stripe' => [
'model' => App\User::class,
'key' => env('STRIPE_KEY'),
'secret' => env('STRIPE_SECRET'),
],
So I saw that my .env file did not have the AWS IAM login keys, those called in the config /services.php file.
After a small adjustment everything works great.
This issue may occur if you are passing the wrong ENV variables, check your config/filesystems.php:
'key' => env('AWS_ACCESS_KEY_ID'),
'secret' => env('AWS_SECRET_ACCESS_KEY'),
'region' => env('AWS_DEFAULT_REGION'),
'bucket' => env('AWS_BUCKET'),
'url' => env('AWS_URL'),
See: https://github.com/laravel/laravel/blob/master/config/filesystems.php#L60
And make sure the keys are matching in your .env.
Pretty sure they changed the name in the last couple updates.

beanstalkd driver configuration error in laravel app

I am trying to use beanstalkd as the queue driver for my laravel app. I am getting this error when I am trying to push something on the queue.
Pheanstalk_Exception_ConnectionException
Socket error 111: Connection refused (connecting to localhost:11300)
Please note that in 'queue.php' I have just changed the default driver to 'beanstalkd' but haven't changed any settings for the driver. The settings for the driver are as follows-
'beanstalkd' => array(
'driver' => 'beanstalkd',
'host' => 'localhost',
'queue' => 'default',
),
Please help me with this.
Figured it out. Did these two things -
$ sudo vim /etc/default/beanstalkd
> START yes # uncomment
$ sudo service beanstalkd start
# Alternatively: /etc/init.d/beanstalkd start
Got it from this link - http://fideloper.com/ubuntu-beanstalkd-and-laravel4
The answer by #halkujabra is correct. The error is because beanstalkd is not running. To fix it you just have to start beanstalkd. For MacOS use this script https://gist.github.com/finger-berlin/1942295 to to that.
Download and save it as script.sh
Make it executable: chmod a+x script.sh
Run ./script.sh start

Composer update ran via puppet times out

I'm using composer to manage dependencies. And basically want I want to do is automatically run composer update in puppet config when vagrant up is running.
I'm using puphpet to generate puppet files for vagrant.
I added composer::exec section in this code in the default.pp file:
if $php_values['composer'] == 1 {
class { 'composer':
target_dir => '/usr/local/bin',
composer_file => 'composer',
download_method => 'curl',
logoutput => true,
tmp_path => '/tmp',
php_package => "${php::params::module_prefix}cli",
curl_package => 'curl',
suhosin_enabled => false,
}
composer::exec { 'composer-update':
cmd => 'update',
cwd => '/var/www/myproject'
}
}
Some times I'm getting this error in output:
Error: Command exceeded timeout
Error: /Stage[main]//Composer::Exec[composer-update]/Exec[composer_update_composer-update]/returns: change from notrun to 0 failed: Command exceeded timeout
And there is no timeout property in puppet composer.
How to solve it?
Take a look at http://docs.puppetlabs.com/references/latest/type.html#exec-attribute-timeout - it is possible to set a timeout for an exec resource. If the puppet composer module does not provide an option to override that, it really should IMO. And if by a chance it is composer itself that's timing out, not puppet exec, you'd wanna try
export COMPOSER_PROCESS_TIMEOUT=600

Amazon DynamoDB InvalidSignatureException

From this code I'm getting the error below
require "vendor/autoload.php";
use Aws\Common\Aws;
use Aws\DynamoDb\DynamoDbClient;
use Aws\DynamoDb\Enum\ComparisonOperator;
use Aws\DynamoDb\Enum\KeyType;
use Aws\DynamoDb\Enum\Type;
$aws = Aws::factory(array(
'key' => '[clipped]',
'secret' => '[clipped]',
'region' => Region::US_WEST_1
));
$client = $aws->get("dynamodb");
$tableName = "ExampleTable";
$result = $client->createTable(array(
"TableName" => $tableName,
"AttributeDefinitions" => array(
array(
"AttributeName" => "Id",
"AttributeType" => Type::NUMBER
)
),
"KeySchema" => array(
array(
"AttributeName" => "Id",
"KeyType" => KeyType::HASH
)
),
"ProvisionedThroughput" => array(
"ReadCapacityUnits" => 5,
"WriteCapacityUnits" => 6
)
));
print_r($result->getPath('TableDescription'));
I'm getting the following error when trying to add a table into AWS's DynamoDB.
PHP Fatal error: Uncaught Aws\\DynamoDb\\Exception\\DynamoDbException: AWS Error Code:
InvalidSignatureException,
Status Code: 400,
AWS Request ID: [clipped],
AWS Error Type: client,
AWS Error Message: Signature expired: 20130818T021159Z is now earlier than
20130818T021432Z (20130818T022932Z - 15 min.),
User-Agent: aws-sdk-php2/2.4.3 Guzzle/3.7.2 curl/7.21.6 PHP/5.3.6-13ubuntu3.9\n thrown in
/var/www/vendor/aws/aws-sdk-php/src/Aws/Common/Exception/NamespaceExceptionFactory.php on
line 91
So far I've:
Checked to see if Authentication Key and Secret Key were correct, they were.
Updated cURL
When I put false authentication permissions in, the error didn't change.
It seems that your local system time might be incorrect. I've had a similar problem with AWS S3, where my system clock was skewed by 30 mins.
If you're running ubuntu, try updating your system time:
sudo ntpdate ntp.ubuntu.com
You can also restart your date service to solve the problem if you've already got ntpdate installed.
sudo service ntpdate stop
sudo service ntpdate start
If you are using docker-machine on Mac, you can resolve with this command:
docker-machine ssh default 'sudo ntpclient -s -h pool.ntp.org'
Quick note for vagrant projects: this is usually resolved by vagrant reload.
Not exactly OP question, but this is top google response for "InvalidSignatureException DynamoDB", which has many underlying causes.
For me, it was because my body contained emoji, 100% reproducible. Worked around by encoding the body (in my case stringified json) using encodeURIComponent.

Categories