Created
June 17, 2015 18:56
-
-
Save sneak/740dfe13f81deafbef7a to your computer and use it in GitHub Desktop.
shell script to ease MFA use with aws role assumption
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
#!/bin/bash | |
if [[ $# -ne 1 ]]; then | |
echo "usage: $0 <rolename> (e.g. \`$0 EngineerProd\`)" > /dev/stderr | |
exit 127 | |
fi | |
if ! which jq 2>&1 > /dev/null ; then | |
echo "$0 error: Please install 'jq'." > /dev/stderr | |
exit 127 | |
fi | |
if ! which aws 2>&1 > /dev/null ; then | |
echo "$0 error: Please install 'awscli'." > /dev/stderr | |
exit 127 | |
fi | |
USERARN="$(aws --output json iam get-user | jq -r .User.Arn)" | |
if [[ -z "$USERARN" ]]; then | |
echo "$0 error: unable to determine AWS IAM user. Did you run 'aws configure'?" > \ | |
/dev/stderr | |
exit 128 | |
fi | |
IAMUSER="$(basename $USERARN)" | |
ACCOUNT="$(echo $USERARN | cut -d: -f5)" | |
REGION="us-east-1" | |
ROLEARN="arn:aws:iam::$ACCOUNT:role/$1" | |
MFAARN="arn:aws:iam::$ACCOUNT:mfa/$IAMUSER" | |
echo -n "Enter MFA token code for $MFAARN: " | |
read -s MFACODE | |
echo "" | |
RESP="$(aws --region $REGION sts assume-role \ | |
--role-arn $ROLEARN \ | |
--role-session-name assumption-$IAMUSER-$(date +%s) \ | |
--serial-number $MFAARN --token-code $MFACODE 2> /dev/null )" | |
AKI="$(echo $RESP | jq -r .Credentials.AccessKeyId)" | |
if [[ -z "$AKI" ]]; then | |
echo "Failure." > /dev/null | |
exit 129 | |
fi | |
SAK="$(echo $RESP | jq -r .Credentials.SecretAccessKey)" | |
ST="$(echo $RESP | jq -r .Credentials.SessionToken)" | |
echo "export AWS_ACCESS_KEY_ID=\"$AKI\"" | |
echo "export AWS_SECRET_ACCESS_KEY=\"$SAK\"" | |
echo "export AWS_SESSION_TOKEN=\"$ST\"" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment