Assuming a role is how you temporarily get permissions from another AWS account or a different IAM role within the same account. I use this daily when working across multiple AWS accounts in an organization — you authenticate with your main account and then assume a role in the target account.

The script below calls sts assume-role, parses the temporary credentials from the JSON response, and exports them as environment variables so subsequent AWS CLI commands use the assumed role.

OUT=$(aws sts assume-role --role-arn arn:aws:iam::0123456789:role/OrganizationAccountAccessRole --role-session-name test)
export AWS_ACCESS_KEY_ID=$(echo $OUT | cut -d '"' -f 6 )
export AWS_SECRET_ACCESS_KEY=$(echo $OUT | cut -d '"' -f 10 )
export AWS_SESSION_TOKEN=$(echo $OUT | cut -d '"' -f 14 )
aws sts get-caller-identity

The temporary credentials expire after 1 hour by default (configurable up to 12 hours). If you’re doing this frequently, consider using aws sso login with AWS SSO or a tool like aws-vault which handles the credential rotation automatically. The cut parsing above is fragile — for production scripts, use jq to extract the fields more reliably.