Last active
August 24, 2019 15:12
-
-
Save sgdan/d7e6841b281bec113f3f031d2cfad65d to your computer and use it in GitHub Desktop.
Utility shell script for logging into AWS CLI named profile using an MFA token
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
#!/bin/bash | |
if [ $# -lt 1 ]; then | |
cat << EOF | |
usage: awslogin <profile> | |
Utility script for logging into AWS CLI named profile with an MFA token. | |
A session token will be requested and the "default" profile will be updated | |
with the valid session data. Make sure you have a named profile configured | |
as described below, including the "mfa" arn: | |
~/.aws/config file: | |
[myprofile] | |
output = json | |
region = ap-southeast-2 | |
~/.aws/credentials file: | |
[myprofile] | |
aws_access_key_id = XXXXXXXXXXXXXXXXXXXX | |
aws_secret_access_key = XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX | |
mfa = arn:aws:iam::XXXXXXXXXXXX:mfa/myprofile | |
EOF | |
exit 1 | |
fi | |
profile=$1 | |
# "mfa" should be configured in the profile in ~/.aws/credentials | |
mfa=$(aws configure get mfa --profile $profile) || { echo "No mfa arn configured for profile $profile"; exit 1; } | |
read -p "MFA Token for $profile: " token | |
token=${token} | |
values=($(aws sts get-session-token \ | |
--serial-number $mfa \ | |
--token-code $token \ | |
--query '[Credentials.AccessKeyId,Credentials.SecretAccessKey,Credentials.SessionToken]' \ | |
--output text \ | |
--profile $profile)) | |
aws configure set aws_access_key_id ${values[0]} | |
aws configure set aws_secret_access_key ${values[1]} | |
aws configure set aws_session_token ${values[2]} | |
echo "Updated 'default' profile with session values" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment