Last active
August 19, 2019 13:39
-
-
Save louy/678aa5299967ee84dd22fabc9aa0485e to your computer and use it in GitHub Desktop.
aws-cli mfa session utility
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
# AWS MFA session util | |
# Setup: | |
# assuming you're using a profile called "default": | |
# In ~/.aws/config, set up a default-mfa-temp profile: | |
# ``` | |
# [default] | |
# region = eu-west-2 | |
# [default-mfa-temp] | |
# region = eu-west-2 | |
# ``` | |
# And in ~/.aws/credentials, copy the default credentials over to the mfa profile: | |
# ``` | |
# [default] | |
# aws_access_key_id = XXX | |
# aws_secret_access_key = YYY | |
# [default-mfa-temp] | |
# aws_access_key_id = XXX | |
# aws_secret_access_key = YYY | |
# aws_session_token = | |
# ``` | |
# | |
# Make sure you set the `AWS_PROFILE` env var | |
# export AWS_PROFILE=default | |
# Usage: | |
# $ aws-mfa | |
# Enter your 6 digit mfa code for profile [default] and press [ENTER]: 000000 | |
# Now using profile [default-mfa-temp] | |
# Add this function to your `~/.zshrc` file: | |
aws-mfa() { | |
local profile_name=${AWS_PROFILE:-default} | |
local profile_name="${profile_name/-mfa-temp/}" | |
local mfa_profile_name=$profile_name-mfa-temp | |
if [ -z $profile_name ]; then echo "Unknown profile" && return 1; fi | |
echo -n "Enter your 6 digit mfa code for profile [$profile_name] and press [ENTER]: " | |
read mfa_code | |
if [ -z $mfa_code ]; then echo "Missing token" && return 1; fi | |
local mfa_device=$(aws sts get-caller-identity --profile $profile_name --query 'Arn' --output text | sed s/user/mfa/) | |
if [ -z $mfa_device ]; then return 1; fi | |
local session_token=$( \ | |
aws sts get-session-token \ | |
--profile $profile_name \ | |
--serial-number $mfa_device \ | |
--output text \ | |
--query "Credentials.[AccessKeyId,SecretAccessKey,SessionToken]" \ | |
--duration-seconds 129600 \ | |
--token-code "$mfa_code" \ | |
) | |
if [ -z $session_token ]; then return 1; fi | |
echo $session_token \ | |
| awk '{ \ | |
print "aws configure set profile.'$mfa_profile_name'.aws_access_key_id " $1 \ | |
" && aws configure set profile.'$mfa_profile_name'.aws_secret_access_key " $2 \ | |
" && aws configure set profile.'$mfa_profile_name'.aws_session_token " $3}' \ | |
| sh || return 1 # FIXME - return not working | |
export AWS_PROFILE=$mfa_profile_name | |
echo "Now using profile [$mfa_profile_name]" | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment