Last active
August 7, 2024 10:36
-
-
Save huevos-y-bacon/83042498eb6435424c74125de7944116 to your computer and use it in GitHub Desktop.
AWS STS - GET SESSION TOKEN WITH MFA allowing CLI access to commands without switching to an IAM Role
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
#!/usr/bin/env bash | |
# shellcheck disable=2086,2162,2005,2046,1091 | |
# GET AWS SESSION TOKEN WITH MFA | |
# allowing CLI access to commands without switching to an IAM Role, e.g. for accessing the Well-Architected Tool | |
source colours > /dev/null 2>&1 # import colours script if it exists in the PATH | |
usage(){ | |
echo " | |
Get session token with MFA, allowing CLI access to commands without switching | |
to an IAM Role, e.g. accessing the Well-Architected Tool | |
Add alias to .bashrc, .zshrc or equivalent: | |
alias aws-get-session-token=\"source aws-get-session-token\" | |
" | |
} | |
if [[ "$*" == *"-d"* ]] || [[ "$*" == *"debug"* ]] || [[ "$*" == *"DEBUG"* ]]; then DEBUG=true; fi | |
if [[ "$*" == *"-h"* ]] || [[ "$*" == *"help"* ]]; then usage; return; fi | |
get_mfa(){ | |
echo | |
echo -n "${RED}Enter MFA Token:${NORM} " | |
read TOKENCODE | |
if [[ -z $TOKENCODE ]]; then echo "${YELLOW}No MFA token supplied${NORM}"; return 1; fi | |
} | |
get_user_details(){ | |
read -r \ | |
USERARN \ | |
ACCOUNTID \ | |
< <(echo $(aws sts get-caller-identity --out json | jq -r '. | .Arn, .Account')) | |
MFAARN="${USERARN/\:user\//:mfa/}" | |
IAMUSER="${USERARN#*/}" | |
echo "${YELLOW}IAM User : ${IAMUSER}${NORM}" | |
echo "${YELLOW}Account : ${ACCOUNTID}${NORM}" | |
if [[ -n $DEBUG ]]; then | |
echo "${YELLOW}User Arn : ${USERARN}${NORM}" | |
echo "${YELLOW}MFA Arn : ${MFAARN}${NORM}" | |
fi | |
} | |
get_token(){ | |
aws sts get-session-token --serial-number ${MFAARN} --token-code ${TOKENCODE} \ | |
| jq -r '.Credentials | .AccessKeyId, .SecretAccessKey, .SessionToken, .Expiration' | |
} | |
get_token_vars(){ | |
read -r \ | |
AWS_ACCESS_KEY_ID \ | |
AWS_SECRET_ACCESS_KEY \ | |
AWS_SESSION_TOKEN \ | |
AWS_SESSION_TOKEN_EXPIRY \ | |
< <(echo $(get_token)) | |
export AWS_ACCESS_KEY_ID | |
export AWS_SECRET_ACCESS_KEY | |
export AWS_SESSION_TOKEN | |
export AWS_SESSION_TOKEN_EXPIRY | |
} | |
if (return 0 2>/dev/null); then | |
get_user_details && \ | |
get_mfa && \ | |
get_token_vars && \ | |
echo -e "\n${GREEN}${BOLD}Token expiry: ${AWS_SESSION_TOKEN_EXPIRY}${NORM}\n" | |
else echo "${RED}This script has to be sourced${NORM}"; usage; | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment