Last active
March 25, 2020 15:52
-
-
Save ch1bo/8ec03590ed26a0b2704a79cb761d7c58 to your computer and use it in GitHub Desktop.
Interactive AWS profile selection and environment setup using a yubikey, fzf and constistent names in ~/.aws/credentials
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env bash | |
set -e | |
if [ -z "$(which aws)" ] || [ -z "$(which fzf)" ] || [ -z "$(which ykman)" ] || [ -z "$(which jq)" ]; then | |
>&2 echo "# This script requires 'aws', 'fzf', 'ykman' and 'jq' to be installed" | |
exit 1 | |
fi | |
function clear-credentials { | |
>&2 echo "# Clearing credentials" | |
echo "unset AWS_ACCESS_KEY_ID" | |
echo "unset AWS_SECRET_ACCESS_KEY" | |
echo "unset AWS_SESSION_TOKEN" | |
echo "unset AWS_PROFILE" | |
>&2 echo "# To request new credentials, connect a yubikey and run with:" | |
>&2 echo "# eval \$($0)" | |
} | |
ykman oath info > /dev/null || (clear-credentials && exit 1) | |
PROFILE=$(ykman oath list | sed "1 i\[none]" - | fzf) | |
if [ ${PROFILE} = "[none]" ]; then | |
clear-credentials | |
exit 0 | |
fi | |
export AWS_PROFILE=${PROFILE#aws-} | |
if [ ${PROFILE} = ${AWS_PROFILE} ]; then | |
>&2 echo "# Select a oath code with \"aws-\" prefix" | |
exit 1 | |
fi | |
>&2 echo "# Loading AWS credentials with AWS_PROFILE=${AWS_PROFILE}" | |
SERIAL_NUMBER=$(AWS_PROFILE=${AWS_PROFILE} aws iam list-mfa-devices | jq -r '.MFADevices[0].SerialNumber') | |
>&2 echo "# Using first MFA device ${SERIAL_NUMBER}" | |
TOKEN_CODE=$(ykman oath code --single ${PROFILE}) | |
>&2 echo "# Generated token code ${TOKEN_CODE}" | |
# Clear within session to retrieve new tokens | |
unset AWS_ACCESS_KEY_ID | |
unset AWS_SECRET_ACCESS_KEY | |
unset AWS_SESSION_TOKEN | |
RESULT=$(aws sts get-session-token --serial-number ${SERIAL_NUMBER} --token-code ${TOKEN_CODE}) | |
EXPIRATION=$(echo ${RESULT} | jq '.Credentials.Expiration') | |
ACCESS_KEY_ID=$(echo ${RESULT} | jq '.Credentials.AccessKeyId') | |
SECRET_ACCESS_KEY=$(echo ${RESULT} | jq '.Credentials.SecretAccessKey') | |
SESSION_TOKEN=$(echo ${RESULT} | jq '.Credentials.SessionToken') | |
>&2 echo "# Got credentials, valid until ${EXPIRATION}" | |
echo "export AWS_PROFILE=${AWS_PROFILE}" | |
echo "export AWS_ACCESS_KEY_ID=${ACCESS_KEY_ID}" | |
echo "export AWS_SECRET_ACCESS_KEY=${SECRET_ACCESS_KEY}" | |
echo "export AWS_SESSION_TOKEN=${SESSION_TOKEN}" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment