php-awsHow do I use PHP to assume an AWS role?
Assuming an AWS role from an EC2 instance using PHP is done using the AWS SDK for PHP. The following code example shows how to do this:
<?php
require 'vendor/autoload.php';
use Aws\Credentials\CredentialProvider;
use Aws\Sts\StsClient;
$sts = new StsClient([
'region' => 'us-west-2',
'version' => 'latest',
'credentials' => CredentialProvider::instance()
]);
$role_arn = 'arn:aws:iam::123456789012:role/MyRole';
$result = $sts->assumeRole([
'RoleArn' => $role_arn,
'RoleSessionName' => 'MySessionName'
]);
$credentials = $result->get('Credentials');
$access_key_id = $credentials['AccessKeyId'];
$secret_access_key = $credentials['SecretAccessKey'];
$session_token = $credentials['SessionToken'];
echo "Access Key Id: {$access_key_id}\n";
echo "Secret Access Key: {$secret_access_key}\n";
echo "Session Token: {$session_token}\n";
Output example
Access Key Id: <access_key_id>
Secret Access Key: <secret_access_key>
Session Token: <session_token>
In the example code above:
- The
require
statement includes the AWS SDK for PHP. - The
use
statements import the necessary classes. - The
$sts
variable creates an instance of theStsClient
class. - The
$role_arn
variable contains the ARN of the role to be assumed. - The
$result
variable stores the result of theassumeRole
call. - The
$credentials
variable stores the credentials returned by theassumeRole
call. - The
$access_key_id
,$secret_access_key
, and$session_token
variables store the credentials returned by theassumeRole
call.
Helpful links
More of Php Aws
- How do I use PHP to create a ZIP file on AWS?
- How can I use AWS and Zksync together with PHP?
- How can I use Yum to install PHP on an Amazon EC2 instance?
- How can I use an AWS SQS Worker with PHP?
- How can I use AWS WAF to secure my PHP application?
- How can I use AWS PHP SDK without credentials?
- How do I generate an AWS Signature Version 4 with PHP?
- How do I determine the version of PHP I am running on AWS?
- How can I use the AWS S3 S3Client library with PHP?
- How can I connect to an AWS MySQL database using PHP?
See more codes...