How to Authenticate GitLab CI to AWS with OIDC
GitLab can mint an OIDC ID token per job and exchange it for short-lived AWS credentials - no static keys.
Declare an id_tokens: block with the AWS aud, then call aws sts assume-role-with-web-identity (or use it via the AWS CLI) to get temporary credentials.
Assume a role with a job ID token
GitLab provides the OIDC token in the named variable; pass it to STS to assume the role.
.gitlab-ci.yml
deploy:
image: amazon/aws-cli:2
id_tokens:
AWS_ID_TOKEN:
aud: https://gitlab.com
script:
- >
export $(aws sts assume-role-with-web-identity
--role-arn "$AWS_ROLE_ARN"
--role-session-name "ci-$CI_JOB_ID"
--web-identity-token "$AWS_ID_TOKEN"
--query 'Credentials.[AccessKeyId,SecretAccessKey,SessionToken]'
--output text | awk '{print "AWS_ACCESS_KEY_ID="$1" AWS_SECRET_ACCESS_KEY="$2" AWS_SESSION_TOKEN="$3}')
- aws s3 lsGotchas
- The IAM trust policy must match the token
audand thesubclaim (e.g.project_path:group/repo:ref_type:branch:ref:main). - On self-managed GitLab the
audis your instance URL, nothttps://gitlab.com. - The ID token is per-job and short-lived - request it in each job that needs AWS access.
Related guides
How to Use OIDC to Authenticate GitHub Actions to AWSAuthenticate GitHub Actions to AWS with OIDC - no long-lived secrets. Set up the IAM role, trust policy, and…
How to Authenticate CircleCI to AWS with OIDCAuthenticate CircleCI to AWS with OIDC - use the CIRCLE_OIDC_TOKEN in a context-scoped job to assume an IAM r…