DEV Community

Cover image for Generate AWS Temporary Credential And Add It As A Profile
๐Ÿš€ Vu Dao ๐Ÿš€
๐Ÿš€ Vu Dao ๐Ÿš€

Posted on

Generate AWS Temporary Credential And Add It As A Profile

Generate AWS Temporary Credential And Add It As A Profile

๐Ÿš€ Beside AWS SSO, we can use auto script to generate temporary credential and add it as [mfa] profile

Ref: https://aws.amazon.com/premiumsupport/knowledge-center/authenticate-mfa-cli/

#!/bin/bash
# Generate Temp cred and promote it as a new profile
# Run script whenever the session token expired
set -e

tmp_file=$(mktemp /tmp/temp-cred.XXXXX)
aws sts get-session-token --serial-number arn:aws:iam::111111111111:mfa/my.mfa --token-code "$1" > "$tmp_file"

sed -i '/\[mfa\]/,/^\s*$/{d}' ~/.aws/credentials

cat<<EOF >>~/.aws/credentials
[mfa]
aws_access_key_id = $(cat ${tmp_file} | jq '.[] | .AccessKeyId' | sed 's/"//g')
aws_secret_access_key = $(cat ${tmp_file} | jq '.[] | .SecretAccessKey' | sed 's/"//g')
aws_session_token = $(cat ${tmp_file} | jq '.[] | .SessionToken' | sed 's/"//g')
EOF

rm $tmp_file
Enter fullscreen mode Exit fullscreen mode

๐Ÿš€ Test

โšก $ ./short-term-cred.sh 1234

โšก $ cat ~/.aws/credentials
[default]
aws_access_key_id = example-access-key
aws_secret_access_key = example-secret-access


[mfa]
aws_access_key_id = example-access-key-as-in-returned-output
aws_secret_access_key = example-secret-access-key-as-in-returned-output
aws_session_token = example-session-Token-as-in-returned-output
Enter fullscreen mode Exit fullscreen mode
โšก $ aws elbv2 describe-target-groups --region ap-northeast-1 --profile mfa | grep TargetGroupArn | wc -l 
35
Enter fullscreen mode Exit fullscreen mode

๐ŸŒ  Blog ยท Github ยท Web ยท Linkedin ยท Group ยท Page ยท Twitter ๐ŸŒ 

Top comments (0)