Skip to content

Instantly share code, notes, and snippets.

@lparkes
Created August 24, 2020 23:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lparkes/d186bf2397ef5419c1b460525a7bc488 to your computer and use it in GitHub Desktop.
Save lparkes/d186bf2397ef5419c1b460525a7bc488 to your computer and use it in GitHub Desktop.
#!/bin/sh
# This script acquires a temporary AWS session token for you.
# This is useful for two reasons:
# 1) It means you don't get pestered for an MFA token every time you
# run an AWS CLI command.
# 2) It means you can run batch programs that can't request an MFA
# token, but which access AWS resources protected by mandatory
# MFA policies. The session token is generated from an MFA token,
# and so it complies with the mandatory MFA policies. Terraform
# is a commonly used tool that fits into this category.
#
# Put the line ``sts() { eval $(do_sts $1); }`` in your profile
# somewhere and then just run ``sts`` when you want to start doing AWS
# stuff. The tokens will last for several hours. Put your own email
# address in this script as well.
#
# This script requires the ``json`` command from Trent Mick
# (https://github.com/trentm/json).
set -e
email=XYZZY@zfrobco.com
mfa_serial=arn:aws:iam::133257548191:mfa/${email}
echo -n Please enter the MFA code for ${email}:' ' 1>&2
read mfa_code
unset AWS_SESSION_TOKEN AWS_ACCESS_KEY_ID AWS_SECRET_ACCESS_KEY
if [ x"$1" = x ]
then
session_codes=$(aws sts get-session-token --serial-number "${mfa_serial}" --token-code "${mfa_code}")
else
session_codes=$(aws sts assume-role --duration-seconds 3600 --role-arn $1 --role-session-name ${email} --serial-number "${mfa_serial}" --token-code "${mfa_code}")
fi
echo export AWS_ACCESS_KEY_ID=$(echo "${session_codes}" | json Credentials.AccessKeyId)
echo export AWS_SECRET_ACCESS_KEY=$(echo "${session_codes}" | json Credentials.SecretAccessKey)
echo export AWS_SESSION_TOKEN=$(echo "${session_codes}" | json Credentials.SessionToken)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment