Skip to content

Instantly share code, notes, and snippets.

@radnov
Created June 23, 2021 17:00
Show Gist options
  • Save radnov/91a72cb3cd8c5786ad6b51cf08590fb8 to your computer and use it in GitHub Desktop.
Save radnov/91a72cb3cd8c5786ad6b51cf08590fb8 to your computer and use it in GitHub Desktop.
aws-cli MFA helper
#!/usr/bin/env bash
tempcreds_file="$HOME/.aws/tempcreds"
device="" # <- MFA DEVICE ARN HERE
key_env="AWS_ACCESS_KEY_ID"
secret_env="AWS_SECRET_ACCESS_KEY"
token_env="AWS_SESSION_TOKEN"
duration=3600
export_env_vars () {
tempcreds=$(cat ${tempcreds_file})
export $key_env=$(echo ${tempcreds} | jq -r ".Credentials.AccessKeyId")
export $secret_env=$(echo ${tempcreds} | jq -r ".Credentials.SecretAccessKey")
export $token_env=$(echo ${tempcreds} | jq -r ".Credentials.SessionToken")
}
cleanup () {
unset $key_env
unset $secret_env
unset $token_env
echo "\nTemporary environment variables cleared."
}
if [[ "$#" -eq "0" ]]; then
echo "\nNo arguments supplied. OTP or command required."
return 1
fi
if [[ "$1" = "clear" ]]; then
cleanup
return
fi
if [[ "$1" = "reuse" ]]; then
export_env_vars
echo "\nExisting temporary credentials reused."
return
fi
if [[ -n "$2" ]]; then
duration=$(($2 * 60))
echo "\nSession duration set to $2 minutes."
fi
cleanup
echo "\nRequesting new temporary credentials."
aws sts get-session-token \
--duration-seconds ${duration} \
--serial-number "$device$AWS_PROFILE" \
--token-code $1 > ${tempcreds_file}
# meh
if [ $? -eq 0 ]; then
echo "\nDone! Expiration at $(echo ${tempcreds} | jq -r '.Credentials.Expiration')"
export_env_vars
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment