AWS CLI & MFA
The steps outlined below define the procedure for assuming roles across accounts. These steps assume that the user has MFA enabled, is in the appropriate role on the trusted account, and has the appropriate trust policy attached to the role being assumed.
Assume Role
Environment variables may need to be unset
before calling aws sts assume-role
aws sts assume-role \
--role-arn arn:aws:iam::<account-id>:role/<name> \
--serial-number arn:aws:iam::<account-id>:mfa/<user-name> \
--role-session-name <some-name> \
--token-code <some-token>
--role-arn
: Amazon Resource Number for role being assumed--serial-number
: Amazon Resource Number of user’s MFA device *--role-session-name
: Temporary session identifier *--token-code
: Token code from user’s MFA device
The --duration-seconds
parameter is used to specify the duration of the role
session, from 900 seconds (15 minutes) up to the Maximum CLI/API session
duration setting for the role. If you specify a value for the DurationSeconds
parameter that is higher than the maximum setting, the operation fails. The
default session duration is 3600 (1 hour).
Response:
{
"Credentials": {
"AccessKeyId": "some-id",
"SecretAccessKey": "some-key",
"SessionToken": "some-token",
"Expiration": "1990-03-30T00:00:00Z"
},
"AssumedRoleUser": {
"AssumedRoleId": "some-id:some-name",
"Arn": "arn:aws:sts::<account-id>:assumed-role/<role-name>/<session-name>"
}
}
Export environment variables from the response:
export AWS_ACCESS_KEY_ID=<AccessKeyId>
export AWS_SECRET_ACCESS_KEY=<SecretAccessKey>
export AWS_SESSION_TOKEN=<SessionToken>
Validate identity
aws sts get-caller-identity
Response:
{
"UserId": "AccessKeyId",
"Account": "AccountId",
"Arn": "arn:aws:iam::<account-id>:user/<user-name>"
}
Script:
Tested on BSD systems. Requires jq
https://stedolan.github.io/jq/download/
#!/bin/bash
#usage source ./assume-role.sh role-arn mfa-arn session-name token-code
unset AWS_ACCESS_KEY_ID
unset AWS_SECRET_ACCESS_KEY
unset AWS_SESSION_TOKEN
credentials=$(aws sts assume-role \
--role-arn $1 \
--serial-number $2 \
--role-session-name $3 \
--token-code $4)
export AWS_ACCESS_KEY_ID=$(echo $credentials \
| jq '.Credentials.AccessKeyId' \
| xargs)
export AWS_SECRET_ACCESS_KEY=$(echo $credentials \
| jq '.Credentials.SecretAccessKey' \
| xargs)
export AWS_SESSION_TOKEN=$(echo $credentials \
| jq '.Credentials.SessionToken' \
| xargs)