Last active
January 15, 2023 15:56
-
-
Save shar1z/5b0581700401dc874e5e44dac358e6c2 to your computer and use it in GitHub Desktop.
OIDC
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export AWS_ROLE_ARN=arn:aws:iam::1234567890:role/RoleToAssume | |
export AWS_WEB_IDENTITY_TOKEN_FILE=/tmp/awscreds | |
export AWS_DEFAULT_REGION=<region> | |
export DEFAULT_PARALLEL_JOBS=4 | |
OUTPUT_TOKEN_REQUEST=$(curl -H "Authorization: bearer $ACTIONS_ID_TOKEN_REQUEST_TOKEN" "$ACTIONS_ID_TOKEN_REQUEST_URL") | |
echo "$OUTPUT_TOKEN_REQUEST" | jq -r '.value' > /tmp/awscreds | |
RET=1 | |
MAX_RETRIES=5 | |
COUNTER=1 | |
WAIT_FACTOR=2 | |
RUN_ID=$(uuidgen) | |
until [ ${RET} -eq 0 ]; do | |
# 5 retries are enough, then fail. | |
if [ $COUNTER -gt $MAX_RETRIES ]; then | |
echo "$RUN_ID - Maximum retries of $MAX_RETRIES reached. Returning error." | |
exit 1 | |
fi | |
# Try to perform the assume role with web identity | |
OUTPUT_ASSUME_ROLE=$(aws sts assume-role-with-web-identity --duration-seconds 3600 --role-session-name my_role_name --role-arn $AWS_ROLE_ARN --web-identity-token $(cat /tmp/awscreds) --region $AWS_DEFAULT_REGION) | |
RET=$? | |
echo "$RUN_ID - attempt: $COUNTER, assume rule returned code: $RET" | |
if [ $RET -ne 0 ]; then | |
echo "$RUN_ID - attempt: $COUNTER - Error happened in assume role, error code - $RET, error msg: $OUTPUT_ASSUME_ROLE. retrying..." | |
WAIT_FACTOR=$((WAIT_FACTOR*COUNTER)) | |
sleep $WAIT_FACTOR | |
else | |
access_key_id="$(echo "$OUTPUT_ASSUME_ROLE" | jq -r '.Credentials.AccessKeyId')" | |
# Set the AWS environment variables to be used. | |
export AWS_ACCESS_KEY_ID=$access_key_id | |
secret_access_key="$(echo "$OUTPUT_ASSUME_ROLE" | jq -r '.Credentials.SecretAccessKey')" | |
export AWS_SECRET_ACCESS_KEY=$secret_access_key | |
session_token="$(echo "$OUTPUT_ASSUME_ROLE" | jq -r '.Credentials.SessionToken')" | |
export AWS_SESSION_TOKEN=$session_token | |
fi | |
COUNTER=$((COUNTER+1)) | |
done | |
# Perform any calls to AWS now - the 3 environment variables will take precedence over AWS_WEB_IDENTITY_TOKEN_FILE |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment