Created
December 3, 2021 15:01
-
-
Save jhpacker/73f3fb2efd4b384543e93653551201a8 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 | |
## run this with . | |
# your IAM user | |
IAM='xx:mfa/xx' # get from console or `aws sts get-caller-identity` | |
# uses macosx gnu version of utils like numfmt, grep, etc. | |
if [[ $(uname -s) = *Darwin* ]]; then | |
DATE='gdate' | |
else | |
DATE='date' | |
fi | |
CREDS=$(aws sts get-session-token) | |
NOW=$($DATE -u '+%Y-%m-%dT%H:%M:%S+00:00') | |
if [ -z "$CREDS" ]; then | |
EXPIRES=$($DATE -u '+%Y-%m-%dT%H:%M:%S+00:00' --date="yesterday") | |
else | |
EXPIRES=$(echo "$CREDS" | jq -r .Credentials.Expiration) | |
fi | |
# is our token expired? | |
if [ "$NOW" \> "$EXPIRES" ]; then | |
read -rp "Enter OTP: " OTP | |
AWS=$(aws --profile default sts get-session-token --duration 129600 \ | |
--serial-number arn:aws:iam::$IAM --token-code "$OTP") | |
echo "$AWS" | |
else | |
echo "existing token exported to environment" | |
fi | |
AWS_ACCESS_KEY_ID=$(echo "$CREDS" | jq -r .Credentials.AccessKeyId) | |
AWS_SECRET_ACCESS_KEY=$(echo "$CREDS" | jq -r .Credentials.SecretAccessKey) | |
AWS_SESSION_TOKEN=$(echo "$CREDS" | jq -r .Credentials.SessionToken) | |
export AWS_ACCESS_KEY_ID | |
export AWS_SECRET_ACCESS_KEY | |
export AWS_SESSION_TOKEN |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment