Skip to content

Instantly share code, notes, and snippets.

@marcosnils
Last active March 19, 2021 17:34
Show Gist options
  • Save marcosnils/289fdc37d4f9b7f07f289eedfa9d2f4b to your computer and use it in GitHub Desktop.
Save marcosnils/289fdc37d4f9b7f07f289eedfa9d2f4b to your computer and use it in GitHub Desktop.
Simple script to use MFA using AWS cli.
#!/bin/bash
# shellcheck disable=SC2102
set -euo pipefail
renew_creds() {
unset AWS_ACCESS_KEY_ID
unset AWS_SECRET_ACCESS_KEY
unset AWS_SESSION_TOKEN
unset AWS_MFA_TOKEN_EXPIRATION
DEVICE=$(aws iam list-mfa-devices --query "MFADevices[0].SerialNumber" --output text)
read -r -p "Enter MFA token: "
while read -r exp secret key token; do
export AWS_ACCESS_KEY_ID="$key"
export AWS_SECRET_ACCESS_KEY="$secret"
export AWS_SESSION_TOKEN="$token"
export AWS_MFA_TOKEN_EXPIRATION="$exp"
done < <(aws sts get-session-token \
--serial-number "$DEVICE" \
--token-code "$REPLY" \
--query Credentials.[Expiration,SecretAccessKey,AccessKeyId,SessionToken] \
--output text)
cat <<EOF > $HOME/.aws/mfa_creds
export AWS_MFA_TOKEN_EXPIRATION="$AWS_MFA_TOKEN_EXPIRATION"
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"
EOF
}
# shellcheck disable=SC1091
source $HOME/.aws/mfa_creds 2>/dev/null || renew_creds
localdate=$(TZ=UTC date +%Y-%m-%dT%H:%M:%SZ)
[[ "$localdate" < "$AWS_MFA_TOKEN_EXPIRATION" ]] || renew_creds
if [[ $# -eq 0 ]]; then
echo "export AWS_ACCESS_KEY_ID=$AWS_ACCESS_KEY_ID"
echo "export AWS_SECRET_ACCESS_KEY=$AWS_SECRET_ACCESS_KEY"
echo "export AWS_SESSION_TOKEN=$AWS_SESSION_TOKEN"
exit 0
fi
aws "$@"
@glazari
Copy link

glazari commented Mar 13, 2020

I had to add quotes on the Device query to make it work for me
aws iam list-mfa-devices --query "MFADevices[0].SerialNumber" --output text
Rather than
aws iam list-mfa-devices --query MFADevices[0].SerialNumber --output text

Not sure if this has to do with the fact that I use zsh, no bash, but it might be usefull for someone

@marcosnils
Copy link
Author

Interesting... Adding quotes makes sense. Just updated the gist.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment