Last active
July 2, 2018 19:50
-
-
Save koleror/a6614f12be8f716e7f16a465a8d32d9f to your computer and use it in GitHub Desktop.
Regenerate two factor tokens for AWS and add them to your environment
This file contains 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 | |
command -v aws | |
if [[ $? != 0 ]]; then | |
echo "Please install awscli and try again" | |
return; | |
fi | |
set -e | |
SERIAL="${AWS_MFA_SERIAL_NUMBER?Please set AWS_MFA_SERIAL_NUMBER in your environment first}" | |
unset AWS_ACCESS_KEY_ID | |
unset AWS_SECRET_ACCESS_KEY | |
unset AWS_SESSION_TOKEN | |
if [ -f ~/.aws/credentials.bkp ] | |
then | |
echo "Reseting credentials from backup..." | |
cp ~/.aws/credentials.bkp ~/.aws/credentials | |
else | |
echo "Creating credentials backup" | |
cp ~/.aws/credentials ~/.aws/credentials.bkp | |
fi | |
if [ "$#" == "1" ]; then | |
TOKEN=$1 | |
else | |
read -p "Please enter your token: " TOKEN || TOKEN = "null"; | |
fi | |
if [[ TOKEN == "null" ]]; then | |
return; | |
fi | |
set +e | |
credentials=`aws sts get-session-token --serial-number "$SERIAL" --token-code $TOKEN` || return; | |
set -e | |
AWS_ACCESS_KEY_ID=`python -c "import json; print json.loads(\"\"\"$credentials\"\"\")['Credentials']['AccessKeyId']"` | |
AWS_SECRET_ACCESS_KEY=`python -c "import json; print json.loads(\"\"\"$credentials\"\"\")['Credentials']['SecretAccessKey']"` | |
AWS_SESSION_TOKEN=`python -c "import json; print json.loads(\"\"\"$credentials\"\"\")['Credentials']['SessionToken']"` | |
EXPIRATION=`python -c "import json; from datetime import datetime; date = json.loads(\"\"\"$credentials\"\"\")['Credentials']['Expiration']; print str(datetime.strptime(date, '%Y-%m-%dT%H:%M:%SZ')).replace(' ', ' at ')"` | |
export AWS_ACCESS_KEY_ID="$AWS_ACCESS_KEY_ID" | |
export AWS_SECRET_ACCESS_KEY="$AWS_SECRET_ACCESS_KEY" | |
export AWS_SESSION_TOKEN="$AWS_SESSION_TOKEN" | |
echo "[default] | |
aws_access_key_id = $AWS_ACCESS_KEY_ID | |
aws_secret_access_key = $AWS_SECRET_ACCESS_KEY | |
aws_session_token = $AWS_SESSION_TOKEN" > ~/.aws/credentials | |
echo Access will expire on $EXPIRATION | |
echo 'Two factor acces key added to your environment. Enjoy!' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment