Skip to content

Instantly share code, notes, and snippets.

Created June 2, 2017 13:30
Show Gist options
  • Save hjst/df9d31816a501187e2d99f481e63a921 to your computer and use it in GitHub Desktop.
Save hjst/df9d31816a501187e2d99f481e63a921 to your computer and use it in GitHub Desktop.
Shell function to set temporary MFA session env vars for AWS CLI access
aws_set_mfa_env_vars () {
# This assumes you have the aws-cli tool already set up and working:
# This is the ARN for your MFA device, it's found in the "Security
# Credentials" tab of your IAM user summary
# This function only takes one parameter: the current TOTP value
# shown on your MFA device (will be a 6 digit number)
if [ $# -lt 1 ]; then
echo 1>&2 "Missing one-time-password (6 digits)"
# Firstly, grab the tab-separated creds response via aws-cli
cred_string=$(aws --output=text sts get-session-token \
--serial-number "${mfa_arn}" --token-code "${mfa_totp}")
# Response field ordering:
# 2: AccessKeyId
# 3: Expiry timestamp
# 4: SecretAccessKey
# 5: SessionToken
AccessKeyId=$(echo "${cred_string}" | cut -f 2)
SecretAccessKey=$(echo "${cred_string}" | cut -f 4)
SessionToken=$(echo "${cred_string}" | cut -f 5)
export AWS_ACCESS_KEY_ID=${AccessKeyId}
export AWS_SECRET_ACCESS_KEY=${SecretAccessKey}
export AWS_SESSION_TOKEN=${SessionToken}
# TODO: export the timestamp somewhere and check it before running
# this function? adding a countdown timer to the PS1 prompt
# would be cute...
Copy link

hjst commented Jun 2, 2017

If you add this function to your shell's rc file (e.g. ~/.bashrc) then you can run it like so…

$ aws_set_mfa_env_vars 619367

…and your current shell will get the following temporary environment variables:

$ env | grep -i aws

Note that the AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY are also temporary and will not match whatever your permanent creds are in ~/.aws/credentials. For the aws CLI tool, env vars take precedence over the vars in the creds file, so any further aws commands will use the temporary MFA-enabled creds. Here's an example session:

$ aws iam list-users
USERS   arn:aws:iam::063549794[...]
USERS   arn:aws:iam::063549794[...]

$ aws ec2 describe-instances
An error occurred (UnauthorizedOperation) when calling the DescribeInstances operation:
You are not authorized to perform this operation.

$ aws_set_mfa_env_vars 525403
$ aws ec2 describe-instances
RESERVATIONS    06352844782    r-08cc1ddce0ed80d4
INSTANCES       0       x86_64  JiPkS14964072317[...]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment