Skip to content

Instantly share code, notes, and snippets.

@bishopb
Created September 28, 2022 02:07
Show Gist options
  • Save bishopb/89615a4ae7b9608c34ab77e5b9b609bf to your computer and use it in GitHub Desktop.
Save bishopb/89615a4ae7b9608c34ab77e5b9b609bf to your computer and use it in GitHub Desktop.
Simple bash wrapper around the AWS CLI commands necessary to get temporary tokens from AWS STS using an identity with MFA
#!/bin/bash
set -euo pipefail
trap 'echo "Caught SIGINT. Exiting..." >&2; exit 1' INT
tmpfile=$(mktemp)
chmod 600 "${tmpfile}"
trap 'rm -f "${tmpfile}"' EXIT
main() {
local serial="${1:?First argument must be the MFA serial number, available on the AWS web console}"
local duration="${2:-10800}"
local token
token=$(read_token)
get_tmp_creds "${serial}" "${token}" "${duration}" > "${tmpfile}"
local ak sk st ex
ak=$(jq -r .Credentials.AccessKeyId < "${tmpfile}")
sk=$(jq -r .Credentials.SecretAccessKey < "${tmpfile}")
st=$(jq -r .Credentials.SessionToken < "${tmpfile}")
ex=$(jq -r .Credentials.Expiration < "${tmpfile}")
update_creds_file "${ak}" "${sk}" "${st}"
verify_identity
echo "Authenticated. Credentials stored in the 'mfa' profile and expire at ${ex}."
}
read_token() {
local max=3
for i in $(seq 1 "${max}"); do
read -r -n 6 -p "Token (attempt #${i} of ${max}): " token
echo >&2
if [[ "${token}" =~ ^[0-9][0-9][0-9][0-9][0-9][0-9]$ ]]; then
echo "${token}"
return 0
else
echo 'Token input must be exactly six numbers' >&2
fi
done
return 1
}
get_tmp_creds() {
# https://aws.amazon.com/premiumsupport/knowledge-center/authenticate-mfa-cli/
aws sts get-session-token \
--serial-number "${1}" \
--token-code "${2}" \
--duration-seconds "${3}"
}
update_creds_file() {
local ak sk st
ak=$1
sk=$2
st=$3
# https://stackoverflow.com/a/16987794/2908724
sed -i '' \
-e '/^\[mfa\]$/,/^\[/ s@^aws_access_key_id *=.*@aws_access_key_id='"${ak}"'@' \
-e '/^\[mfa\]$/,/^\[/ s@^aws_secret_access_key *=.*@aws_secret_access_key='"${sk}"'@' \
-e '/^\[mfa\]$/,/^\[/ s@^aws_session_token *=.*@aws_session_token='"${st}"'@' \
"${HOME}"/.aws/credentials
}
verify_identity() {
aws sts get-caller-identity --profile mfa >/dev/null
}
main "${@:-}"
@bishopb
Copy link
Author

bishopb commented Oct 5, 2022

Deprecated. Just use mfa_serial (and as needed role_arn) in the AWS config file. https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-role.html#cli-role-prepare

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