Skip to content

Instantly share code, notes, and snippets.

@vranystepan
Last active August 28, 2024 19:53
Show Gist options
  • Save vranystepan/000f44ebddb2bd460bcef5c2109e278a to your computer and use it in GitHub Desktop.
Save vranystepan/000f44ebddb2bd460bcef5c2109e278a to your computer and use it in GitHub Desktop.
CI/CD assume role

Simple AWS IAM role assume for CI/CD environments

Example

set AWS env. variables

export ASSUME_ROLE_ARN="arn:aws:iam::000000000000:role/role00001"
export AWS_ACCESS_KEY_ID="..."
export AWS_SECRET_ACCESS_KEY="..."

optionally you can set session token for MFA

export AWS_SESSION_TOKEN="..."

and then load the helper

wget "${ASSUME_HELPER_URL}" -O ./init.sh
. ./init.sh
aws eks list-clusters --region eu-central-1

Caveats

Do not execute this helper as script. As we need to modify environment variables in the current proces - helper has to be sourced with source or .

#!/bin/sh
check_empty () {
# $1 is variable name
# Write status
echo "checking variable ${1} ..."
# check if variable is empty - unset or ''
if [ -z "$(eval echo \$"$1")" ]; then
echo "${1} is empty!"
exit 1
fi
}
# perform validation
check_empty ASSUME_ROLE_ARN
check_empty AWS_ACCESS_KEY_ID
check_empty AWS_SECRET_ACCESS_KEY
# create temporary directory for aws config & credentials
mkdir -p "$(pwd)/.aws"
# configure aws cli behaviour
AWS_CONFIG_FILE="$(pwd)/.aws/config"
AWS_SHARED_CREDENTIALS_FILE="$(pwd)/.aws/credentials"
cat <<EOT > "${AWS_CONFIG_FILE}"
[profile main]
region = eu-central-1
output = json
[profile default]
role_arn = ${ASSUME_ROLE_ARN}
source_profile = main
EOT
cat <<EOT > "${AWS_SHARED_CREDENTIALS_FILE}"
[main]
aws_access_key_id = ${AWS_ACCESS_KEY_ID}
aws_secret_access_key = ${AWS_SECRET_ACCESS_KEY}
aws_session_token = ${AWS_SESSION_TOKEN}
EOT
# unset AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY,
# otherwise AWS_DEFAULT_PROFILE won't work
unset AWS_ACCESS_KEY_ID
unset AWS_SECRET_ACCESS_KEY
unset AWS_SESSION_TOKEN
# export AWS environment variables
export AWS_CONFIG_FILE
export AWS_SHARED_CREDENTIALS_FILE
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment