Skip to content

Instantly share code, notes, and snippets.

@scottzach1
Created September 3, 2024 22:47
Show Gist options
  • Save scottzach1/55e60dcf6af1fff3825f8235f19580e7 to your computer and use it in GitHub Desktop.
Save scottzach1/55e60dcf6af1fff3825f8235f19580e7 to your computer and use it in GitHub Desktop.
AWS CLI MFA
#!/bin/bash
# Set the profile you want to use for MFA
SRC_PROFILE="default"
MFA_PROFILE="default-mfa"
MFA_DEVICE_ARN=$(aws configure get aws_mfa_device --profile "$SRC_PROFILE")
if [ -z "$MFA_DEVICE_ARN" ]; then
echo "Error: MFA device ARN not found in the ~/.aws/credentials file for profile $SRC_PROFILE"
exit 1
fi
if [ -z "$1" ]; then
read -rp 'MFA: ' totp
else
totp="$1"
fi
token="$(aws sts get-session-token --serial-number "$MFA_DEVICE_ARN" --token-code "$totp" --profile "$SRC_PROFILE")"
accessKey="$(echo "$token" | jq -r ".Credentials.AccessKeyId")"
secretKey="$(echo "$token" | jq -r ".Credentials.SecretAccessKey")"
sessionTk="$(echo "$token" | jq -r ".Credentials.SessionToken")"
aws configure set aws_access_key_id "$accessKey" --profile "$MFA_PROFILE"
aws configure set aws_secret_access_key "$secretKey" --profile "$MFA_PROFILE"
aws configure set aws_session_token "$sessionTk" --profile "$MFA_PROFILE"
echo "Loaded profile $MFA_PROFILE:"
aws sts get-caller-identity --profile "$MFA_PROFILE"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment