Created
February 12, 2021 11:49
-
-
Save aksel/3520cd5254fa4439e305447f39d4b2a0 to your computer and use it in GitHub Desktop.
Script for authenticating using MFA for the AWS CLI. Variables are exported, so the script can be sourced.
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 | |
MFA_DEVICE=$1 | |
if [ -z "$MFA_DEVICE" ]; then | |
echo "MFA device ARN not specified." >&2 | |
exit 1 | |
fi | |
# Prompt for OTP | |
OTP= | |
while true; do | |
echo -n "Input OTP: " | |
read -rs OTP | |
echo | |
if [[ $OTP =~ ^[0-9]{6}$ ]]; then | |
break | |
fi | |
echo "OTP must be a six-digit number." >&2 | |
done | |
# Fetch credentials, and export them. | |
CREDENTIALS=$(aws --profile="$AWS_PROFILE" sts get-session-token --serial-number "$MFA_DEVICE" --token-code "$OTP") | |
AWS_ACCESS_KEY_ID=$(jq -r ".Credentials.AccessKeyId" <<<"$CREDENTIALS") | |
AWS_SECRET_ACCESS_KEY=$(jq -r ".Credentials.SecretAccessKey" <<<"$CREDENTIALS") | |
AWS_SESSION_TOKEN=$(jq -r ".Credentials.SessionToken" <<<"$CREDENTIALS") | |
echo "AWS_ACCESS_KEY_ID=$AWS_ACCESS_KEY_ID" | |
echo "AWS_SECRET_ACCESS_KEY=$AWS_SECRET_ACCESS_KEY" | |
echo "AWS_SESSION_TOKEN=$AWS_SESSION_TOKEN" | |
export AWS_ACCESS_KEY_ID | |
export AWS_SECRET_ACCESS_KEY | |
export AWS_SESSION_TOKEN |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment