AWS Developer Blog

Providing credentials to the AWS SDK for PHP

In order to authenticate requests, the AWS SDK for PHP requires credentials in the form of an AWS access key ID and secret access key. In this post, we’ll discuss how to configure credentials in the AWS SDK for SDK.

Configuring credentials

There are several methods that can be used for configuring credentials in the SDK. The method that you use to supply credentials to your application is up to you, but we recommend that you use IAM roles when running on Amazon EC2 or use environment variables when running elsewhere.

Credentials can be specified in several ways:

  1. IAM roles (Amazon EC2 only)
  2. Environment variables
  3. Configuration file and the service builder
  4. Passing credentials into a client factory method

If you do not provide credentials to the SDK using a factory method or a service builder configuration file, the SDK checks if the AWS_ACCESS_KEY_ID and AWS_SECRET_KEY environment variables are present. If defined, these values are used as your credentials. If these environment variables are not found, the SDK attempts to retrieve IAM role credentials from an Amazon EC2 instance metadata server. If your application is running on Amazon EC2 and the instance metadata server responds successfully with credentials, they are used to authenticate requests. If none of the above methods successfully yield credentials, an AwsCommonExceptionInstanceProfileCredentialsException exception is thrown.

IAM roles (Amazon EC2 only)

IAM roles are the preferred method 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 instance’s metadata server. These temporary credentials allow access to the actions and resources that the role’s policy allows.

When launching an EC2 instance, you can choose to associate it with an IAM role. Any application running on that EC2 instance is then allowed to assume the associated role. Amazon EC2 handles all the legwork of securely authenticating instances to the IAM service to assume the role and periodically refreshing the retrieved role credentials, keeping your application secure with almost no work on your part.

If you do not provide credentials and no environment variable credentials available, the SDK attempts to retrieve IAM role credentials from an Amazon EC2 instance metadata server. These credentials are available only when running on Amazon EC2 instances that have been configured with an IAM role.

Caching IAM role credentials

While using IAM role credentials is the preferred method for providing credentials to an application running on an Amazon EC2 instance, the roundtrip from the application to the instance metadata server on each request can introduce latency. In these situations, you might find that utilizing a caching layer on top of your IAM role credentials can eliminate the introduced latency.

The easiest way to add a cache to your IAM role credentials is to specify a credentials cache using the credentials.cache option in a client’s factory method or in a service builder configuration file. The credentials.cache configuration setting should be set to an object that implements Guzzle’s GuzzleCacheCacheAdapterInterface. This interface provides an abstraction layer over various cache backends, including Doctrine Cache, Zend Framework 2 cache, etc.

<?php

require 'vendor/autoload.php';

use DoctrineCommonCacheFilesystemCache;
use GuzzleCacheDoctrineCacheAdapter;

// Create a cache adapter that stores data on the filesystem
$cacheAdapter = new DoctrineCacheAdapter(new FilesystemCache('/tmp/cache'));

// Provide a credentials.cache to cache credentials to the file system
$s3 = AwsS3S3Client::factory(array(
    'credentials.cache' => $cacheAdapter
));

With the addition of credentials.cache, credentials are now cached to the local filesystem using Doctrine’s caching system. Every request that uses this cache adapter first checks if the credentials are in the cache. If the credentials are found in the cache, the client then ensures that the credentials are not expired. In the event that cached credentials become expired, the client automatically refreshes the credentials on the next request and populates the cache with the updated credentials.

A credentials cache can also be used in a service builder configuration:

<?php

// File saved as /path/to/custom/config.php

use DoctrineCommonCacheFilesystemCache;
use GuzzleCacheDoctrineCacheAdapter;

$cacheAdapter = new DoctrineCacheAdapter(new FilesystemCache('/tmp/cache'));

return array(
    'includes' => array('_aws'),
    'services' => array(
        'default_settings' => array(
            'params' => array(
                'credentials.cache' => $cacheAdapter
            )
        )
    )
);

If you were to use the above configuration file with a service builder, then all of the clients created through the service builder would utilize a shared credentials cache object.

Environment variables

If you do not provide credentials to a client’s factory method or via a service builder configuration, the SDK attempts to find credentials in your environment by checking in the $_SERVER superglobal and using the getenv() function, looking for the AWS_ACCESS_KEY_ID and AWS_SECRET_KEY environment variables.

If you are hosting your application on AWS Elastic Beanstalk, you can set the AWS_ACCESS_KEY_ID and AWS_SECRET_KEY environment variables through the AWS Elastic Beanstalk console so that the SDK can use those credentials automatically.

Configuration file and the service builder

The SDK provides a service builder that can be used to share configuration values across multiple clients. The service builder allows you to specify default configuration values (e.g., credentials and regions) that are applied to every client. The service builder is configured using either JSON configuration files or PHP scripts that return an array.

Here’s an example of a configuration script that returns an array of configuration data that can be used by the service builder:

<?php

// File saved as /path/to/custom/config.php

return array(
    // Bootstrap the configuration file with AWS specific features
    'includes' => array('_aws'),
    'services' => array(
        // All AWS clients extend from 'default_settings'. Here we are
        // overriding 'default_settings' with our default credentials and
        // providing a default region setting.
        'default_settings' => array(
            'params' => array(
                'key'    => 'your-aws-access-key-id',
                'secret' => 'your-aws-secret-access-key',
                'region' => 'us-west-1'
            )
        )
    )
);

After creating and saving the configuration file, you need to instantiate a service builder.

<?php

// Assuming the SDK was installed via Composer
require 'vendor/autoload.php';

use AwsCommonAws;

// Create the AWS service builder, providing the path to the config file
$aws = Aws::factory('/path/to/custom/config.php');

At this point, you can now create clients using the get() method of the Aws object:

$s3 = $aws->get('s3');

Passing credentials into a factory method

A simple way to specify your credentials is by injecting them directly into the factory method of a client. This is useful for quick scripting, but be careful to not hard-code your credentials inside of your applications. Hard-coding your credentials inside of an application can be dangerous because it is easy to commit your credentials into an SCM repository, potentially exposing your credentials to more people than intended. It can also make it difficult to rotate credentials in the future.

<?php

$s3 = AwsS3S3Client::factory(array(
    'key'    => 'my-access-key-id',
    'secret' => 'my-secret-access-key'
));