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):
- plan in every merge request, apply on merge to main;
- keyless AWS access through GitLab OIDC: a read-only role for plan, and an admin role for apply that only main can assume;
- semver releases with pinned stack versions in production;
- a CI check that rejects floating module references.
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:
- The job declares
id_tokens. GitLab issues a signed JWT for this job, with claims about the project, the branch and the pipeline. - The job calls
sts:AssumeRoleWithWebIdentitywith the token and a role ARN. This call needs no AWS credentials. - AWS checks the signature against GitLab’s public keys, then checks the role’s trust policy against the claims in the token.
- 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:
- Exact match for apply.
ref_type:branchis in the string on purpose: a tag namedmainhas a differentsuband gets nothing. - Protect main. The trust policy says “code on main”. That means “reviewed code” only if main is a protected branch: no direct pushes, and merges only through approved merge requests. Without that, anyone with Developer access can push to main and get admin.
- Branches cannot escalate. A developer can edit
.gitlab-ci.ymlin a feature branch and request a token, but the token’ssubnames their branch, and the apply role refuses it. - Read-only is not harmless. Plan reads Terraform state, and state can contain secrets. Anyone who can push a branch effectively holds the plan role. Keep secrets out of state where you can, and limit each plan role to the state of its own project.
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:
workflow:rulesruns pipelines for merge requests and for main only, so a branch with an open merge request does not get two pipelines.- Only jobs that extend
.awsreceive an ID token. Thecheck-refsjob needs no cloud access and gets none. - Plan saves plan files. On main, the apply job takes exactly those files and applies them with the admin role. If the state changed between plan and apply, Terraform refuses the stale plan instead of applying something nobody reviewed.
resource_groupmakes applies from different pipelines wait for each other.- Role ARNs are not secrets, so they live in the YAML. Nothing in CI/CD variables has to be secret anymore.
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:
- patch: fixes only; inputs, outputs and resource addresses stay the same;
- minor: new optional inputs or new outputs;
- major: anything that can break a consumer: a removed or renamed input or output, a changed default that changes resources, a resource address change without a
movedblock, a provider major version.
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
- AWS must reach your GitLab. STS fetches GitLab’s OIDC discovery document and signing keys from the instance URL. A self-managed GitLab that is reachable only over VPN cannot act as an identity provider as it is.
- Audience mismatch. If
audinid_tokensdiffers from the client ID registered in AWS, STS answersInvalidIdentityTokenwith “Incorrect token audience”. - Session length. A role allows one-hour sessions by default. Credentials that expire halfway through a long apply leave a half-applied change and possibly a lock nobody released. Raise
max_session_durationon the apply role (up to 12 hours) and request the same length with--duration-seconds. - Debug logging.
CI_DEBUG_TRACEprints variables into the job log, including the temporary credentials. Do not turn it on for these jobs. - Plan files are sensitive. A saved plan can contain secret values in clear text. Keep
expire_inshort and limit who can download job artifacts.
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
- An IAM OIDC provider for your GitLab in every account Terraform manages
- Plan role: read-only plus state and lock access, trusted for any branch of one project
- Apply role: trusted only for
ref_type:branch:ref:mainof that project, with a long enough session - main is protected, and changes reach it only through reviewed merge requests
- No AWS keys in CI/CD variables
- Saved plans applied on main, one apply at a time
- Production pins exact release tags, and CI rejects floating references
The best part of this setup is what disappears: there is no CI key left to rotate, leak or forget about.
