Skip to content

Instantly share code, notes, and snippets.

@chtorr
Last active June 18, 2021 13:36
Show Gist options
  • Save chtorr/0ecc8fca27a4c5e186c636c262cc4757 to your computer and use it in GitHub Desktop.
Save chtorr/0ecc8fca27a4c5e186c636c262cc4757 to your computer and use it in GitHub Desktop.
aws-vault yubikey bash helpers
# - install the Yubico authenticator app
# - install ykman
# - setup your yubikey as a virtual MFA device in AWS, and
# - install and setup AWS vault
# - place the following in your ~/.bash_profile (or whatever the appropriate profile file is)
# - run source ~/.bash_profile or open a new shell
# load temp AWS credentials in your current shell: `aws_auth <profile>`
# login to AWS console with temp credentials: `aws_login <profile`
# I also like to add the vault name to my shell prompt: \033[0;31m[\$AWS_VAULT]\033[0m
# get the name of the profile from the output of `ykman oath list`
YUBIKEY_PROFILE="REPLACE ME"
_aws_unset() {
unset AWS_SESSION_TOKEN
unset AWS_VAULT
unset AWS_SECRET_ACCESS_KEY
unset AWS_ACCESS_KEY_ID
unset AWS_SECURITY_TOKEN
}
_aws_check_profile() {
if [ $# -eq 0 ]
then
echo "Must pass aws-vault profile name"
return 1
fi
grep -qw "^\[profile $1\]$" <~/.aws/config
if [ $? -gt 0 ]; then
echo "Profile $1 not found in aws config"
return 1
fi
}
_aws_vault_export() {
aws-vault exec $1 --no-session --assume-role-ttl=12h -m `ykman oath code --single "$YUBIKEY_PROFILE" | awk '{print $NF}'` -- env | grep ^AWS | sed -e 's/^/export\ /'
}
aws_auth(){
_aws_check_profile $1
if [ $? -gt 0 ]; then
return $?
fi
_aws_unset
eval "$(_aws_vault_export $1)"
}
aws_login() {
_aws_check_profile $1
if [ $? -gt 0 ]; then
return $?
fi
aws-vault login $1 --no-session --assume-role-ttl=12h -t `ykman oath code --single "$YUBIKEY_PROFILE" | awk '{print $NF}'`
}
@dominics
Copy link

dominics commented Nov 14, 2019

I think this helper needs set -o pipefail or similar, and checking the result of the aws-vault exec - it'll fail if aws_auth is run twice in quick succession, because AWS will refuse the duplicate MFA code. Unfortunately, this isn't checked, and fails silently (because the exit code of _aws_vault_export is the exit code of the sed, even if the aws-vault call failed).

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