Access AWS resources through CLI aws sts assume-role?

Hi -

Has anyone successfully access AWS resources using IAM role via AWS CLI aws sts assume-role?

Enclosed is a bash script which is invoked in GitLab CI/CD pipeline (gitlab-ci.yml). I could get a temporary credentials when I invoked the same bash script outside of GitLab CI/CD pipeline. But, when it’s executed in GitLab CI/CD, it returned

Unable to locate credentials. You can configure credentials by running “aws configure”.

BEGIN BASH SCRIPT

#!/bin/bash
set -e
set -u

unset AWS_ACCESS_KEY_ID AWS_SECRET_ACCESS_KEY AWS_SESSION_TOKEN AWS_SECURITY_TOKEN
ROLE_ARN=“arn:aws:iam::xxxxxxxx:role/VCS-CICD-DeploymentRole”
DURATION=“900”
NAME="${CI_BUILD_ID}-date +%Y%m%d"
AWS_REGION=$AWS_REGION

echo 'Assuming role… ’ + $ROLE_ARN
echo ‘Session name…’ + $NAME

KST=(aws sts assume-role --role-arn "${ROLE_ARN}" \ --role-session-name "${NAME}" \ --duration-seconds ${DURATION} \ --query 'Credentials.[AccessKeyId,SecretAccessKey,SessionToken]' \ --output text)
echo “export AWS_DEFAULT_REGION=’{AWS_REGION}'" echo "export AWS_ACCESS_KEY_ID='{KST[0]}’”
echo “export AWS_SECRET_ACCESS_KEY=’{KST[1]}'" echo "export AWS_SESSION_TOKEN='{KST[2]}’”
echo “export AWS_SECURITY_TOKEN=’${KST[2]}’”

There’s a couple of issues. The first one is you need to setup AWS to handle AssumeRoleWithFederatedIdentity. Gitlab also has open issues that prevent this from working out of the box: Add aud claim to CI_JOB_JWT to support Terraform (#216259) · Issues · GitLab.org / GitLab · GitLab

So there are some solutions to get around this that aren’t that bad. For instance this one focusing on avoiding AWS access tokens.