Skip to content

Instantly share code, notes, and snippets.

@jhpacker
Created December 3, 2021 15:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jhpacker/73f3fb2efd4b384543e93653551201a8 to your computer and use it in GitHub Desktop.
Save jhpacker/73f3fb2efd4b384543e93653551201a8 to your computer and use it in GitHub Desktop.
#!/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