Skip to content

Instantly share code, notes, and snippets.

@k-k
Last active March 11, 2021 20:00
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 k-k/375eb44bee397cc8bb3e99faafda6e09 to your computer and use it in GitHub Desktop.
Save k-k/375eb44bee397cc8bb3e99faafda6e09 to your computer and use it in GitHub Desktop.
Wraps commands dependent on STS Tokens through a function using saml2aws, automatically refreshing the session token
# This function can be added to your bash or zsh rc file - then you setup aliases for
# commonly used tools which rely on AWS session tokens to be refreshed through saml2aws.
s2a_auth() {
yellow=`tput setaf 3`
reset=`tput sgr0`
now_minus_5=$(date -v "-5M" +"%Y-%m-%dT%T%z")
exp_date=$(awk -F "=" '/x_security_token_expires/ {print $2}' ~/.aws/credentials | tr -d ' ')
# If a date is not found or there is less than 5 minutes before expiration, re-auth.
if [ -z "$exp_date" ] || [[ $now_minus_5 > $exp_date ]]; then
echo -ne "\n${yellow}"
if [ -z "$exp_date" ]; then
echo -n "AWS Session Token expiration was not found"
else
echo -n "AWS Session Token has expired or is expiring soon"
fi
echo "; requesting a new session token...${reset}\n\n"
saml2aws login --skip-prompt --force
fi
# Run the command with all arguments
$@
}
# Example usage
alias aws="s2a_auth aws"
alias terraform="s2a_auth terraform"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment