Created
November 8, 2023 11:12
-
-
Save gurukulkarni/daa7b25b3ca62f18f70d448a5c89d5de to your computer and use it in GitHub Desktop.
A Simple bash script to accept a code from user interactively for AWS 2FA TOTP
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 | |
read -r -p "Enter OTP for AWS: " TOKEN_CODE | |
# Change below for you user and account and profile | |
MFA_ARN=arn:aws:iam::xxxxxxxxxxxxx:mfa/AwsUserName | |
PROFILE=xxxxx | |
DURATION=43200 | |
TMP_FILE=/tmp/aws-creds | |
CREDENTIALS_FILE=~/.aws/credentials | |
trap "rm -fv $TMP_FILE" EXIT | |
if $(test -e ~/.aws/credentials.withoutMFA); then | |
cp ~/.aws/credentials.withoutMFA ${CREDENTIALS_FILE} | |
else | |
cp ${CREDENTIALS_FILE} ~/.aws/credentials.withoutMFA | |
fi | |
aws sts get-session-token --duration-seconds ${DURATION} --serial-number ${MFA_ARN} --token-code ${TOKEN_CODE} --profile ${PROFILE} > ${TMP_FILE} | |
AWS_ACCESS_KEY_ID=$(jq -r '.Credentials | .AccessKeyId' ${TMP_FILE}) | |
AWS_SECRET_ACCESS_KEY=$(jq -r '.Credentials | .SecretAccessKey' ${TMP_FILE}) | |
AWS_SESSION_TOKEN=$(jq -r '.Credentials | .SessionToken' ${TMP_FILE}) | |
cat << END > ${CREDENTIALS_FILE} | |
[default] | |
aws_access_key_id=${AWS_ACCESS_KEY_ID} | |
aws_secret_access_key=${AWS_SECRET_ACCESS_KEY} | |
[${PROFILE}] | |
aws_access_key_id=${AWS_ACCESS_KEY_ID} | |
aws_secret_access_key=${AWS_SECRET_ACCESS_KEY} | |
aws_session_token=${AWS_SESSION_TOKEN} | |
END | |
echo "wrote ${CREDENTIALS_FILE}" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment