Skip to content
Latchkey

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 ls

Gotchas

  • The IAM trust policy must match the token aud and the sub claim (e.g. project_path:group/repo:ref_type:branch:ref:main).
  • On self-managed GitLab the aud is your instance URL, not https://gitlab.com.
  • The ID token is per-job and short-lived - request it in each job that needs AWS access.

Related guides

Run this faster and cheaper on Latchkey managed runners. Start free →