Skip to content

Instantly share code, notes, and snippets.

@keymon
Last active January 5, 2017 16:48
Show Gist options
  • Save keymon/025226011bafe6aa0d32e308e5f3d083 to your computer and use it in GitHub Desktop.
Save keymon/025226011bafe6aa0d32e308e5f3d083 to your computer and use it in GitHub Desktop.
Get temporary credentials from AWS using a MFA token, also assuming role: you can assume a role ⁠⁠⁠⁠./create-token-role.sh elasticache-broker-spike-role⁠⁠⁠⁠ or create new tokens for yourself ⁠⁠⁠⁠./create-token-role.sh me 900⁠⁠⁠⁠
#!/bin/bash
SCRIPT_NAME="$0"
usage() {
cat <<EOF
Creates a set of tokens assuming the given role. Use "me" as role to simply generate a new session token for your user.
Usage:
$SCRIPT_NAME <role name> [duration in seconds]
EOF
exit 1
}
role_name="$1"
duration="${2:-3600}"
if [ -z "${role_name}" ]; then
usage
fi
read -p "Token code: " token
user_arn=$(aws sts get-caller-identity --query Arn --output text)
arn_prefix=${user_arn%:*}
token_arn=${user_arn/:user/:mfa}
if [ "${role_name}" == "me" ]; then
echo "Creating a new session token for ${user_arn}..."
aws sts get-session-token \
--serial-number "${token_arn}" \
--duration-seconds "${duration}" \
--output text \
--query [Credentials.AccessKeyId,Credentials.SecretAccessKey,Credentials.SessionToken] \
--token-code "${token}" | \
awk '{ print "export AWS_ACCESS_KEY_ID=\"" $1 "\"\n" "export AWS_SECRET_ACCESS_KEY=\"" $2 "\"\n" "export AWS_SESSION_TOKEN=\"" $3 "\"" }'
else
echo "Creating new session token for role ${role_name}..."
aws sts assume-role \
--role-arn "${arn_prefix}:role/${role_name}" \
--role-session-name "${role_name}_mfa_command_line" \
--serial-number "${token_arn}" \
--duration-seconds "${duration}" \
--output text \
--query [Credentials.AccessKeyId,Credentials.SecretAccessKey,Credentials.SessionToken] \
--token-code "${token}" | \
awk '{ print "export AWS_ACCESS_KEY_ID=\"" $1 "\"\n" "export AWS_SECRET_ACCESS_KEY=\"" $2 "\"\n" "export AWS_SESSION_TOKEN=\"" $3 "\"" }'
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment