Skip to content

Instantly share code, notes, and snippets.

@gitjonez
Last active December 22, 2023 06:53
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save gitjonez/ee7962a4f38088ccd7fe5604e034e3cd to your computer and use it in GitHub Desktop.
Save gitjonez/ee7962a4f38088ccd7fe5604e034e3cd to your computer and use it in GitHub Desktop.
Function to set AWS_ temporary token variables with MFA code

awsmfa

A [ba|z]sh function to fetch temporary access credentials for awscli

Inspired by this 'ogavrisevs' gist

Requires

  • awscli (and configured config, credentials files)
  • Working AWS account MFA and the device ARN
  • awk

Installation

  • Paste this code in ~/.profile, .zshrc, ...
  • or, make a file out of it, e.g. ~/.awsmfa and in .profile-ish source from profile, rc
  • Update lines 9,10,11 with your info and desired settings

Example

after defining the function:

bash-5.2$ awsmfa
MFA Code: 712717

bash-5.2$ aws ec2 describe-vpcs | jq -r '.Vpcs[] | [.VpcId, .CidrBlock] | @tsv'
vpc-05f640d1978a16de0	172.31.0.0/16
vpc-076a8e5660e066e69	192.168.0.0/16
awsmfa () {
# Get temporary credentials, read MFA code, and set vars
# Create a file with this and `source` (recommended: in your shell profile
# .bash_profile, .profile, .zshrc, ...)
# Options: [-v] Verbose: Print stuff
#
# Set your preferences here:
HOURS=4
MFA_ID=arn:aws:iam::123456789012:mfa/pixel-5a
export AWS_PROFILE=aws-profile-name
# end preferences
DURATION=$(($HOURS * 60 * 60))
echo -n 'MFA Code: '
read MFA_CODE
unset AWS_ACCESS_KEY_ID AWS_SECRET_ACCESS_KEY AWS_SESSION_TOKEN
read AWS_ACCESS_KEY_ID AWS_SECRET_ACCESS_KEY AWS_SESSION_TOKEN <<< \
$( aws sts get-session-token \
--duration $DURATION \
--serial-number $MFA_ID \
--token-code $MFA_CODE \
--output text | awk '{ print $2, $4, $5 }')
if [[ $AWS_SESSION_TOKEN ]]; then
export AWS_ACCESS_KEY_ID AWS_SECRET_ACCESS_KEY AWS_SESSION_TOKEN
if [[ "$?" == "0" && $# -ge 1 && "$1" == '-v' ]]; then
echo "MFA Identifier:\t$MFA_ID"
echo "Duration hours:\t${HOURS}, seconds: $DURATION"
echo "AWS_PROFILE:\t$AWS_PROFILE"
echo "AWS_ACCESS_KEY_ID:\t$AWS_ACCESS_KEY_ID"
echo "AWS_SECRET_ACCESS_KEY:\t$AWS_SECRET_ACCESS_KEY"
echo "AWS_SESSION_TOKEN:\t$AWS_SESSION_TOKEN"
fi
else
echo "\n*Error*"
echo "Duration hours:\t${HOURS}, seconds: $DURATION"
echo "HOURS:\t$HOURS"
echo "DURATION:\t$DURATION"
echo "MFA_CODE:\t$MFA_CODE"
echo "AWS_PROFILE:\t'$AWS_PROFILE'"
echo "MFA_ARN:\t'$MFA_ID'"
fi
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment