Use STS temporary credentials in shell variables
📑 On this page
Part 116 of AWS from Zero. This lesson changes or inspects one IAM concept so the permission model stays understandable.
What we are learning
The AWS CLI recognizes three environment variables for STS credentials. The session token is mandatory.
Before you run it
ACCOUNT_ID=$(aws sts get-caller-identity --query Account --output text)
ROLE_ARN="arn:aws:iam::$ACCOUNT_ID:role/aws-zero-demo-role"Use a private shell session with history and debug output handled carefully.
The command
read AWS_ACCESS_KEY_ID AWS_SECRET_ACCESS_KEY AWS_SESSION_TOKEN <<< "$(
aws sts assume-role \
--role-arn "$ROLE_ARN" \
--role-session-name aws-zero-env \
--query "Credentials.[AccessKeyId,SecretAccessKey,SessionToken]" \
--output text
)"
export AWS_ACCESS_KEY_ID AWS_SECRET_ACCESS_KEY AWS_SESSION_TOKENThe variables override profile credentials for subsequent commands in this process.
Inspect the result
aws sts get-caller-identity \
--query "{Arn:Arn,Account:Account}" \
--output tableThe ARN should contain assumed-role/aws-zero-demo-role/aws-zero-env.
One tiny variation
aws s3api list-buckets \
--query "Buckets[].Name" \
--output textThe request now runs with the role session's effective permissions.
Common mistake
Forgetting AWS_SESSION_TOKEN produces invalid-token errors. Exporting only the access key and secret is not enough for STS credentials.
Cleanup
unset AWS_ACCESS_KEY_ID
unset AWS_SECRET_ACCESS_KEY
unset AWS_SESSION_TOKENRun get-caller-identity again to confirm the shell returned to its previous credential source.
Next, we will learn Configure an automatic assume-role CLI profile.