Created
June 2, 2017 13:30
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
aws_set_mfa_env_vars () { | |
# This assumes you have the aws-cli tool already set up and working: | |
# http://docs.aws.amazon.com/cli/latest/userguide/cli-chap-welcome.html | |
# | |
# This is the ARN for your MFA device, it's found in the "Security | |
# Credentials" tab of your IAM user summary | |
mfa_arn="arn:aws:iam::01234567890:mfa/your.name.here" | |
# 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)" | |
else | |
mfa_totp=$1 | |
# 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: | |
# 1: "CREDENTIALS" | |
# 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... | |
fi | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
If you add this function to your shell's rc file (e.g.
~/.bashrc
) then you can run it like so……and your current shell will get the following temporary environment variables:
Note that the
AWS_ACCESS_KEY_ID
andAWS_SECRET_ACCESS_KEY
are also temporary and will not match whatever your permanent creds are in~/.aws/credentials
. For theaws
CLI tool, env vars take precedence over the vars in the creds file, so any furtheraws
commands will use the temporary MFA-enabled creds. Here's an example session: