Skip to content

Instantly share code, notes, and snippets.

@bennettp123
Last active June 10, 2020 07:31
Show Gist options
  • Save bennettp123/0b54e783d56c6186aed2939e36bad39e to your computer and use it in GitHub Desktop.
Save bennettp123/0b54e783d56c6186aed2939e36bad39e to your computer and use it in GitHub Desktop.
aws-mfa-login.sh
#!/bin/bash
set -e -o pipefail
#
# Instructions
#
# To log into an AWS profile "mgmt":
#
# 1. create a profile mgmt-nomfa. Use aws_access_key_id and
# aws_secret_access_key as normal.
# 2. `export AWS_PROFILE=mgmt`
# 3. `aws-mfa-login.sh <token>`
#
# This script will append "-nomfa" to AWS_PROFILE and attempt to fetch the mfa
# device for the account. It will then get a temporary token using that acccount.
#
# The command will print out commands to update the profile; you can apply these
# credentials using eval:
#
# ```
# eval `./aws-mfa-login.sh <token>`
# ```
#
# To use this script with the default profile, leave AWS_PROFILE empty, and
# just use [nomfa] for the security credentials.
#
if [ "$1" == "" ]; then
echo "Usage: `basename "$0"` <MFA-TOKEN>"
exit
fi
TARGET_PROFILE="${AWS_PROFILE}"
NOMFA_PROFILE="${TARGET_PROFILE}-nomfa"
CONFIG_PREFIX="profile.${TARGET_PROFILE}."
if [ "${TARGET_PROFILE}" == "" ]; then
NOMFA_PROFILE="nomfa"
CONFIG_PREFIX=""
fi
export AWS_PROFILE="${NOMFA_PROFILE}"
SESSION_DURATION=129600 # 36 hours
SERIAL_NUMBER="$(aws iam list-mfa-devices | jq -r .MFADevices[0].SerialNumber)"
MFA_CODE="$1"
TMPFILE="$(mktemp)"
chmod go-rwx "${TMPFILE}"
trap "rm -f '${TMPFILE}'" EXIT
aws sts get-session-token \
--duration-seconds "${SESSION_DURATION}" \
--serial-number "${SERIAL_NUMBER}" \
--token-code "${MFA_CODE}" \
> "${TMPFILE}"
DESIRED_OUTPUT="$(aws configure get "${CONFIG_PREFIX}output" || echo "json")"
DESIRED_REGION="$(aws configure get "${CONFIG_PREFIX}region" || echo "ap-southeast-2")"
cat <<EOF
aws configure set "${CONFIG_PREFIX}aws_secret_access_key" "$(cat "${TMPFILE}" | jq -r '.Credentials.SecretAccessKey')";
aws configure set "${CONFIG_PREFIX}aws_access_key_id" "$(cat "${TMPFILE}" | jq -r '.Credentials.AccessKeyId')";
aws configure set "${CONFIG_PREFIX}aws_session_token" "$(cat "${TMPFILE}" | jq -r '.Credentials.SessionToken')";
aws configure set "${CONFIG_PREFIX}output" "${DESIRED_OUTPUT}";
aws configure set "${CONFIG_PREFIX}region" "${DESIRED_REGION}";
EOF
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment