Skip to content

Instantly share code, notes, and snippets.

@limed
Forked from sneak/assumeawsrole
Created October 15, 2015 23:51
Show Gist options
  • Save limed/28fd12dbfcd5fe3e590e to your computer and use it in GitHub Desktop.
Save limed/28fd12dbfcd5fe3e590e to your computer and use it in GitHub Desktop.
shell script to ease MFA use with aws role assumption
#!/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