Skip to content

Instantly share code, notes, and snippets.

@dinvlad
Created October 25, 2016 23:32
Show Gist options
  • Save dinvlad/d1bc0a45419abc277eb86f2d1ce70625 to your computer and use it in GitHub Desktop.
Save dinvlad/d1bc0a45419abc277eb86f2d1ce70625 to your computer and use it in GitHub Desktop.
Get session token for virtual MFA-enabled actions through AWS CLI
#!/bin/bash
# Thanks to MattJ at:
# http://www.brassmill.net/2015/10/using-the-aws-cli-with-roles-security-token-service-and-mfa/
#
# User must have 'iam:GetUser' permission on themselves that doesn't require MFA
[ -z $1 ] && echo "Please enter your MFA code" && exit 1
user=$(aws iam get-user \
--query 'User.Arn' \
--output text \
) || exit 1
profile=$(echo $user | cut -f2 -d '/')
serial=$(echo $user | sed 's/:user/:mfa/')
output=$(aws sts get-session-token \
--query 'Credentials.[SecretAccessKey,AccessKeyId,SessionToken]' \
--output text \
--serial-number $serial \
--token-code $1 \
) || exit 1
aws_secret_access_key=$(echo $output | cut -f1 -d ' ')
aws_access_key_id=$(echo $output | cut -f2 -d ' ')
aws_session_token=$(echo $output | cut -f3 -d ' ')
aws configure set profile.$profile.aws_access_key_id $aws_access_key_id
aws configure set profile.$profile.aws_secret_access_key $aws_secret_access_key
aws configure set profile.$profile.aws_session_token $aws_session_token
@dinvlad
Copy link
Author

dinvlad commented Jan 1, 2022

Glad it still does! I haven't touched it in a while :-)

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