Created
September 14, 2022 10:19
-
-
Save a2tt/a5b8e03c9418236dc9063e547bbd1154 to your computer and use it in GitHub Desktop.
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 | |
AWS_ACCOUNT="" | |
IAM_USER="" | |
MFA_ARN="arn:aws:iam::$AWS_ACCOUNT:mfa/$IAM_USER" | |
AWS_DIRECTORY="$HOME/.aws" | |
CREDENTIALS_FILE="$AWS_DIRECTORY/credentials" | |
if [ $# -ne 1 ]; then | |
echo "One-time Password is required." | |
exit 1 | |
fi | |
# Create credentials file | |
if [ ! -e $CREDENTIALS_FILE ]; then | |
mkdir -p $AWS_DIRECTORY && touch $CREDENTIALS_FILE || exit 1 | |
fi | |
# Profile required | |
if ! grep -Fxq "[$IAM_USER]" $CREDENTIALS_FILE; then | |
echo "Profile [$IAM_USER] does not exist." | |
exit 1 | |
fi | |
# Switch to the original profile | |
export AWS_PROFILE=$IAM_USER | |
# Get session token and keys from AWS | |
credentials=$(aws sts get-session-token --serial-number $MFA_ARN --token-code $1) || exit 1 | |
# Add session profile | |
SESSION_PROFILE="${IAM_USER}-session" | |
line_num=$(grep -Fn "[$SESSION_PROFILE]" -m 1 $CREDENTIALS_FILE | cut -d: -f1) | |
# If exists, delete it | |
if [ "$line_num" != "" ]; then | |
line_num_end=$((line_num + 3)) | |
sed -i -e "${line_num},${line_num_end}d" $CREDENTIALS_FILE | |
fi | |
echo "[$SESSION_PROFILE]" >> $CREDENTIALS_FILE | |
echo "aws_access_key_id =" $(echo $credentials | jq --raw-output ".Credentials.AccessKeyId") >> $CREDENTIALS_FILE | |
echo "aws_secret_access_key =" $(echo $credentials | jq --raw-output ".Credentials.SecretAccessKey") >> $CREDENTIALS_FILE | |
echo "aws_session_token =" $(echo $credentials | jq --raw-output ".Credentials.SessionToken") >> $CREDENTIALS_FILE | |
echo "To switch default profile, run: export AWS_PROFILE=$SESSION_PROFILE" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment