AWS STS: Assume an IAM Role
Assume an IAM role using aws sts assume-role to get temporary credentials for cross-account access or privilege escalation.
STS Operations
Detailed Explanation
Assuming IAM Roles with STS
The aws sts assume-role command requests temporary security credentials for a specified IAM role. This is the foundation of cross-account access, privilege separation, and temporary credential workflows in AWS.
Basic Assume Role
aws sts assume-role \
--role-arn arn:aws:iam::987654321098:role/CrossAccountReader \
--role-session-name my-session
Output Structure
{
"Credentials": {
"AccessKeyId": "ASIAEXAMPLE",
"SecretAccessKey": "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY",
"SessionToken": "FwoGZXIvYXdzEBYaDH...",
"Expiration": "2024-01-15T12:00:00Z"
},
"AssumedRoleUser": {
"AssumedRoleId": "AROAEXAMPLE:my-session",
"Arn": "arn:aws:sts::987654321098:assumed-role/CrossAccountReader/my-session"
}
}
Using Assumed Credentials
# Capture the credentials
CREDS=$(aws sts assume-role \
--role-arn arn:aws:iam::987654321098:role/MyRole \
--role-session-name cli-session \
--output json)
# Export as environment variables
export AWS_ACCESS_KEY_ID=$(echo $CREDS | jq -r '.Credentials.AccessKeyId')
export AWS_SECRET_ACCESS_KEY=$(echo $CREDS | jq -r '.Credentials.SecretAccessKey')
export AWS_SESSION_TOKEN=$(echo $CREDS | jq -r '.Credentials.SessionToken')
# Now commands run as the assumed role
aws s3 ls s3://other-account-bucket/
With External ID (for third-party access)
aws sts assume-role \
--role-arn arn:aws:iam::987654321098:role/ThirdPartyAccess \
--role-session-name vendor-session \
--external-id unique-external-id-12345
Custom Session Duration
aws sts assume-role \
--role-arn arn:aws:iam::987654321098:role/MyRole \
--role-session-name long-session \
--duration-seconds 43200
Maximum duration depends on the role's MaxSessionDuration setting (default 1 hour, max 12 hours).
Profile-Based Assume Role
Instead of scripting, add to ~/.aws/config:
[profile cross-account]
role_arn = arn:aws:iam::987654321098:role/MyRole
source_profile = default
Then use: aws s3 ls --profile cross-account
Use Case
Accessing resources in other AWS accounts, implementing least-privilege with temporary credentials, configuring CI/CD cross-account deployments, or switching between organizational roles.