Skip to content

Instantly share code, notes, and snippets.

@virajkanwade
Last active August 12, 2020 17:54
Show Gist options
  • Save virajkanwade/022ceb7ea4a8519d1037744a2bcaaaf2 to your computer and use it in GitHub Desktop.
Save virajkanwade/022ceb7ea4a8519d1037744a2bcaaaf2 to your computer and use it in GitHub Desktop.
AWS CLI with MFA
#!/bin/bash
# source ./aws_mfa_creds.sh <MFA KEY> <ORIG AWS PROFILE NAME - optional, default>
# https://aws.amazon.com/premiumsupport/knowledge-center/authenticate-mfa-cli/
# Works on MacOS. Might need changes to date command params for linux
if [ -n "$AWS_SESSION_TOKEN_EXPIRATION" ]
then
if [ $(date -jf "%Y-%m-%dT%H:%M:%SZ" "$AWS_SESSION_TOKEN_EXPIRATION" +"%s") -gt $(date +"%s") ]
then
echo "Existing creds valid till $AWS_SESSION_TOKEN_EXPIRATION"
return 0
fi
fi
AWS_PROFILE=${2:-default}
echo $AWS_PROFILE
ARN=$(aws --profile $AWS_PROFILE sts get-caller-identity --output text | awk '{ print $2 }' | sed 's/user/mfa/')
echo $ARN
CREDS=$(aws --profile $AWS_PROFILE sts get-session-token --serial-number $ARN --output text --token-code $1)
if [ $(echo -e $CREDS | wc -w) -ne 5 ]
then
echo "$CREDS"
else
unset AWS_ACCESS_KEY_ID
unset AWS_SECRET_ACCESS_KEY
unset AWS_SESSION_TOKEN
unset AWS_SESSION_TOKEN_EXPIRATION
export AWS_ACCESS_KEY_ID=$(echo -e $CREDS | awk '{ print $2 }')
export AWS_SECRET_ACCESS_KEY=$(echo -e $CREDS | awk '{ print $4 }')
export AWS_SESSION_TOKEN=$(echo -e $CREDS | awk '{ print $5 }')
export AWS_SESSION_TOKEN_EXPIRATION=$(echo -e $CREDS | awk '{ print $3 }')
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment