Join our Newsletter — 33% off our NHI Course
Home› Guides› How to federate GitLab CI to AWS: OIDC…
Guide Cloud & Workload Identity

How to federate GitLab CI to AWS: OIDC role credentials instead of stored access keys

PDF for newsletter subscribers · free to read online

← All guides
By NHI Mgmt Group, under the editorial direction of Lalit Choda Updated 18 November 2026 16 min read
On this page

You can federate GitLab CI to AWS by registering GitLab as an IAM OIDC identity provider, creating a role whose trust policy only accepts ID tokens from specific projects and refs, and having each job exchange its short-lived GitLab ID token for temporary STS credentials. The result is a pipeline that never holds a long-lived AWS access key. There is nothing to rotate, nothing to leak from a CI/CD variable, and every session in CloudTrail carries a name that points back to the project and pipeline that created it.

This guide walks through the set-up for GitLab.com and for self-managed or Dedicated instances, the trust policy conditions that matter, how to verify the change, the errors you are most likely to meet and the hardening steps to take once it works. It is written for platform engineers, cloud security teams and anyone who owns the AWS side of a GitLab estate. If you also deploy to Azure, the companion page on How to set up workload identity federation for GitLab CI to Azure covers the Entra ID side of the same pattern.

This is an independent guide from NHI Mgmt Group, based on GitLab's public documentation and AWS IAM documentation as of November 2026. It is not sponsored or reviewed by GitLab or AWS. Product features change, so confirm settings against GitLab's current documentation.

Key takeaways

  • GitLab issues a signed OIDC ID token to any job that declares the id_tokens keyword. AWS STS accepts that token through AssumeRoleWithWebIdentity and returns temporary credentials, so no static access key needs to live in GitLab.
  • The security of the whole arrangement sits in the role trust policy. A trust policy that checks only the provider, or uses a loose wildcard on sub, lets any project on the instance assume the role.
  • On GitLab.com you can pin trust to namespace_id and project_id, which do not change when a project is renamed. On self-managed and Dedicated instances, AWS only supports sub and aud as condition keys.
  • The ID token expires at the job timeout, or after five minutes if no timeout is set, which limits the value of a stolen token. The STS session lifetime is set separately and should be as short as the job allows.
  • The legacy CI_JOB_JWT_V2 variable was removed in GitLab 17.0. Any pipeline still using it needs moving to id_tokens.
  • Once federation works, delete the old IAM user access keys and the CI/CD variables that held them. Federation that runs beside a live static key adds an access path instead of removing one.

When you need this

Most GitLab estates that deploy to AWS started with an IAM user, an access key pair and two masked CI/CD variables called AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY. That key is a long-lived non-human identity credential. It is readable by anyone who can edit the pipeline definition on a branch that receives the variable, it is copied into job logs when a script is careless, and it usually outlives the engineer who created it. The OWASP Non-Human Identities Top 10 lists long-lived secrets and secret leakage among its leading risks, and stored CI keys are a textbook example.

You should plan this change when any of the following is true:

  • An IAM user exists only so that a GitLab pipeline can call AWS APIs.
  • Your secrets scanning or cloud posture tooling reports IAM access keys older than your rotation policy that are used from CI runner IP ranges.
  • Audit asks which pipeline made a given change in AWS and CloudTrail can only answer with an IAM user name shared by dozens of projects.
  • You are moving from shared, instance-wide CI/CD variables to per-project or per-environment access and want each project to have its own AWS role.
  • A GitLab token or variable leak has been reported, either inside your organisation or at a supplier, and you need to reduce what a leaked variable is worth. The GitLab Tokens Security Guide covers the GitLab token types themselves.

Federation does not remove the need to protect GitLab. Whoever can push a pipeline definition to a ref that the trust policy accepts can still obtain AWS credentials. What it removes is the standing secret: an attacker has to act through the pipeline at the moment of the job, and every session is short-lived and attributable.

Before you start

Collect the following before changing anything:

  • The GitLab issuer URL. For GitLab.com this is https://gitlab.com. For a self-managed instance it is the instance address, for example https://gitlab.example.com. AWS fetches the OpenID configuration and signing keys from this address, so it must be reachable from the public internet, or you must publish the discovery document elsewhere (covered below).
  • The audience value you will use. GitLab lets each job set the aud claim. The AWS IAM provider must list the same value as an audience (client ID). GitLab's documentation notes that sts.amazonaws.com is a common choice; using the GitLab URL as the audience can work but is semantically misleading, because the audience should name the service that validates the token.
  • The project and namespace identity. Note the full project path (group/subgroup/project), and on GitLab.com the numeric project ID and namespace ID from the project settings page or the Projects API.
  • The refs and environments that should deploy. Decide which branches, tags or protected environments are allowed to assume the role. Production roles should normally accept only protected refs or protected environments.
  • An inventory of the static keys being replaced. List the IAM users, their access key IDs, the GitLab projects or groups holding them as variables, and their last-used dates. The live page How to audit AWS IAM Roles Anywhere and OIDC identity providers covers reviewing existing providers in the account.
  • Permissions. You need IAM permissions to create an OIDC provider and a role in the target account, and Maintainer access or higher on the GitLab project to change .gitlab-ci.yml.

The IAM provider must be created in the same AWS account as the role that trusts it. In a multi-account organisation that means one provider per account that GitLab deploys into, or a single deployment account whose role then assumes roles in the others.

Step-by-step

1. Create the IAM OIDC identity provider

In the IAM console, open Identity providers and add an OpenID Connect provider. Enter the provider URL exactly as the issuer appears in GitLab's discovery document: it must start with https://, must not include a port, and is case-sensitive. Add your chosen audience. AWS documents a limit of one to 100 audiences per provider and requires the provider URL to be unique within the account.

Before you save, confirm that <issuer>/.well-known/openid-configuration returns a document containing issuer, jwks_uri and claims_supported. AWS validates the TLS certificate of the JWKS endpoint against its library of trusted root CAs and only uses the stored thumbprint as a fallback, for example when the certificate is not issued by a trusted CA.

The same provider can be created with aws iam create-open-id-connect-provider, or in Terraform or CloudFormation. Infrastructure as code is the better option because the provider becomes reviewable and repeatable across accounts.

2. Create the role and its trust policy

Create a role for web identity, choose the GitLab provider and set the audience. Then replace the generated trust policy with one that names the exact project and ref. GitLab's documented example for GitLab.com looks like this:

1 Sample only, based on the public documentation cited. Assess it independently against the current official documentation, test outside production and back up first.

Sample 1
{
  "Version": "2012-10-17",
  "Statement": [{
    "Effect": "Allow",
    "Principal": {
      "Federated": "arn:aws:iam::<AWS_ACCOUNT>:oidc-provider/gitlab.com"
    },
    "Action": "sts:AssumeRoleWithWebIdentity",
    "Condition": {
      "StringEquals": {
        "gitlab.com:sub": "project_path:<group>/<project>:ref_type:branch:ref:main",
        "gitlab.com:namespace_id": "<namespace_id>",
        "gitlab.com:project_id": "<project_id>"
      }
    }
  }]
}

NHI Mgmt Group also recommends adding gitlab.com:aud to the same StringEquals block so the role only accepts tokens minted for this audience. On a self-managed instance, replace gitlab.com with your instance host in the provider ARN and condition key prefix, and use only sub and aud, because AWS does not support the other GitLab claims as condition keys for non-GitLab.com providers.

The default sub claim has the form project_path:{group}/{project}:ref_type:{type}:ref:{branch_name}. If you genuinely need a pattern, such as all release tags, switch the operator to StringLike: GitLab's documentation warns that wildcards do not match under StringEquals. Keep any wildcard to the narrowest part of the string, for example project_path:platform/api:ref_type:tag:ref:v*, and never wildcard the project path itself.

3. Attach least-privilege permissions

Attach permissions to the role only after the trust policy is right. Start from what the job actually does: pushing an image to one ECR repository, syncing to one S3 bucket, or updating one ECS service. Avoid reusing the policy that was attached to the old IAM user, which was often broadened over years. Set the role's maximum session duration to the shortest value that covers your longest job.

Use separate roles for separate trust decisions. A role for merge request pipelines that runs plans or read-only checks should not be the same role that applies production changes from the protected main branch.

4. Request an ID token in the job

Add the id_tokens keyword to the job. GitLab exposes the signed token as the variable you name, and you can use it in script, before_script or after_script. The documented pattern exchanges it with the AWS CLI:

Sample 1
assume role:
  id_tokens:
    GITLAB_OIDC_TOKEN:
      aud: sts.amazonaws.com
  script:
    - >
      aws_sts_output=$(aws sts assume-role-with-web-identity
      --role-arn ${ROLE_ARN}
      --role-session-name "GitLabRunner-${CI_PROJECT_ID}-${CI_PIPELINE_ID}"
      --web-identity-token ${GITLAB_OIDC_TOKEN}
      --duration-seconds 3600
      --query 'Credentials.[AccessKeyId,SecretAccessKey,SessionToken]'
      --output text)
    - export $(printf "AWS_ACCESS_KEY_ID=%s AWS_SECRET_ACCESS_KEY=%s AWS_SESSION_TOKEN=%s" $aws_sts_output)
    - aws sts get-caller-identity

The aud value here must match an audience on the IAM provider. ROLE_ARN is not a secret and can be a plain CI/CD variable or written into the pipeline file. Reduce --duration-seconds to the shortest value your job needs.

The role session name is what appears in CloudTrail. Including the project ID and pipeline ID, as above, makes it possible to trace any AWS API call back to a specific pipeline run. NHI Mgmt Group recommends adding the job ID as well where the 64-character limit allows.

5. Handle self-managed instances that are not publicly reachable

If AWS cannot reach your GitLab instance, GitLab documents publishing the OpenID configuration and JWKS at a public location such as an S3 bucket, updating issuer and jwks_uri in the configuration to that location, setting ci_id_tokens_issuer_url in the GitLab configuration for your installation type, and running the ci:validate_id_token_configuration Rake task. Exposing /.well-known/openid-configuration through a different host name does not work, because the document still points at the original instance.

Treat that bucket as a tier-zero asset. GitLab's documentation warns that a misconfigured bucket could lead to the takeover of any cloud account that trusts the OIDC identity: whoever can write to it can publish their own signing key and mint tokens your roles will accept. Block public writes, enable versioning, restrict the bucket policy to a small administration role and alert on any change.

6. Retire the static keys

Once the federated job has run successfully on every branch that needs it, remove the AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY variables at project, group and instance level. Deactivate the IAM user's access keys, wait for at least one full release cycle while watching for failures, then delete the keys and the user. Record the change in your NHI inventory so the identity is marked as replaced, not merely unused.

Verify it worked

  • Caller identity. The job output from aws sts get-caller-identity should show an assumed-role ARN of the form arn:aws:sts::<account>:assumed-role/<role>/GitLabRunner-<project>-<pipeline>, not an IAM user.
  • CloudTrail. Look for AssumeRoleWithWebIdentity events with the GitLab provider as the identity provider and your session name. Subsequent API calls should carry the same session name.
  • Negative tests. Run the same job from a feature branch, from a fork or from another project. Each should fail with AccessDenied. If any of them succeeds, the trust policy is too broad.
  • Key usage. In IAM, the old access keys' last-used date should stop moving after cut-over. If it keeps updating, another pipeline or script is still using them.
  • Variable scan. Search project, group and instance CI/CD variables for any remaining AWS key values, and run your secrets scanner over recent job logs.

Rollback and common errors

Keep the old access key deactivated, not deleted, until the federated path has been stable for a full release cycle. Rollback is then a matter of reactivating the key and restoring the variables, which should be a documented emergency step with an owner and an expiry, not a quiet fallback.

ErrorLikely causeFix
AccessDenied: not authorised to perform sts:AssumeRoleWithWebIdentityThe trust policy does not match the token: wrong project path, branch or tag not covered, or a wildcard used with StringEquals.Decode the token claims in a test job (without printing the token itself), compare sub and aud with the policy, and switch to StringLike for patterns.
Could not connect to the OpenID configuration of the providerThe instance certificate chain is out of order, duplicated or has extra certificates.Check the chain with openssl s_client; it should run from the server certificate through intermediates to the root.
Could not retrieve the verification key from the identity providerThe discovery document or jwks_uri is not publicly reachable, a firewall blocks AWS, or responses take longer than five seconds.Make the endpoints reachable, or publish them to a public location as described above. On recent GitLab releases, check that jwks_uri is not built from an internal host name.
InvalidIdentityTokenThe audience does not match, the issuer URL differs from the provider URL, or the JWKS contains private key material.Align aud and the provider audience list; check the issuer string character for character.
401 errors in older pipelinesThe job still uses CI_JOB_JWT_V2, removed in GitLab 17.0.Move the job to id_tokens.
Token issuance blocked after a project moveGitLab blocks ID tokens when a sub path was previously used by a different project, so a new project cannot inherit old trust.Set ci_id_token_sub_claim_components through the Projects API and update the trust policy to match.

Hardening afterwards

  • Bind production to protected refs and environments. The ID token carries ref_protected, environment and environment_protected claims, and since GitLab 18.7 projects can customise the sub claim to include ref_protected, environment_protected and deployment_tier. On a self-managed instance, where only sub is usable in AWS, adding these components to sub is the way to make the trust policy check them.
  • Use stable IDs on GitLab.com. Pair the path-based sub condition with project_id and namespace_id. Paths can be renamed and later reused; numeric IDs cannot.
  • Do not trust user claims alone. GitLab advises against using user_login or user_email as the only condition because users can change them.
  • Use a distinct audience per service. If the same job also authenticates to Vault or another cloud, give each its own id_tokens entry and aud, so a token captured for one cannot be replayed to another.
  • Protect the pipeline definition. Restrict who can push to protected branches, require approval for changes to .gitlab-ci.yml and included templates, and review which runners can pick up jobs for deployment projects. The GitLab security guide covers these controls.
  • Monitor the role. Alert on AssumeRoleWithWebIdentity calls for production roles outside expected pipelines, on any change to the role trust policy and on any change to the IAM OIDC provider.
  • Apply a permissions boundary or service control policy so that even a misconfigured trust policy cannot grant IAM administration or access outside the intended accounts.

Common failure patterns

  • Provider-only trust. The console wizard produces a trust policy that checks the provider and audience. Left as is, any project on GitLab.com that requests a token with that audience could assume the role. Always add a project-specific sub condition.
  • Wildcards in the wrong place. project_path:mygroup/* trusts every current and future project in the group, including those created by people with modest permissions.
  • Merge request pipelines treated as trusted. In a merge request pipeline, project_path and ref describe the source branch. A role that trusts all branches therefore trusts unreviewed code.
  • Static keys left in place. Federation is set up, but the old IAM user stays active "just in case" and its key remains in a group-level variable.
  • One role for everything. A single broad role is shared by build, test and deploy jobs across many projects, so CloudTrail session names are the only distinction and blast radius is the whole account.
  • Unprotected discovery bucket. On self-managed instances, the public bucket holding the JWKS is created by an engineer and never brought under change control.
  • Long sessions. --duration-seconds is set to the maximum, so temporary credentials remain useful long after the job has finished.

Practitioner checklist

  • IAM OIDC provider created in each target account with the exact GitLab issuer URL and the agreed audience.
  • Each role trust policy checks aud and a project-specific sub; on GitLab.com it also checks project_id and namespace_id.
  • Wildcards only under StringLike, and never across the project path.
  • Production roles accept only protected refs or protected environments.
  • Role permissions scoped to the job, with a short maximum session duration and a permissions boundary.
  • Jobs use id_tokens; no remaining use of CI_JOB_JWT_V2.
  • Role session names include project and pipeline IDs.
  • Negative tests from other branches and projects fail.
  • Old IAM user keys deactivated, then deleted; CI/CD variables removed at every level.
  • Alerts on trust policy changes, provider changes and unexpected role assumptions.
  • For self-managed instances behind a firewall, the published discovery bucket is locked down and monitored.

Standards and references

Related NHI Mgmt Group resources: How to set up workload identity federation for GitLab CI to Azure · GitLab Tokens Security Guide · How to audit AWS IAM Roles Anywhere and OIDC identity providers · Cross-cloud workload identity federation

PDF for subscribers

Take this guide with you

Every section, table and checklist in one PDF, with links to the sources and related guides. Subscribe to our weekly NHI & AI Identity Journal and we’ll email you a download link.

Free weekly newsletter

Subscribe to the NHI & AI Identity Journal

The latest on NHI and Agentic AI security – articles, research, breaches, news and events every week.

Bonus 33% off our NHI Course when you subscribe.

PDF Downloads for Newsletter Subscribers

Get the guide

Enter your details and we’ll email you a download link.

The full guide is free to read online. The PDF is a thank you for subscribing.

Fill in all fields marked * and tick both boxes to continue.