Skip to content

Instantly share code, notes, and snippets.

@jasonmcintosh
Last active April 27, 2020 22:29
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jasonmcintosh/35b5ee17663aca74c3192fef7fe44d37 to your computer and use it in GitHub Desktop.
Save jasonmcintosh/35b5ee17663aca74c3192fef7fe44d37 to your computer and use it in GitHub Desktop.
aws-creds helper script
#!/bin/bash
VAULT_PATH=$1
ROLE=$2
DURATION=$3
if [ -z "$VAULT_ADDR" ]; then
echo "Missing VAULT_ADDR env variable"
exit 1
fi
if [ -z "$VAULT_PATH" ]; then
echo "Missing VAULT_PATH argument.\nExample: `$0 documents-store`"
exit 1
fi
if [ -z "$ROLE" ]; then
echo "Missing ROLE argument"
exit 1
fi
if [ -z "$DURATION" ]; then
DURATION=43200
fi
if [[ -z "${VAULT_TOKEN}" ]]; then
echo "No vault token environment variable found attempting to read the token from the default file"
VAULT_TOKEN=`cat ~/.vault-token`
fi
#CREDS=$(curl --header "X-Vault-Token: $VAULT_TOKEN" --request POST --data '{"ttl":"24h"}' $VAULT_ADDR/v1/aws/$VAULT_PATH/sts/$ROLE)
# Can use vault read vs. write now with later releases. Makes permissions a bit easier
CREDS="`vault read aws/$VAULT_PATH/sts/$ROLE ttl=$DURATION`"
export AWS_ACCESS_KEY_ID=$(echo "$CREDS" | grep 'access_key' | awk '{print $2}')
export AWS_SECRET_ACCESS_KEY=$(echo "$CREDS" | grep 'secret_key' | awk '{print $2}')
export AWS_SESSION_TOKEN=$(echo "$CREDS" | grep 'security_token' | awk '{print $2}')
SIGNIN_TOKEN=`curl -G --data-urlencode "Action=getSigninToken" --data-urlencode "SessionType=json" --data-urlencode "Session={\"sessionId\":\"${AWS_ACCESS_KEY_ID}\", \"sessionKey\":\"${AWS_SECRET_ACCESS_KEY}\", \"sessionToken\":\"${AWS_SESSION_TOKEN}\"}" https://signin.aws.amazon.com/federation|jq -r '.SigninToken'`
echo "Logout FIRST to use the below sign-in link"
echo "https://console.aws.amazon.com/iam/logout!doLogout"
echo "https://signin.aws.amazon.com/federation?Action=login&Issuer=https%3A%2F%2Fmyvaultserver&Destination=https%3A%2F%2Fconsole.aws.amazon.com%2F&SigninToken=${SIGNIN_TOKEN}"
DURATION=$(echo "$CREDS" | grep 'lease_duration' | awk '{print $2}')
if [ -z "$DURATION" ]; then
echo FAILED to obtain credentials lease!
return -1
else
echo Credentials good for $DURATION seconds.
fi
## Un comment to set shell sample. Can probably be tweaked to inject parameter vs. sample below
#txtgrn='\e[0;32m'
#export PS1="\u1\h2 \[$txtgrn\](AWS:`aws iam list-account-aliases|jq -r '.AccountAliases[0] '`)\[\e[0m\] $ "
@k0emt
Copy link

k0emt commented Jun 11, 2018

Please replace the last line with:

if [ -z "$DURATION" ]; then
  echo FAILED to obtain credentials lease!
else
  echo Credentials good for $DURATION seconds.
fi

@jasonmcintosh
Copy link
Author

Updated :)

@k0emt
Copy link

k0emt commented Jun 11, 2018

Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment