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
requirestatement includes the AWS SDK for PHP. - The
usestatements import the necessary classes. - The
$stsvariable creates an instance of theStsClientclass. - The
$role_arnvariable contains the ARN of the role to be assumed. - The
$resultvariable stores the result of theassumeRolecall. - The
$credentialsvariable stores the credentials returned by theassumeRolecall. - The
$access_key_id,$secret_access_key, and$session_tokenvariables store the credentials returned by theassumeRolecall.
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?
See more codes...