Location to put credentials file for AWS PHP SDK

I created an EC2 Ubuntu instance.

The following is working using the AWS 2.6 SDK for PHP:

$client = DynamoDbClient::factory(array(
    'key' => 'xxx',
    'secret' => 'xxx',
    'region'  => 'eu-west-1'
));

I created a credentials file in ~/.aws/credentials.
I put this in /home/ubuntu/.aws/credentials

[default]
aws_access_key_id=xxx
aws_secret_access_key=xxx

Trying the following does not work and gives an InstanceProfileCredentialsException :

$client = DynamoDbClient::factory(array(
    'profile' => 'default',
    'region'  => 'eu-west-1'
));

There is a user www-data and a user ubuntu.
In what folder should I put the credentials file?


One solution to set the credentials is:

sudo nano /etc/apache2/envvars

add environment variables:

export AWS_ACCESS_KEY_ID="xxx"
export AWS_SECRET_ACCESS_KEY="xxx"

sudo service apache2 restart

After that the following works:

$client = DynamoDbClient::factory(array(
    'region'  => 'eu-west-1'
));

If you are calling the API from an EC2 instance, you should use IAM roles.

Using IAM roles is the preferred technique for providing credentials to applications running on Amazon EC2. IAM roles remove the need to worry about credential management from your application. They allow an instance to "assume" a role by retrieving temporary credentials from the EC2 instance's metadata server. These temporary credentials, often referred to as instance profile credentials, allow access to the actions and resources that the role's policy allows.


This is way too late, but the solution I found for shared servers where you can't actually use environment vars is to define a custom ini file location, like this:

require (__DIR__.'/AWSSDK/aws-autoloader.php');

use Aws\Credentials\CredentialProvider;
use Aws\S3\S3Client;

$profile = 'default';
$path = '/path/to/credentials';

$provider = CredentialProvider::ini($profile, $path);
$provider = CredentialProvider::memoize($provider);

$client = new \Aws\S3\S3Client([
    'version' => 'latest',
    'region' => 'us-west-2',
    'credentials' => $provider
]);

Note that you could even define different profiles with this method. Documentation HERE