Last active
December 2, 2017 09:40
-
-
Save StyleT/3d0b5f02c84ae33afadb677f646ca599 to your computer and use it in GitHub Desktop.
Retrieves a set of temporary MFA-signed credentials for an AWS account or IAM user.
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
#!/usr/bin/env bash | |
# Retrieves a set of temporary MFA-signed credentials for an AWS account or IAM user. | |
# | |
# To use it you should save MFA ARN to the profile config: | |
# aws configure set mfa_serial_number <ARN_OF_MFA> [--profile disco] | |
# | |
# Once the temp token is obtained, profile with "_mfa" postfix will be created | |
# Example: ./aws_mfa.sh disco 345324 - profile "disco_mfa" will be created with obtained creds | |
AWS_CLI=`which aws` | |
if [ $? -ne 0 ]; then | |
echo "AWS CLI is not installed; exiting" | |
exit 1 | |
fi | |
if [ $# -ne 2 ]; then | |
echo "Usage: $0 <AWS_CLI_PROFILE> <MFA_TOKEN_CODE>" | |
echo "Where:" | |
echo " <AWS_CLI_PROFILE> = aws-cli profile usually in $HOME/.aws/config" | |
echo " <MFA_TOKEN_CODE> = Code from virtual MFA device" | |
exit 2 | |
fi | |
AWS_CLI_PROFILE=$1 | |
MFA_TOKEN_CODE=$2 | |
AWS_MFA_PROFILE="${AWS_CLI_PROFILE}_mfa" | |
AWS_MFA_ARN=$(aws configure get mfa_serial_number --profile $AWS_CLI_PROFILE) | |
if [ $? -ne 0 ]; then | |
echo "MFA ARN is not configured; exiting" | |
echo "How to fix this issue:" | |
echo " aws configure set mfa_serial_number <ARN_OF_MFA> [--profile disco]" | |
exit 1 | |
fi | |
SESSION_OUT=($(aws --profile $AWS_CLI_PROFILE sts get-session-token --duration 129600 --serial-number $AWS_MFA_ARN --token-code $MFA_TOKEN_CODE --output text)) | |
if [ $? -ne 0 ]; then | |
echo "Error during retrieval of the temporary MFA-signed credentials!" | |
echo "Make sure that you have entered correct MFA_TOKEN_CODE" | |
exit 1 | |
fi | |
aws configure set aws_access_key_id ${SESSION_OUT[1]} --profile $AWS_MFA_PROFILE | |
aws configure set aws_secret_access_key ${SESSION_OUT[3]} --profile $AWS_MFA_PROFILE | |
aws configure set aws_session_token ${SESSION_OUT[4]} --profile $AWS_MFA_PROFILE | |
AWS_REGION=$(aws configure get region --profile $AWS_CLI_PROFILE) | |
if [ $? -eq 0 ]; then | |
aws configure set region $AWS_REGION --profile $AWS_MFA_PROFILE | |
else | |
aws configure set region "" --profile $AWS_MFA_PROFILE | |
fi | |
echo "Profile \"$AWS_MFA_PROFILE\" with temporary MFA-signed credentials created." |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment