Skip to content

Instantly share code, notes, and snippets.

@beaufour
Last active September 28, 2020 19:16
Show Gist options
  • Save beaufour/a7546c382bc9c6181d7a9600ce02a11f to your computer and use it in GitHub Desktop.
Save beaufour/a7546c382bc9c6181d7a9600ce02a11f to your computer and use it in GitHub Desktop.
AWS STS authenticator script
#!/bin/bash
#
# Gets a temporary token from STS and stores it in the default AWS profile.
#
# The script needs two environment variables set:
# * AWS_MFA_ARN: ARN of your MFA device (look up in IAM)
# * AWS_STS_PROFILE: aws cli user profile that allows you to call STS
#
# To use it, you also need to have two profiles in your ~/.aws/credentials file. The default and the
# one that contains your permanent access tokens. Like this for example:
#
# --------------------
# [default]
#
# [bh]
# aws_access_key_id = XXX
# aws_secret_access_key = YYY
# --------------------
#
# `default` will be filled in by this script, and you would set
#
# AWS_STS_PROFILE=bh
#
# (This script was based on : https://gist.github.com/ogavrisevs/2debdcb96d3002a9cbf2 )
#
set -e
AWS_CLI=`which aws`
if [ $? -ne 0 ]; then
echo "AWS CLI is not installed; exiting"
exit 1
fi
if [ $# -ne 1 ]; then
echo "Usage: $0 <MFA_TOKEN_CODE>"
echo "Where:"
echo " <MFA_TOKEN_CODE> = Code from the MFA device"
exit 1
fi
MFA_TOKEN_CODE=$1
if [ -z "$AWS_MFA_ARN" ]
then
echo AWS_MFA_ARN is not set
exit 1
fi
if [ -z "$AWS_STS_PROFILE" ]
then
echo AWS_STS_PROFILE is not set
exit 1
fi
read AWS_ACCESS_KEY_ID AWS_SECRET_ACCESS_KEY AWS_SESSION_TOKEN <<< \
$( aws --profile $AWS_STS_PROFILE sts get-session-token \
--serial-number $AWS_MFA_ARN \
--token-code $MFA_TOKEN_CODE \
--output text | awk '{ print $2, $4, $5 }')
if [ -z "$AWS_ACCESS_KEY_ID" ]
then
echo Could not get AWS credentials
exit 1
fi
`aws configure set aws_access_key_id "$AWS_ACCESS_KEY_ID"`
`aws configure set aws_secret_access_key "$AWS_SECRET_ACCESS_KEY"`
`aws configure set aws_session_token "$AWS_SESSION_TOKEN"`
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment