Skip to content

Instantly share code, notes, and snippets.

@TimothyLoyer
Created April 22, 2020 20:48
Show Gist options
  • Save TimothyLoyer/81b3d2fd432c4b41fedd3b316fa065ee to your computer and use it in GitHub Desktop.
Save TimothyLoyer/81b3d2fd432c4b41fedd3b316fa065ee to your computer and use it in GitHub Desktop.
Bash script to set MFA IAM session in environment variables
#!/bin/bash
#description : Set MFA session in environment variables
#usage : source mfa-env [token-from-mfa-device]
#requirements : Install aws-cli v2
mfa_config=~/.aws/mfa
mfa_device_arn=""
mfa_token="${1-}"
if [ ! -f $mfa_config ]; then
echo "Please create a config file at ~/.aws/mfa!"
echo "Config should contain line with \"mfa-device = mfa-device-arn\"."
echo
return 1
fi
while IFS= read -r line; do
if [[ $line == mfa-device* ]]; then
mfa_device_arn="${line/mfa-device = /}"
fi
done < $mfa_config
if [[ "$mfa_device_arn" == "" ]]; then
echo "Config should contain line with \"mfa-device = mfa-device-arn\"."
return 2
fi
if [[ "$mfa_token" == "" ]]; then
echo "\`mfa-env\` must be called with the current MFA token from your device!"
return 3
fi
# Can't run get-session-token with session credentials!
unset AWS_ACCESS_KEY_ID
unset AWS_SECRET_ACCESS_KEY
unset AWS_SESSION_TOKEN
credentials=($(aws sts get-session-token --serial-number "$mfa_device_arn" --token-code "$mfa_token" --output text))
[ $? -ne 0 ] && return 4
export AWS_ACCESS_KEY_ID="${credentials[2]}"
export AWS_SECRET_ACCESS_KEY="${credentials[4]}"
export AWS_SESSION_TOKEN="${credentials[5]}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment