Last active
September 1, 2021 20:20
-
-
Save kshcherban/41746566e118cf0abd270410502e9ec8 to your computer and use it in GitHub Desktop.
Simple script to set AWS creds with MFA auth, just put it in your bashrc like `alias mfa='. ~/.local/bin/aws-mfa.sh $@'`
This file contains hidden or 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 | |
#set -eo pipefail | |
# | |
# Sample for getting temp session token from AWS STS | |
# | |
# aws --profile youriamuser sts get-session-token --duration 3600 \ | |
# --serial-number arn:aws:iam::012345678901:mfa/user --token-code 012345 | |
# | |
# 1 or 2 args ok | |
if [[ $# -ne 1 && $# -ne 2 ]]; then | |
echo "Usage: $0 <MFA_TOKEN_CODE> <AWS_CLI_PROFILE>" | |
echo "Where:" | |
echo " <MFA_TOKEN_CODE> = Code from virtual MFA device" | |
echo " <AWS_CLI_PROFILE> = aws-cli profile usually in $HOME/.aws/config" | |
else | |
AWS_CLI_PROFILE=${2:-default} | |
MFA_TOKEN_CODE=$1 | |
DURATION=129600 | |
SESSION_FILE="${HOME}/.aws/mfa_session_${AWS_CLI_PROFILE}" | |
USER_INFO="$(aws --profile $AWS_CLI_PROFILE iam get-user --output text)" | |
if [[ x"$USER_INFO" == "x" ]]; then | |
echo "Something went wrong, please check 'aws iam get-user' output" | |
exit 1 | |
else | |
USER_ID="$(echo $USER_INFO | awk '{print $NF}')" | |
ORG_ID="$(echo $USER_INFO | awk -F: '{print $5}')" | |
ARN_OF_MFA="arn:aws:iam::${ORG_ID}:mfa/${USER_ID}" | |
fi | |
echo "AWS-CLI Profile: $AWS_CLI_PROFILE" | |
echo "MFA ARN: $ARN_OF_MFA" | |
echo "MFA Token Code: $MFA_TOKEN_CODE" | |
aws --profile $AWS_CLI_PROFILE sts get-session-token --duration $DURATION \ | |
--serial-number $ARN_OF_MFA --token-code $MFA_TOKEN_CODE --output text \ | |
| awk '{printf("export AWS_ACCESS_KEY_ID=\"%s\"\nexport AWS_SECRET_ACCESS_KEY=\"%s\"\nexport AWS_SESSION_TOKEN=\"%s\"\nexport AWS_SECURITY_TOKEN=\"%s\"\n",$2,$4,$5,$5)}' > $SESSION_FILE | |
# Fail if mfa or creds are incorrect | |
if [[ ${PIPESTATUS[0]} -ne 0 ]]; then | |
echo "ERROR retrieving credentials from AWS" | |
else | |
echo "Temporary Creds written in $SESSION_FILE" | |
source $SESSION_FILE | |
fi | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment