Discuss your project

Blog

Keyless Terraform CI on GitLab: OIDC roles for plan and apply

Mher Poghosyan · 29 November 2026 · 8 min read

The most common way to run Terraform from CI is still an IAM user with admin rights and its access keys in CI/CD variables. It works, and it has three problems. The keys never expire, so a leaked key stays valid until someone notices. Anyone who can change the pipeline can use them: masking hides a value in the job log, not from a job that sends it somewhere else. And AWS cannot tell a plan from a feature branch from an apply on main, because both use the same admin keys.

This article walks through the delivery flow our lead engineer built for a multi-team Terragrunt platform at an online gaming and crypto group (the platform story covers the results):

Names and IDs in the configs below are placeholders.

How GitLab OIDC to AWS works

Instead of holding a key, each job proves where it comes from:

  1. The job declares id_tokens. GitLab issues a signed JWT for this job, with claims about the project, the branch and the pipeline.
  2. The job calls sts:AssumeRoleWithWebIdentity with the token and a role ARN. This call needs no AWS credentials.
  3. AWS checks the signature against GitLab’s public keys, then checks the role’s trust policy against the claims in the token.
  4. STS returns temporary credentials that expire on their own, after one hour by default.

Two claims matter. aud is the audience you set in the pipeline, and it must match the client ID registered in AWS. sub says where the job comes from, in a fixed format:

project_path:platform-live/payments:ref_type:branch:ref:main

Project path, ref type and ref name in one string: that is everything this design needs.

Step 1: register GitLab in the AWS account

Each AWS account that Terraform manages gets one OIDC provider pointing at your GitLab instance (https://gitlab.com for GitLab.com):

resource "aws_iam_openid_connect_provider" "gitlab" {
  url            = "https://gitlab.example.com"
  client_id_list = ["https://gitlab.example.com"]
}

In current versions of the AWS provider, thumbprint_list is optional: for a certificate from a public CA, AWS verifies the chain itself. A self-managed GitLab with a certificate from a private CA still needs the thumbprint.

The provider and the two roles below belong in whatever bootstraps a new account: the one apply that needs a person with admin credentials, once. Everything after it goes through CI.

Step 2: two roles with different trust

The apply role trusts exactly one thing: pipelines on main of one project.

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": {
        "Federated": "arn:aws:iam::<account-id>:oidc-provider/gitlab.example.com"
      },
      "Action": "sts:AssumeRoleWithWebIdentity",
      "Condition": {
        "StringEquals": {
          "gitlab.example.com:aud": "https://gitlab.example.com",
          "gitlab.example.com:sub": "project_path:platform-live/payments:ref_type:branch:ref:main"
        }
      }
    }
  ]
}

The plan role has the same statement with a wider sub, so that plan can run for any branch of the same project. Only the condition differs:

"Condition": {
  "StringEquals": { "gitlab.example.com:aud": "https://gitlab.example.com" },
  "StringLike": { "gitlab.example.com:sub": "project_path:platform-live/payments:*" }
}

What matters here:

A practical starting point for the plan role is the AWS managed ReadOnlyAccess policy plus explicit access to the state bucket. With S3 native locking (use_lockfile = true), even plan takes a lock by writing a .tflock object next to the state, so the role must be able to create and delete those:

{
  "Version": "2012-10-17",
  "Statement": [
    { "Effect": "Allow", "Action": "s3:ListBucket", "Resource": "arn:aws:s3:::<state-bucket>" },
    { "Effect": "Allow", "Action": "s3:GetObject", "Resource": "arn:aws:s3:::<state-bucket>/*" },
    {
      "Effect": "Allow",
      "Action": ["s3:PutObject", "s3:DeleteObject"],
      "Resource": "arn:aws:s3:::<state-bucket>/*.tflock"
    }
  ]
}

If the bucket is encrypted with your own KMS key, add the matching KMS permissions. The apply role gets AdministratorAccess.

Step 3: the pipeline

workflow:
  rules:
    - if: $CI_PIPELINE_SOURCE == "merge_request_event"
    - if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH

stages: [check, plan, apply]

default:
  image: registry.example.com/platform/terragrunt-ci:1.4.0  # pinned Terraform, Terragrunt, AWS CLI

.aws:
  id_tokens:
    AWS_ID_TOKEN:
      aud: https://gitlab.example.com
  before_script:
    - |
      creds=$(aws sts assume-role-with-web-identity \
        --role-arn "$ROLE_ARN" \
        --role-session-name "gitlab-$CI_PROJECT_ID-$CI_JOB_ID" \
        --web-identity-token "$AWS_ID_TOKEN" \
        --duration-seconds "$SESSION_SECONDS" \
        --query 'Credentials.[AccessKeyId,SecretAccessKey,SessionToken]' \
        --output text)
      export AWS_ACCESS_KEY_ID="$(printf '%s' "$creds" | cut -f1)"
      export AWS_SECRET_ACCESS_KEY="$(printf '%s' "$creds" | cut -f2)"
      export AWS_SESSION_TOKEN="$(printf '%s' "$creds" | cut -f3)"
      aws sts get-caller-identity

check-refs:
  stage: check
  script:
    - ./ci/check-refs.sh

plan:
  stage: plan
  extends: .aws
  variables:
    ROLE_ARN: arn:aws:iam::<account-id>:role/gitlab-terraform-plan
    SESSION_SECONDS: "3600"
  script:
    - terragrunt run --all --non-interactive --out-dir "$CI_PROJECT_DIR/.plans" -- plan -input=false -lock-timeout=5m
  artifacts:
    paths: [.plans/]
    expire_in: 1 day

apply:
  stage: apply
  extends: .aws
  needs: [plan]
  resource_group: terraform-apply
  variables:
    ROLE_ARN: arn:aws:iam::<account-id>:role/gitlab-terraform-apply
    SESSION_SECONDS: "7200"
  script:
    - terragrunt run --all --non-interactive --out-dir "$CI_PROJECT_DIR/.plans" -- apply -input=false -lock-timeout=5m
  rules:
    - if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH

How it fits together:

If you would rather not call STS yourself, write the token to a file and set AWS_ROLE_ARN and AWS_WEB_IDENTITY_TOKEN_FILE: the AWS CLI, the Terraform AWS provider and the S3 backend pick them up and assume the role on their own. The explicit call is easier to debug, fails early with a clear error, and lets you choose the session length.

Step 4: releases and pinned versions

Keyless access answers “who may apply”. Versioning answers “what exactly gets applied”. Modules and stacks are released with semver tags, and a release is a promise about the contract:

Production pins an exact tag. An upgrade is a merge request that changes the tag, and its plan shows what the new version does to this environment. Non-production environments take a new release first.

A floating reference, such as ?ref=main, a branch name or no ref at all, breaks this. The code planned in a merge request is not necessarily the code applied after the merge, and two environments “on the same version” can run different code.

Step 5: reject floating references in CI

In live repositories, a short script checks every Terragrunt source:

#!/usr/bin/env bash
# ci/check-refs.sh: every Terragrunt source must be pinned to a release tag (vX.Y.Z).
set -euo pipefail

pinned='\?ref=v[0-9]+\.[0-9]+\.[0-9]+$'
bad=0
while IFS=: read -r file line text; do
  src=$(sed -E 's/^[^"]*"([^"]*)".*/\1/' <<<"$text")
  if [[ ! $src =~ $pinned ]]; then
    echo "$file:$line: not pinned to a release: $src"
    bad=1
  fi
done < <(grep -rnE --include='*.hcl' --exclude-dir='.terragrunt-*' \
           '^[[:space:]]*source[[:space:]]*=' .)
exit "$bad"

It accepts git::https://gitlab.example.com/platform/stacks.git//units/eks?ref=v3.2.1 and rejects ?ref=main, a missing ref, a local path and a ref built from a variable. The last one is on purpose: a reviewer should see the version in the diff.

For plain Terraform modules that call other modules, tflint’s built-in Terraform rules do the same job:

# .tflint.hcl
plugin "terraform" {
  enabled = true
  preset  = "recommended"
}

rule "terraform_module_pinned_source" {
  enabled = true
  style   = "semver"
}

rule "terraform_module_version" {
  enabled = true
  exact   = true
}

Pitfalls

The same rules without CI

Our own infrastructure repository, Terraform and Terragrunt for Cloudflare and GitHub, has one operator and no CI, and the same rules apply locally. make plan-all saves a plan for every unit and prints a summary of changes. make apply-all applies exactly those plans, only where something changes, and refuses plans older than 30 minutes. make lint runs formatting, validation, tflint, shellcheck and gitleaks before every commit. Smaller tooling, same principle: what gets applied is what someone reviewed.

Checklist

The best part of this setup is what disappears: there is no CI key left to rotate, leak or forget about.

#terraform#gitlab#aws#security