Last active
March 26, 2020 18:13
-
-
Save wallentx/b3343eb37e7ccfb6b4a85b6e1681ecba to your computer and use it in GitHub Desktop.
MFA helper for AWS CLI
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 | |
| set -e | |
| AWS_ENV=$1 | |
| TMPAUTH=$(mktemp /tmp/authXXXXXXXX) | |
| if [[ -z $AWS_ENV ]]; then | |
| echo "No profile specified" | |
| echo "Usage: aws-profile <profile>" | |
| exit 1 | |
| fi | |
| SERIAL=$(aws --profile $AWS_ENV iam list-mfa-devices --query='MFADevices[].SerialNumber' --output text) | |
| read -p "MFA Code for $AWS_ENV: " TOKEN | |
| # Get AWS CLI token using MFA key | |
| get_token() { | |
| aws --profile $AWS_ENV sts get-session-token \ | |
| --duration 129600 \ | |
| --serial-number $SERIAL \ | |
| --token-code $TOKEN \ | |
| --output json | |
| } | |
| # Write output to mktemp file | |
| get_token > ${TMPAUTH} | |
| # Grab vars from mktemp file | |
| SESS_ID=$(jq -r '.Credentials.AccessKeyId' ${TMPAUTH}) | |
| SESS_KEY=$(jq -r '.Credentials.SecretAccessKey' ${TMPAUTH}) | |
| SESS_TOKEN=$(jq -r '.Credentials.SessionToken' ${TMPAUTH}) | |
| TMPCREDS=$(mktemp /tmp/credsXXXXXXXX) | |
| AWS_CONFIG=$HOME/.aws/config | |
| AWS_CREDS=$HOME/.aws/credentials | |
| # Wipe existing tokenauth creds | |
| sed '/\[tokenauth\]/,$d' $AWS_CREDS > ${TMPCREDS} | |
| # Wipe existing tokenauth profile | |
| sed '/\[profile tokenauth\]/,$d' $AWS_CONFIG > $AWS_CONFIG | |
| # Set tokenauth config profile | |
| # Setting default output to YAML, and no pager here, but set to your own liking | |
| echo -e "[profile tokenauth]" >> $AWS_CONFIG | |
| echo -e "region = us-east-1" >> $AWS_CONFIG | |
| echo -e "output = yaml" >> $AWS_CONFIG | |
| echo -e "cli_pager = " >> $AWS_CONFIG | |
| # Set tokenauth creds profile | |
| echo -e "[tokenauth]" >> ${TMPCREDS} | |
| echo -e "aws_access_key_id = "$SESS_ID"" >> ${TMPCREDS} | |
| echo -e "aws_secret_access_key = "$SESS_KEY"" >> ${TMPCREDS} | |
| echo -e "aws_session_token = "$SESS_TOKEN"" >> ${TMPCREDS} | |
| cat ${TMPCREDS} > ~/.aws/credentials | |
| echo "AWS_PROFILE=tokenauth" > ~/.aws/current_profile | |
| echo -e "alias the following to execute AWS CLI as authed profile:" | |
| echo -e "alias aws='source ~/.aws/current_profile && aws --profile \$AWS_PROFILE'" | |
| # Remove mktemp files | |
| rm -f $TMPAUTH $TMPCREDS | |
| exit |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment