Using the AWS PHP SDK

Tutorials

September 27th, 2021

aws.png

AWS has SDK's for almost all popular languages, including PHP. These SDK's behave very similarly, using the same API calls and parameters.

Generally, the SDKs do a nice job of taking advantage of each languages strengths.

Let's see how to use the PHP SDK - it's simpler than you might think!

Configuring Credentials

The AWS SDK's all make API calls against AWS. To do this, you need IAM credentials with the correct access setup to make the API calls requests (IAM Roles and Policies).

Assuming you have the permissions to run the API calls you need, the SDK's all do a nice job of detecting the various ways you might pass the credentials to the SDK.

You can see a list of the ways to get the SDK to read your credentials here. Don't worry if they don't all make sense.

Here's the gist of it:

  1. You can set environment variables
  2. You can have your ~/.aws/credentials file
  3. Your environment (EC2 server, CodeBuild environment, Lambda function, ECS environment) can "assume" a role (more advanced)

There are other yet even more advanced ways to setup your credentials, but these are the most common.

I generally do one of the following:

  1. Setting up environment variables (via Laravel's .env file)
  2. Allow the SDK to read the ~/.aws.credentials file, usually done for local development

If you set certain environment variables, the SDK will do everything for you. If you don't have environmet variables set, the SDK will automatically search for your ~/.aws/credentials file.

Here's what it looks like to create a new Ec2Client object:

1use Aws\Ec2\Ec2Client;
2 
3$ec2 = new Ec2Client([
4 // Region is required if not set by an env var
5 'region' => 'us-east-2',
6 
7 // API version
8 'version' => 'latest',
9 
10 // Use a profile from ~/.aws/credentials
11 // 'profile' => 'your-profile-here'
12]);

Making Commands

Each language has it's own API reference documentation. The PHP docs are here.

We'll see an example of using the Amazon EC2 API to create a server. This uses the RunInstances (plural!) API call.

Here's what it looks like to create an EC2 server:

1// $result: ['Location' => 'us-east-2']
2$result = $ec2->runInstances([
3 
4 // ImageId: https://cloud-images.ubuntu.com/locator/ec2/
5 'ImageId' => 'ami-0b29b6e62f2343b46',
6 'InstanceType' => 't3.small',
7 
8 // Optional parameters you likely want to define
9 // 'KeyName' => "some-key",
10 // 'SecurityGroupIds' => ['sg-foobar'],
11 // 'SubnetId' => 'subnet-foobar',
12 
13 'MaxCount' => 1, // You can create multiple servers
14 'MinCount' => 1, // but we'll just create one
15 
16 // Create the root disk volume
17 'BlockDeviceMappings' => [
18 // Can usually assume this is the correct
19 // root device name
20 'DeviceName' => '/dev/sda1',
21 'Ebs' => [
22 'DeleteOnTermination' => true,
23 'VolumeSize' => 8,
24 'VolumeType' => 'gp3',
25 ],
26 ],
27]);

Waiters

One of the overlooked features of the SDK's is "waiters", which let you wait until a resource has reached a certain state.

This is useful to get around the times where you find yourself writing things like:

1while(/* server is not yet running */) {
2 // Check if server is running
3}

Trust me, you'll end up writing code like that when coding against AWS.

Waiters aren't always well documented, depending on the SDK. PHP's are, luckily, well documented. For example, on the EC2 page, we can scroll down to see available Waiters.

We'll use the InstanceRunning waiter. Note that it tells us this waiter uses the DescribeInstances API operation. That means the parameters we pass it are the ones used for that API call.

Let's see what that looks like:

1$result = $ec2->runInstances([/* ... */]);
2 
3// We only created one instance, so we can assume
4// the zeroeth array index
5$instanceId = $result['Instances'][0]['InstanceId'];
6 
7$ec2->waitUntil('InstanceRunning', [
8 // Can pass an array of instance ID's
9 // We only have 1 instance
10 'InstanceIds' => [$instanceId],
11 '@waiter' => [
12 'delay' => 3, // Wait 3 seconds between polling
13 'maxAttempts' => 10, // Max attempts before failing, total of 30 seconds waited here
14 ]
15]);

This will wait a maximium of 30 seconds for an instance to reach the "running" state. That's 3 attempts with 10 seconds between each attempt.

If it does not reach that state, then a timeout exception is thrown.

More Examples

If you're interested in more examples, this repository has AWS SDK examples across serveral popular languages!

Filed in:

Chris Fidao

Teaching coding and servers at CloudCasts and Servers for Hackers. Co-founder of Chipper CI.