Skip to content

Instantly share code, notes, and snippets.

@davespanton
Last active June 12, 2017 16:49
Show Gist options
  • Save davespanton/7c701a003ef9c135ac02d4fb7a2b37c2 to your computer and use it in GitHub Desktop.
Save davespanton/7c701a003ef9c135ac02d4fb7a2b37c2 to your computer and use it in GitHub Desktop.
#! /bin/bash
# Usage:
#
# Set $MFA_ARN to be your mfa device's arn from AWS. (Maybe hardcode this if running all the time).
# Run `source aws_temp_creds.sh` and enter a valid mfa code when prompted.
set -e
if [ -z ${MFA_ARN+x} ]; then echo "MFA_ARN is unset"; exit 1; fi
echo "Unsetting existing AWS env vars..."
for i in $(env | grep AWS | cut -f 1 -d "="); do
unset $i
done
read -p "MFA code: " mfa_code
aws_creds=( $(aws sts get-session-token --duration 129600 --serial-number $MFA_ARN --token-code $mfa_code --output text | awk '{printf "%s %s %s", $2, $4, $5}') )
if [ ${#aws_creds[@]} -ne 3 ]; then exit 1; fi
export AWS_ACCESS_KEY_ID="${aws_creds[0]}"
export AWS_SECRET_ACCESS_KEY="${aws_creds[1]}"
export AWS_SESSION_TOKEN="${aws_creds[2]}"
export AWS_SECURITY_TOKEN="${aws_creds[2]}"
echo -e "All set. Now using $aws_creds[0].\n:D"
#! /bin/bash
# Version which stores credentials in ~/.aws/credentials to enable sharing between shell session.
#
# Set $MFA_ARN to be your mfa device's arn from AWS.
#
# Usage: `./aws_creds_file.sh`
#
# NOTE: DO NOT USE if you store your default credentials in ~/.aws/credentials ([default] section). It will delete them.
# This script assumes you store your default credentials in ~/.aws/config, and use ~/.aws/credentials file for temporary creds,
# and/or other named profiles.
#! /bin/bash
set -e
if [ -z ${MFA_ARN+x} ]; then echo "MFA_ARN is unset"; exit 1; fi
read -p "MFA code: " mfa_code
if [ -z ${mfa_code+x} ]; then echo "mfa_code file?!"; exit 1; fi
echo "Clobbering default profile in ~/.aws/credentials file"
perl -i -00ne 'print unless /default/' ~/.aws/credentials
aws_creds=( $(aws sts get-session-token --duration 129600 --serial-number $MFA_ARN --token-code $mfa_code --output text | awk '{printf "%s %s %s", $2, $4, $5}') )
if [ ${#aws_creds[@]} -ne 3 ]; then exit 1; fi
cat << EOF >> ~/.aws/credentials
[default]
aws_access_key_id = ${aws_creds[0]}
aws_secret_access_key = ${aws_creds[1]}
aws_session_token = ${aws_creds[2]}
aws_security_token = ${aws_creds[2]}
region = eu-west-1
EOF
echo -e "All set. Now using ${aws_creds[0]}.\n:D"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment