Skip to content

Instantly share code, notes, and snippets.

@jroehl
Last active March 14, 2021 16:34
Show Gist options
  • Save jroehl/c0789a3c4dca94ecf6958a9f4e408b8a to your computer and use it in GitHub Desktop.
Save jroehl/c0789a3c4dca94ecf6958a9f4e408b8a to your computer and use it in GitHub Desktop.
An assume-role helper script to update the environment variables with the temporary credentials
#! /bin/bash
# Execute locally
# source ./aws-assume-role.sh AccountId Role Region [LifetimeCredentials]
# Execute from remote
# source <(curl -sL https://gist.github.com/jroehl/c0789a3c4dca94ecf6958a9f4e408b8a/raw/aws-assume-role.sh) AccountId Role Region [SessionName] [LifetimeCredentials]
if (
[[ -n $ZSH_EVAL_CONTEXT && $ZSH_EVAL_CONTEXT =~ :file$ ]] ||
[[ -n $KSH_VERSION && $(cd "$(dirname -- "$0")" &&
printf '%s' "${PWD%/}/")$(basename -- "$0") != "${.sh.file}" ]] ||
[[ -n $BASH_VERSION && $0 != "$BASH_SOURCE" ]]
); then
echo "Script is being sourced"
else
echo "This script needs to be run as source: source ./aws-assume-role.sh"
return 1
fi
if [ -z "$1" ] || [ -z "$2" ] || [ -z "$3" ]; then
echo "Param one has to be of type AWS::AccountId"
echo "Param two has to be of type AWS::Iam::Role"
echo "Param three has to be of type AWS::Region"
return 1
fi
if ! type "aws" &> /dev/null;
then echo "aws-cli is not installed but needed"
return 1
fi
if [ -z "$4" ]; then
(which uuidgen || ( which apt-get && apt-get install uuidgen-runtime || which yum && yum install uuidgen-runtime)) &> /dev/null
SESSION_NAME=$(uuidgen)
fi
ACCOUNT_ID="$1"
TRUSTING_ROLE="$2"
REGION="$3"
unset AWS_SESSION_TOKEN
export AWS_REGION=${REGION}
export AWS_DEFAULT_REGION=${REGION}
(which jq || ( which brew && brew install jq || which apt-get && apt-get install jq || which yum && yum install jq)) &> /dev/null
TMP_CREDENTIALS=$(aws sts assume-role \
--role-arn "arn:aws:iam::${ACCOUNT_ID}:role/${TRUSTING_ROLE}" \
--role-session-name ${4:-$SESSION_NAME} \
--duration-seconds ${5:-3600}
)
export AWS_ACCESS_KEY_ID=$(echo $TMP_CREDENTIALS | jq .Credentials.AccessKeyId | xargs)
export AWS_SECRET_ACCESS_KEY=$(echo $TMP_CREDENTIALS | jq .Credentials.SecretAccessKey | xargs)
export AWS_SESSION_TOKEN=$(echo $TMP_CREDENTIALS | jq .Credentials.SessionToken | xargs)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment