Using the AWS PHP SDK

Published on by

Using the AWS PHP SDK image

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:

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

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:

// $result: ['Location' => 'us-east-2']
$result = $ec2->runInstances([
 
// ImageId: https://cloud-images.ubuntu.com/locator/ec2/
'ImageId' => 'ami-0b29b6e62f2343b46',
'InstanceType' => 't3.small',
 
// Optional parameters you likely want to define
// 'KeyName' => "some-key",
// 'SecurityGroupIds' => ['sg-foobar'],
// 'SubnetId' => 'subnet-foobar',
 
'MaxCount' => 1, // You can create multiple servers
'MinCount' => 1, // but we'll just create one
 
// Create the root disk volume
'BlockDeviceMappings' => [
// Can usually assume this is the correct
// root device name
'DeviceName' => '/dev/sda1',
'Ebs' => [
'DeleteOnTermination' => true,
'VolumeSize' => 8,
'VolumeType' => 'gp3',
],
],
]);

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:

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

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:

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

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!

Chris Fidao photo

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

Cube

Laravel Newsletter

Join 40k+ other developers and never miss out on new tips, tutorials, and more.

image
No Compromises

Joel and Aaron, the two seasoned devs from the No Compromises podcast, are now available to hire for your Laravel project.

Visit No Compromises
Laravel Forge logo

Laravel Forge

Easily create and manage your servers and deploy your Laravel applications in seconds.

Laravel Forge
Tinkerwell logo

Tinkerwell

The must-have code runner for Laravel developers. Tinker with AI, autocompletion and instant feedback on local and production environments.

Tinkerwell
No Compromises logo

No Compromises

Joel and Aaron, the two seasoned devs from the No Compromises podcast, are now available to hire for your Laravel project. ⬧ Flat rate of $7500/mo. ⬧ No lengthy sales process. ⬧ No contracts. ⬧ 100% money back guarantee.

No Compromises
Kirschbaum logo

Kirschbaum

Providing innovation and stability to ensure your web application succeeds.

Kirschbaum
Shift logo

Shift

Running an old Laravel version? Instant, automated Laravel upgrades and code modernization to keep your applications fresh.

Shift
Bacancy logo

Bacancy

Supercharge your project with a seasoned Laravel developer with 4-6 years of experience for just $2500/month. Get 160 hours of dedicated expertise & a risk-free 15-day trial. Schedule a call now!

Bacancy
LoadForge logo

LoadForge

Easy, affordable load testing and stress tests for websites, APIs and databases.

LoadForge
Paragraph logo

Paragraph

Manage your Laravel app as if it was a CMS – edit any text on any page or in any email without touching Blade or language files.

Paragraph
Lucky Media logo

Lucky Media

Bespoke software solutions built for your business. We ♥ Laravel

Lucky Media
Lunar: Laravel E-Commerce logo

Lunar: Laravel E-Commerce

E-Commerce for Laravel. An open-source package that brings the power of modern headless e-commerce functionality to Laravel.

Lunar: Laravel E-Commerce
DocuWriter.ai logo

DocuWriter.ai

Save hours of manually writing Code Documentation, Comments & DocBlocks, Test suites and Refactoring.

DocuWriter.ai
LaraJobs logo

LaraJobs

The official Laravel job board

LaraJobs
All Green logo

All Green

All Green is a SaaS test runner that can execute your whole Laravel test suite in mere seconds so that you don't get blocked – you get feedback almost instantly and you can deploy to production very quickly.

All Green
Larafast: Laravel SaaS Starter Kit logo

Larafast: Laravel SaaS Starter Kit

Larafast is a Laravel SaaS Starter Kit with ready-to-go features for Payments, Auth, Admin, Blog, SEO, and beautiful themes. Available with VILT and TALL stacks.

Larafast: Laravel SaaS Starter Kit
SaaSykit: Laravel SaaS Starter Kit logo

SaaSykit: Laravel SaaS Starter Kit

SaaSykit is a Laravel SaaS Starter Kit that comes with all features required to run a modern SaaS. Payments, Beautiful Checkout, Admin Panel, User dashboard, Auth, Ready Components, Stats, Blog, Docs and more.

SaaSykit: Laravel SaaS Starter Kit
Rector logo

Rector

Your partner for seamless Laravel upgrades, cutting costs, and accelerating innovation for successful companies

Rector

The latest

View all →
Automatic Blade Formatting on Save in PhpStorm image

Automatic Blade Formatting on Save in PhpStorm

Read article
PhpStorm 2024.1 Is Released With a Integrated Terminal, Local AI Code Completion, and More image

PhpStorm 2024.1 Is Released With a Integrated Terminal, Local AI Code Completion, and More

Read article
Laravel Prompts Adds a Multi-line Textarea Input, Laravel 11.3 Released image

Laravel Prompts Adds a Multi-line Textarea Input, Laravel 11.3 Released

Read article
Bartender Is an Opinionated Way to Authenticate Users Using Laravel Socialite image

Bartender Is an Opinionated Way to Authenticate Users Using Laravel Socialite

Read article
Jeffrey Way's PhpStorm Setup in 2024 image

Jeffrey Way's PhpStorm Setup in 2024

Read article
Easily Optimize PDFs in Laravel with the Optimizer Package image

Easily Optimize PDFs in Laravel with the Optimizer Package

Read article