08-02 closed by pointing out that GitHub Actions comes with several of the pieces you have to build in Jenkins: ephemeral runners by default, protected environments with mandatory reviewers, native concurrency groups and, above all, an OIDC identity issuer you neither deploy nor maintain. This lesson implements the flow from 08-01 making use of those pieces.
And it settles the most frequently promised debt in the course. 07-04 explained what OIDC is, why it eliminates the static key and what it gives you over an AWS_SECRET_ACCESS_KEY stored as a secret, and then wrote: "the concrete pipeline configuration belongs to module 8". Here is that configuration, complete and end to end: the identity provider in IAM, the two roles with their trust relationships, the sub mistakes that hand over the whole account, the id-token permission and the action that consumes it, plus the equivalents in Azure and GCP.
What you will not find here are the principles: why the apply applies a plan file, why the roles are separated, why the .tfplan is a secret. That belongs to 08-01 and here it is applied without being justified again.
Security warning. GitHub Actions runs code from pull requests. Two sections of this lesson — §3 on the
submistakes and §8 onpull_request_target— describe very common configurations that hand total control of a cloud account to anybody on the internet. Neither of them is theoretical: both are out there in public repositories today.
- The minimum GitHub Actions concepts
Just enough to read the workflows that follow. If you already know it, skip to §2.
| Concept | What it is | The detail that matters for Terraform |
|---|---|---|
| Workflow | A YAML file in .github/workflows/ |
A repository can have several; they are triggered by different events |
Event (on) |
What triggers it | pull_request, push, workflow_run, schedule, workflow_dispatch |
| Job | A set of steps on a runner | Every job starts on a clean machine: the plan has to be propagated |
| Step | A command or an action | run: for shell, uses: for an action |
| Runner | The machine | ubuntu-latest (managed) or self-hosted (§10) |
permissions |
What the job's GITHUB_TOKEN can do |
id-token: write is what enables OIDC |
environment |
An environment with reviewers, secrets and rules | The approval gate from 08-01 §10 |
concurrency |
A mutual-exclusion group | The per-state group from 08-01 §11 |
| Artefact | A file that survives the job | How the .tfplan travels between workflows |
needs |
A dependency between jobs | Sequencing within one workflow |
matrix |
Repeating a job with parameters | The environment matrix |
Two properties worth being clear about from the start, because they explain the design:
Every job is a new machine. There is no shared workspace. What the plan job generates only reaches the apply job as an artefact, and one workflow's artefacts are not visible from another workflow except through the API or with workflow_run.
GITHUB_TOKEN is ephemeral and its scope is defined by permissions. It is created when the workflow starts, expires when it ends, and by default it carries permissions you almost never need. Declaring permissions explicitly in every workflow is the first security measure and the cheapest.
- OIDC end to end: the provider and the roles in AWS
Here is the debt. Let us go in order: first what has to be created in AWS, then what goes in the workflow.
sequenceDiagram
participant W as GitHub Actions job
participant GH as GitHub's OIDC issuer<br/>token.actions.githubusercontent.com
participant IAM as OIDC provider in IAM
participant STS as AWS STS
participant API as AWS API
W->>GH: Request a token<br/>(requires permissions: id-token: write)
GH-->>W: Signed JWT<br/>iss = token.actions.githubusercontent.com<br/>sub = repo:ecomarket/ecomarket-infra:environment:prod<br/>aud = sts.amazonaws.com<br/>exp ≈ 5 min
W->>STS: AssumeRoleWithWebIdentity(role, JWT)
STS->>IAM: Do I know this issuer?<br/>Is the signature valid?
IAM-->>STS: Yes: provider registered
STS->>STS: Evaluate the role's trust relationship:<br/>does the "sub" match? and the "aud"?
STS-->>W: TEMPORARY credentials (1 h)
W->>API: terraform apply
Note over W,API: No static key<br/>anywhere at all
Step 1: the identity provider in IAM
It is created once per AWS account. EcoMarket has three accounts, so it is created three times (or once in each from the bootstrap/ of 07-01).
# bootstrap/oidc-github.tf
# Registers GitHub as an identity issuer recognised by this account.
# NOTE: this is what allows a GitHub token to be used to assume roles
# here. Who can assume WHAT is decided by the roles (step 2).
resource "aws_iam_openid_connect_provider" "github" {
# The issuer URL. EXACT: no trailing slash, no variants.
url = "https://token.actions.githubusercontent.com"
# The "aud" we accept. It is the value the official AWS action
# sets and the one we will check in every role.
client_id_list = ["sts.amazonaws.com"]
# The thumbprint of the issuer's TLS certificate chain.
# Since 2023 AWS verifies it against the public CAs and this field
# is in practice ceremonial, but the resource still requires it.
# Do not write it by hand: read it from the real certificate.
thumbprint_list = [data.tls_certificate.github.certificates[0].sha1_fingerprint]
tags = local.common_tags
}
data "tls_certificate" "github" {
url = "https://token.actions.githubusercontent.com/.well-known/openid-configuration"
}Why the data "tls_certificate" and not a hand-written thumbprint. The thumbprint that circulates around the internet copied from blogs (6938fd4d98bab03faadb97b34396831e3780aea1) was valid and then changed. A stale value produces the error Could not connect to the endpoint URL, which looks nothing like its cause. Reading it from the real certificate means a CA change breaks nothing.
Step 2: the PLAN role, with its trust relationship
# bootstrap/role-terraform-plan.tf
# The role used by the PROPOSAL job. READ-ONLY (08-01 §4).
resource "aws_iam_role" "terraform_plan" {
name = "ecomarket-terraform-plan-${var.environment}"
max_session_duration = 3600
description = "Read-only role for the terraform plan of pull requests."
assume_role_policy = jsonencode({
Version = "2012-10-17"
Statement = [{
Effect = "Allow"
Action = "sts:AssumeRoleWithWebIdentity"
Principal = { Federated = aws_iam_openid_connect_provider.github.arn }
Condition = {
# 1) The "aud" is checked with StringEquals, ALWAYS.
# Without this condition, a token issued for another
# audience could be used here.
StringEquals = {
"token.actions.githubusercontent.com:aud" = "sts.amazonaws.com"
}
# 2) The "sub" identifies the job's CONTEXT.
# Here we DO use StringLike with a wildcard, and it is
# correct: any PR in the repository may plan, because
# this role cannot write ANYTHING.
#
# The wildcard covers:
# repo:ecomarket/ecomarket-infra:pull_request
# repo:ecomarket/ecomarket-infra:ref:refs/heads/main
# but NEVER another repository: the prefix is exact.
StringLike = {
"token.actions.githubusercontent.com:sub" = "repo:ecomarket/ecomarket-infra:*"
}
}
}]
})
tags = local.common_tags
}
# The policy: read everything, write nothing. Plus the state lock,
# which a plan DOES need to write (08-01 §4).
resource "aws_iam_role_policy_attachment" "plan_read_only" {
role = aws_iam_role.terraform_plan.name
policy_arn = "arn:aws:iam::aws:policy/ReadOnlyAccess"
}
resource "aws_iam_role_policy" "plan_state" {
name = "state-and-lock"
role = aws_iam_role.terraform_plan.id
policy = jsonencode({
Version = "2012-10-17"
Statement = [
{
Effect = "Allow"
Action = ["s3:GetObject", "s3:ListBucket"]
Resource = [
"arn:aws:s3:::ecomarket-tfstate-${var.account}",
"arn:aws:s3:::ecomarket-tfstate-${var.account}/ecomarket/${var.environment}/*",
]
},
{
# A plan locks the state: it needs to write the item.
# It is the trade-off explained in 08-01 §4.
Effect = "Allow"
Action = ["dynamodb:GetItem", "dynamodb:PutItem", "dynamodb:DeleteItem"]
Resource = "arn:aws:dynamodb:eu-west-1:${var.account}:table/ecomarket-tfstate-locks"
},
]
})
}Step 3: the APPLY role, with the narrow trust
# bootstrap/role-terraform-apply.tf
# The role used by the APPLY job. WRITE.
resource "aws_iam_role" "terraform_apply" {
name = "ecomarket-terraform-${var.environment}"
max_session_duration = 3600
assume_role_policy = jsonencode({
Version = "2012-10-17"
Statement = [{
Effect = "Allow"
Action = "sts:AssumeRoleWithWebIdentity"
Principal = { Federated = aws_iam_openid_connect_provider.github.arn }
Condition = {
StringEquals = {
"token.actions.githubusercontent.com:aud" = "sts.amazonaws.com"
# THERE IS NO WILDCARD HERE. StringEquals with a LIST of exact
# values: the token must match one of them.
#
# ref:refs/heads/main → only from the main branch
# environment:<environment> → only from a job that DECLARES
# that environment, which in turn
# requires reviewers. This is the
# piece that makes the approval gate
# exist on the AWS side too.
"token.actions.githubusercontent.com:sub" = [
"repo:ecomarket/ecomarket-infra:ref:refs/heads/main",
"repo:ecomarket/ecomarket-infra:environment:${var.environment}",
]
}
}
}]
})
tags = local.common_tags
}And for prod, the narrower version still — only the environment, not even the branch:
# In prod the branch is NOT enough: you must go through the protected
# environment. With "ref:refs/heads/main" in the list, any job running
# on main — a new one somebody adds included — could apply to
# production without going past the reviewers.
"token.actions.githubusercontent.com:sub" = [
"repo:ecomarket/ecomarket-infra:environment:prod",
]That difference between dev/staging and prod is the heart of the whole section: in production, the only way to obtain a token with the right sub is for the job to declare environment: prod, and declaring that environment activates the mandatory reviewers. The gate cannot be routed around by writing another workflow.
The catalogue of sub values
| Job context | sub value |
|---|---|
| Push to a branch | repo:ORG/REPO:ref:refs/heads/NAME |
| Push of a tag | repo:ORG/REPO:ref:refs/tags/vX.Y.Z |
| Pull request | repo:ORG/REPO:pull_request |
Job with environment: |
repo:ORG/REPO:environment:NAME |
workflow_dispatch on main |
repo:ORG/REPO:ref:refs/heads/main |
| A reusable workflow being called | The calling workflow's sub, unless job_workflow_ref is configured |
The last row matters for §11: a reusable workflow inherits the context of whoever calls it, and that is what lets you centralise the pipeline without losing the restriction.
- The
sub mistakes that hand over the account
sub mistakes that hand over the accountFour common ways of writing the trust relationship wrongly. All four turn up in real repositories and in forum answers.
Mistake 1: the total wildcard
# CATASTROPHIC. Do not copy it, not even to try it out.
StringLike = {
"token.actions.githubusercontent.com:sub" = "*"
}What it grants: any workflow, in any GitHub repository, belonging to anybody in the world, can assume this role. An attacker creates a repository, writes a three-line workflow with role-to-assume pointing at your ARN, and has your permissions. They only need to know the ARN, which appears in any public workflow log, in a screenshot or in an error message.
Mistake 2: the wildcard on the organisation
What it grants: any repository in the organisation. The problem is that organisations have repositories of all kinds: the marketing website, somebody's prototype, an archived repository with lax permissions. And it is enough for somebody to be able to create a repository in the organisation for them to be able to apply to production. In many organisations, that is everybody.
Mistake 3: the wildcard at the end of the correct repository
# SUBTLE AND VERY FREQUENT. It is the one we use deliberately in the PLAN
# role, and it is a serious mistake in the APPLY role.
StringLike = {
"token.actions.githubusercontent.com:sub" = "repo:ecomarket/ecomarket-infra:*"
}What it grants: the repository is correct, but the wildcard covers :pull_request. And a PR can come from anybody:
- Somebody opens a PR against
ecomarket-infra. - The plan workflow runs with the PR's code.
- The PR has modified
.github/workflows/terraform-plan.ymlto assume the apply role instead of the plan one. - The token's
subisrepo:ecomarket/ecomarket-infra:pull_request, which matches the wildcard. - The PR has write access over production, with nobody having approved it.
It is acceptable in the plan role precisely because that role cannot write. In the apply role it is a complete hole.
Mistake 4: StringLike with a value that has no wildcard
# It works, but it is a trap waiting to happen.
StringLike = {
"token.actions.githubusercontent.com:sub" = "repo:ecomarket/ecomarket-infra:environment:prod"
}With no wildcard, StringLike behaves like StringEquals and the effect today is identical. The problem is maintenance: the operator says "pattern match", and the day somebody adds a * to "fix" something, nobody will notice that they have widened the scope. The rule: StringEquals unless the wildcard is deliberate and commented.
The decision table
| Role | Operator | Value | Why |
|---|---|---|---|
Plan (dev/staging/prod) |
StringLike |
repo:ecomarket/ecomarket-infra:* |
Any PR needs to plan; the role does not write |
Apply dev |
StringEquals |
[...:ref:refs/heads/main, ...:environment:dev] |
Only after merging |
Apply staging |
StringEquals |
[...:environment:staging] |
Only by going through the protected environment |
Apply prod |
StringEquals |
[...:environment:prod] |
Likewise, and with no branch as an alternative |
How to verify that the trust is what you think it is
# 1. Read the role's real trust relationship, not the code's.
aws iam get-role --role-name ecomarket-terraform-prod \
--query 'Role.AssumeRolePolicyDocument' | jq .
# 2. Simulate: which "sub" would be accepted? The practical way is to
# launch a test workflow WITHOUT the environment and check that it
# fails. A failure here is the proof that the gate exists.
# 3. Audit every role in the account that trusts GitHub, looking for
# dangerous wildcards. This is run periodically.
aws iam list-roles --query 'Roles[].RoleName' --output text | tr '\t' '\n' | \
while read -r role; do
doc=$(aws iam get-role --role-name "$role" --query 'Role.AssumeRolePolicyDocument' 2>/dev/null)
echo "$doc" | grep -q "token.actions.githubusercontent.com" || continue
sub=$(echo "$doc" | jq -r '..|.["token.actions.githubusercontent.com:sub"]? // empty')
case "$sub" in
'*'|'repo:*') echo "CRITICAL $role → sub=$sub" ;;
*'/*'*) echo "SERIOUS $role → sub=$sub" ;;
*':*') echo "REVIEW $role → sub=$sub (is it a read-only role?)" ;;
*) echo "ok $role → sub=$sub" ;;
esac
doneThat script deserves a place in the security cron job. It is the check that turns "we think it is configured properly" into a fact.
permissions: id-token: write and configure-aws-credentials
permissions: id-token: write and configure-aws-credentialsWith AWS configured, the workflow side is five lines.
jobs:
plan:
runs-on: ubuntu-latest
permissions:
# WITHOUT this, the OIDC token request fails and the message is
# confusing: "Credentials could not be loaded". It is mistake no. 1.
id-token: write
# The minimum for the rest: read the code and comment on the PR.
contents: read
pull-requests: write
steps:
- uses: actions/checkout@v4
- name: Assume the plan role via OIDC
uses: aws-actions/configure-aws-credentials@v4
with:
role-to-assume: arn:aws:iam::123456789014:role/ecomarket-terraform-plan-prod
aws-region: eu-west-1
# The session name reaches CloudTrail: it is the piece that joins
# an API call to the PR that caused it (07-04 §16).
role-session-name: gha-plan-prod-${{ github.run_id }}
# The smallest sufficient duration: a plan does not need an hour.
role-duration-seconds: 1800
# Mask the account identifier in the logs.
mask-aws-account-id: true| Setting | What it does | Why |
|---|---|---|
id-token: write |
Allows requesting the JWT | Without it there is no OIDC. write is the level, it does not mean it writes anything |
role-to-assume |
The role | Different per job: plan or apply |
role-session-name |
The STS session name | Traceability in CloudTrail |
role-duration-seconds |
Credential lifetime | The shortest that suffices; the maximum is the role's max_session_duration |
mask-aws-account-id |
Hides the identifier in the log | Reduces what a public log reveals |
The detail that confuses everybody: id-token: write sounds like a dangerous write permission. It is not: it is the permission level that enables requesting an identity token. The name is unfortunate and forgetting it is a constant source of errors.
And the detail that breaks security unnoticed: declaring permissions for the whole workflow instead of per job. If the block is at the top, every job inherits it, including the one that does not need it. The correct practice is to declare it in each job with the minimum.
- Equivalents in Azure and GCP
| AWS | Azure | GCP | |
|---|---|---|---|
| Object that registers the issuer | aws_iam_openid_connect_provider |
A federated credential on the app registration | A workload identity pool + provider |
| Terraform resource | aws_iam_openid_connect_provider |
azuread_application_federated_identity_credential |
google_iam_workload_identity_pool_provider |
| Identity being assumed | An IAM role | A service principal | A service account |
| Context restriction | A condition on sub |
The federated credential's subject field |
attribute_condition on the provider |
| Workflow action | aws-actions/configure-aws-credentials |
azure/login |
google-github-actions/auth |
| Key variable | — | ARM_USE_OIDC: true |
workload_identity_provider |
| Workflow permission | id-token: write |
id-token: write |
id-token: write |
Azure
# One federated credential PER CONTEXT. Azure does not allow wildcards
# in the "subject": you have to create one per branch, environment or
# event type. It is more verbose and, in practice, safer: you cannot
# write a wildcard by accident.
resource "azuread_application_federated_identity_credential" "apply_prod" {
application_id = azuread_application.terraform.id
display_name = "gha-apply-prod"
description = "GitHub Actions, protected prod environment"
audiences = ["api://AzureADTokenExchange"]
issuer = "https://token.actions.githubusercontent.com"
subject = "repo:ecomarket/ecomarket-infra:environment:prod"
}
resource "azuread_application_federated_identity_credential" "plan_pr" {
application_id = azuread_application.terraform_plan.id
display_name = "gha-plan-pr"
audiences = ["api://AzureADTokenExchange"]
issuer = "https://token.actions.githubusercontent.com"
# A DIFFERENT credential for PRs, associated with the READ-ONLY
# application. The separation from 08-01 §4, in Azure.
subject = "repo:ecomarket/ecomarket-infra:pull_request"
}- uses: azure/login@v2
with:
client-id: ${{ vars.AZURE_CLIENT_ID }} # not a secret: it is an identifier
tenant-id: ${{ vars.AZURE_TENANT_ID }}
subscription-id: ${{ vars.AZURE_SUBSCRIPTION_ID }}
- name: Plan
env:
# The azurerm provider needs to be told to use OIDC; without this
# variable it looks for a client secret that does not exist.
ARM_USE_OIDC: "true"
ARM_CLIENT_ID: ${{ vars.AZURE_CLIENT_ID }}
ARM_TENANT_ID: ${{ vars.AZURE_TENANT_ID }}
ARM_SUBSCRIPTION_ID: ${{ vars.AZURE_SUBSCRIPTION_ID }}
run: terraform plan -out=plan.tfplanGCP
resource "google_iam_workload_identity_pool_provider" "github" {
workload_identity_pool_id = google_iam_workload_identity_pool.ci.workload_identity_pool_id
workload_identity_pool_provider_id = "github"
oidc { issuer_uri = "https://token.actions.githubusercontent.com" }
attribute_mapping = {
"google.subject" = "assertion.sub"
"attribute.repository" = "assertion.repository"
"attribute.ref" = "assertion.ref"
"attribute.environment" = "assertion.environment"
}
# attribute_condition is MANDATORY since 2024 and it is the defence
# equivalent to the "sub" condition in AWS. Without it, any GitHub
# repository could federate against this provider.
attribute_condition = <<-CEL
assertion.repository == "ecomarket/ecomarket-infra" &&
assertion.environment == "prod"
CEL
}
resource "google_service_account_iam_member" "federation" {
service_account_id = google_service_account.terraform_prod.name
role = "roles/iam.workloadIdentityUser"
member = join("", [
"principalSet://iam.googleapis.com/",
google_iam_workload_identity_pool.ci.name,
"/attribute.repository/ecomarket/ecomarket-infra",
])
}- uses: google-github-actions/auth@v2
with:
workload_identity_provider: projects/123456789/locations/global/workloadIdentityPools/ci/providers/github
service_account: [email protected]
- The proposal workflow:
terraform-plan.yml
terraform-plan.yml# .github/workflows/terraform-plan.yml
# The PROPOSAL job (08-01 §3): everything that runs on a PR.
name: Terraform · Plan
on:
pull_request:
# pull_request and NOT pull_request_target. See §10: the difference
# is the entire security of this workflow.
paths:
- 'infra/**'
- 'modules/**'
- 'environments/**' # shared files: they trigger everything
- 'backends/**'
- 'ci/policies/**'
- '.github/workflows/terraform-*.yml'
# Nothing by default. Each job asks for its own.
permissions: {}
concurrency:
# A PR with five pushes in a row: only the last plan is of interest.
group: tf-plan-${{ github.event.pull_request.number }}
cancel-in-progress: true # correct on PLAN; never on apply
env:
TF_IN_AUTOMATION: "1"
TF_INPUT: "false"
AWS_REGION: eu-west-1
jobs:
plan:
name: Plan · ${{ matrix.environment }}
runs-on: ubuntu-latest
permissions:
id-token: write # OIDC
contents: read # checkout
pull-requests: write # comment the plan
strategy:
# No fail-fast: if the dev plan fails, we still want to see the
# staging and prod ones. A failure can be specific to one environment.
fail-fast: false
matrix:
environment: [dev, staging, prod]
environment: ${{ matrix.environment }}-plan # no reviewers: it only groups secrets
steps:
- uses: actions/checkout@v4
with:
# Pinning the action by SHA would be ideal (§10). Here the major
# tag is used for readability; in EcoMarket's real repository,
# Dependabot keeps them pinned by SHA.
persist-credentials: false # keep the token out of .git/config
- name: Read the repository's Terraform version
id: version
run: echo "tf=$(cat .terraform-version)" >> "$GITHUB_OUTPUT"
- uses: hashicorp/setup-terraform@v3
with:
terraform_version: ${{ steps.version.outputs.tf }}
# terraform_wrapper wraps the binary in a script that captures
# stdout/stderr and exposes them as step outputs.
# It is CONVENIENT and it has two side effects:
# - the exit code is altered: -detailed-exitcode does NOT
# propagate properly (this matters in the drift workflow).
# - the output is truncated at 1 MB.
# Here we leave it on because we want steps.plan.outputs.stdout.
terraform_wrapper: true
# ---------- Quality: cheap first, no credentials ----------
- name: Format
run: terraform fmt -check -recursive -no-color
- name: Initialise without a backend (for validate)
run: terraform -chdir=infra/app init -backend=false -lockfile=readonly -no-color
- name: Validate
run: terraform -chdir=infra/app validate -no-color
- uses: terraform-linters/setup-tflint@v4
with: { tflint_version: v0.53.0 }
- name: tflint
run: |
tflint --init
tflint --chdir=infra/app --recursive --format=compact
- name: Trivy (static analysis of the code)
uses: aquasecurity/[email protected]
with:
scan-type: config
scan-ref: .
exit-code: '1'
severity: HIGH,CRITICAL
trivyignores: .trivyignore # with a justification and a review date
- name: Unit tests
# mock_provider (07-03): no cloud, no credentials, fast.
run: terraform -chdir=infra/app test -filter=tests/unit -no-color
# ---------- From here on credentials ARE needed ----------
- name: Assume the PLAN role (read-only)
uses: aws-actions/configure-aws-credentials@v4
with:
role-to-assume: arn:aws:iam::${{ vars[format('ACCOUNT_{0}', matrix.environment)] }}:role/ecomarket-terraform-plan-${{ matrix.environment }}
aws-region: ${{ env.AWS_REGION }}
role-session-name: gha-plan-${{ matrix.environment }}-${{ github.run_id }}
role-duration-seconds: 1800
mask-aws-account-id: true
- name: Provider cache
uses: actions/cache@v4
with:
path: ~/.terraform.d/plugin-cache
# The key includes the lockfile hash: if a provider changes,
# the cache changes. Without this, the cache serves old
# binaries indefinitely.
key: tf-plugins-${{ runner.os }}-${{ hashFiles('**/.terraform.lock.hcl') }}
restore-keys: tf-plugins-${{ runner.os }}-
- name: Initialise with the environment's backend
run: |
mkdir -p ~/.terraform.d/plugin-cache
echo "plugin_cache_dir = \"$HOME/.terraform.d/plugin-cache\"" > ~/.terraformrc
terraform -chdir=infra/app init -reconfigure -lockfile=readonly -no-color \
-backend-config="$PWD/backends/${{ matrix.environment }}.hcl"
- name: Plan
id: plan
run: |
terraform -chdir=infra/app plan -no-color -lock-timeout=5m \
-var-file="$PWD/environments/common.auto.tfvars" \
-var-file="$PWD/environments/${{ matrix.environment }}.tfvars" \
-out="${{ matrix.environment }}-app.tfplan"
date +%s > "infra/app/${{ matrix.environment }}-app.tfplan.created"
# ---------- Plan analysis: NONE of this leaves the runner ----------
- name: Convert the plan to JSON
run: |
cd infra/app
# NOTE: plan.json contains the sensitive values IN THE CLEAR.
# It is not uploaded as an artefact nor published on the PR.
terraform show -json "${{ matrix.environment }}-app.tfplan" > plan.json
- name: Policies (Conftest over the plan)
run: |
curl -fsSL https://github.com/open-policy-agent/conftest/releases/download/v0.56.0/conftest_0.56.0_Linux_x86_64.tar.gz \
| tar -xz -C /usr/local/bin conftest
conftest test --policy ci/policies/ --parser json infra/app/plan.json
- name: Destruction guard
run: ci/destroy-guard.sh ${{ matrix.environment }}
working-directory: .
env:
PLAN_JSON: infra/app/plan.json
- name: Readable plan summary
run: |
cd infra/app
# WITHOUT -json: it respects sensitive. THIS is what goes to the PR.
terraform show -no-color "${{ matrix.environment }}-app.tfplan" > plan.txt
- name: Comment the plan on the PR
uses: actions/github-script@v7
env:
ENVIRONMENT: ${{ matrix.environment }}
with:
script: |
const fs = require('fs');
const script = require('./ci/comment-plan.js');
await script({ github, context, core, fs });
# ---------- The artefact: encrypted, short-lived, restricted ----------
- name: Encrypt the plan before uploading it
run: |
sudo apt-get install -y age >/dev/null 2>&1
cd infra/app
age --encrypt --recipient-file ../../ci/plan-key.pub \
-o "${{ matrix.environment }}-app.tfplan.age" \
"${{ matrix.environment }}-app.tfplan"
# Nothing in the clear survives the step.
rm -f "${{ matrix.environment }}-app.tfplan" plan.json
- uses: actions/upload-artifact@v4
with:
name: plan-${{ matrix.environment }}
path: |
infra/app/${{ matrix.environment }}-app.tfplan.age
infra/app/${{ matrix.environment }}-app.tfplan.created
infra/app/plan.txt
# Days, not months (08-01 §6).
retention-days: 7About terraform_wrapper
hashicorp/setup-terraform installs, by default, a wrapper around the binary. It deserves a table because it decides two things about the workflow.
With terraform_wrapper: true |
With terraform_wrapper: false |
|---|---|
steps.X.outputs.stdout available |
You have to redirect to a file and read it |
steps.X.outputs.exitcode available |
The exit code is the real one |
-detailed-exitcode does not propagate properly |
-detailed-exitcode works as it should |
| The output is truncated at 1 MB | No truncation |
terraform is a script, not the binary |
terraform is the binary |
EcoMarket's rule: true in the plan workflow (we want the outputs for the comment), false in the drift one, because there exit code 2 is the entire point (08-01 §12).
- The PR comment with
actions/github-script
actions/github-scriptThe script is kept separately so it can be tested and so there are not 80 lines of JavaScript inside the YAML.
// ci/comment-plan.js
// Publishes or UPDATES the plan comment on the PR.
module.exports = async ({ github, context, core, fs }) => {
const environment = process.env.ENVIRONMENT;
const dir = 'infra/app';
// The hidden marker is what lets us find OUR comment among all the
// ones on the PR and edit it instead of adding another. Without this,
// a PR with fifteen pushes piles up fifteen plans and nobody knows which.
const marker = `<!-- tf-plan:${environment}:app -->`;
// --- Counts, read from the text (the JSON is gone: it was sensitive) ---
const planText = fs.readFileSync(`${dir}/plan.txt`, 'utf8');
const line = planText.match(/Plan: (\d+) to add, (\d+) to change, (\d+) to destroy/);
const [create, change, destroy] = line
? [line[1], line[2], line[3]]
: ['?', '?', '?'];
const noChanges = /No changes\./.test(planText);
const headline = noChanges
? 'No changes'
: (Number(destroy) > 0 ? `DESTROYS ${destroy} resource(s)` : 'Changes with no destructions');
// --- Truncation: GitHub limits a comment to 65,536 characters ---
// If you exceed it, the API fails and you lose the WHOLE comment,
// including the headline, which is the important part. Truncate with room.
const LIMIT = 55000;
let planBody = planText;
let truncated = false;
if (planBody.length > LIMIT) {
// Keep the END of the plan: that is where the "Plan: N to add..."
// summary and the last resources are. The start is usually state refresh.
planBody = '... (beginning truncated) ...\n\n' + planBody.slice(-LIMIT);
truncated = true;
}
const body = `${marker}
## Terraform plan · \`${environment}\` · ${headline}
| Create | Change | **Destroy** |
| :---: | :---: | :---: |
| ${create} | ${change} | **${destroy}** |
Run [#${context.runNumber}](${context.serverUrl}/${context.repo.owner}/${context.repo.repo}/actions/runs/${context.runId}) · commit \`${context.payload.pull_request.head.sha.slice(0, 8)}\`
<details><summary>Full plan${truncated ? ' · TRUNCATED' : ''}</summary>
\`\`\`terraform
${planBody}
\`\`\`
${truncated ? '\n> The full plan is in the `plan-' + environment + '` artefact of this run.\n' : ''}
</details>
`;
// --- Find the previous comment and decide whether to edit or create ---
const comments = await github.paginate(github.rest.issues.listComments, {
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: context.issue.number,
});
const previous = comments.find(c =>
c.user.type === 'Bot' && c.body.includes(marker));
if (previous) {
await github.rest.issues.updateComment({
owner: context.repo.owner, repo: context.repo.repo,
comment_id: previous.id, body: body,
});
core.info(`Comment ${previous.id} updated for ${environment}.`);
} else {
await github.rest.issues.createComment({
owner: context.repo.owner, repo: context.repo.repo,
issue_number: context.issue.number, body: body,
});
core.info(`Comment created for ${environment}.`);
}
// The job summary: visible without opening the PR.
await core.summary
.addHeading(`Plan ${environment}`)
.addTable([
[{data: 'Create', header: true}, {data: 'Change', header: true}, {data: 'Destroy', header: true}],
[create, change, destroy],
])
.write();
};The three details that make this work well:
- The marker includes the environment. With a three-environment matrix there are three comments, each with its own marker. Without the environment in the marker, the three jobs would fight over the same comment and only the last would survive.
- Truncation keeps the end of the plan, not the beginning. The beginning is state-refresh lines; the end has the counts and the last resources.
github.paginate. A heavily discussed PR has more than 30 comments, andlistCommentsreturns the first page. Without pagination, the previous comment "disappears" and a new one is created on every push.
- The apply workflow:
terraform-apply.yml
terraform-apply.yml# .github/workflows/terraform-apply.yml
# The APPLY job (08-01 §3). Triggered on merge.
name: Terraform · Apply
on:
push:
branches: [main]
paths:
- 'infra/**'
- 'modules/**'
- 'environments/**'
- 'backends/**'
workflow_dispatch:
inputs:
environment:
description: Environment to apply
type: choice
options: [dev, staging, prod]
default: dev
permissions: {}
env:
TF_IN_AUTOMATION: "1"
TF_INPUT: "false"
AWS_REGION: eu-west-1
jobs:
# ---------------- dev: automatic (08-01 §10) ----------------
dev:
name: Apply · dev
runs-on: ubuntu-latest
environment: dev # no reviewers: the review was the PR
concurrency:
# The group identifies the STATE, not the repository.
group: tf-apply-dev-app
cancel-in-progress: false # NEVER cancel an apply half-way
permissions:
id-token: write
contents: read
steps:
- uses: actions/checkout@v4
- uses: ./.github/actions/terraform-apply
with:
environment: dev
role: arn:aws:iam::123456789012:role/ecomarket-terraform-dev
# ---------------- staging: with reviewers ----------------
staging:
name: Apply · staging
needs: dev # promotion: dev first, always
runs-on: ubuntu-latest
environment: staging # with mandatory reviewers configured
concurrency:
group: tf-apply-staging-app
cancel-in-progress: false
permissions:
id-token: write
contents: read
steps:
- uses: actions/checkout@v4
- uses: ./.github/actions/terraform-apply
with:
environment: staging
role: arn:aws:iam::123456789013:role/ecomarket-terraform-staging
# ---------------- prod: reviewers + window ----------------
prod:
name: Apply · prod
needs: staging
runs-on: ubuntu-latest
# Declaring this environment does TWO things at once:
# 1) it activates GitHub's mandatory reviewers
# 2) it puts "environment:prod" in the OIDC token's sub, which is
# the ONLY thing the prod role accepts (§2). The gate exists
# on both sides.
environment: prod
concurrency:
group: tf-apply-prod-app
cancel-in-progress: false
permissions:
id-token: write
contents: read
steps:
- uses: actions/checkout@v4
- name: Deployment window
run: ci/deployment-window.sh
- uses: ./.github/actions/terraform-apply
with:
environment: prod
role: arn:aws:iam::123456789014:role/ecomarket-terraform-prodAnd the composite action the three jobs share:
# .github/actions/terraform-apply/action.yml
name: Apply a Terraform plan
description: Retrieves the PR's plan, checks freshness and applies.
inputs:
environment: { required: true }
role: { required: true }
runs:
using: composite
steps:
- name: Download the plan of the PR that produced this commit
uses: actions/github-script@v7
id: download
with:
script: |
// The artefact was generated by the PLAN workflow, in ANOTHER run.
// It has to be located by the merged commit's SHA.
const runs = await github.rest.actions.listWorkflowRuns({
owner: context.repo.owner, repo: context.repo.repo,
workflow_id: 'terraform-plan.yml',
head_sha: context.payload.head_commit
? context.payload.head_commit.id
: context.sha,
});
if (runs.data.workflow_runs.length === 0) {
core.setFailed(`There is no plan run for commit ${context.sha}.
With no approved plan there is NO apply: re-run the plan workflow
and review the result before applying.`);
return;
}
core.setOutput('run_id', runs.data.workflow_runs[0].id);
- uses: actions/download-artifact@v4
with:
name: plan-${{ inputs.environment }}
path: infra/app
run-id: ${{ steps.download.outputs.run_id }}
github-token: ${{ github.token }}
- name: Decrypt the plan
shell: bash
env:
KEY: ${{ env.PLAN_PRIVATE_KEY }}
run: |
set +x # the key never in the log
set -euo pipefail
umask 077
printf '%s' "$KEY" > /tmp/key.age
cd infra/app
age --decrypt --identity /tmp/key.age \
-o "${{ inputs.environment }}-app.tfplan" \
"${{ inputs.environment }}-app.tfplan.age"
shred -u /tmp/key.age
- name: Check the plan's freshness
shell: bash
run: ci/check-plan-freshness.sh "infra/app/${{ inputs.environment }}-app.tfplan"
- uses: aws-actions/configure-aws-credentials@v4
with:
role-to-assume: ${{ inputs.role }}
aws-region: eu-west-1
role-session-name: gha-apply-${{ inputs.environment }}-${{ github.run_id }}
role-duration-seconds: 3600
- uses: hashicorp/setup-terraform@v3
with:
terraform_version: ${{ env.TF_VERSION }}
terraform_wrapper: false
- name: Apply THE saved plan
shell: bash
run: |
set -euo pipefail
terraform -chdir=infra/app init -reconfigure -lockfile=readonly -no-color \
-backend-config="$PWD/backends/${{ inputs.environment }}.hcl"
# THE file. No -auto-approve (not needed) and no -var-file
# (it would error: the variables are INSIDE the plan).
terraform -chdir=infra/app apply -no-color -lock-timeout=10m \
"${{ inputs.environment }}-app.tfplan"
- name: Clean up
if: always()
shell: bash
run: find . -name '*.tfplan' -delete || trueworkflow_run versus push: the two models
push to main (the one above) |
workflow_run after the plan |
|
|---|---|---|
| When it triggers | On merge | When the plan workflow finishes |
| Artefact | It has to be found by SHA | It comes in the event's context |
| Context | The merged commit | The plan run, which may come from a PR |
| Risk | Low | High if not filtered: workflow_run runs with main's workflow but can originate in a fork's PR |
| When to use it | The normal case | When plan and apply have to be chained without merging |
EcoMarket uses push. workflow_run is the mechanism that lets you grant elevated permissions to something that originated in a PR, and although it has legitimate uses, in an infrastructure repository any mechanism that gives write permissions to something that started in a PR is a risk that does not pay off.
- The scheduled drift workflow
# .github/workflows/terraform-drift.yml
name: Terraform · Drift
on:
schedule:
# Staggered by environment (08-02 §10): if dev fails on credentials,
# you see it an hour before prod tries.
- cron: '17 2 * * *' # dev
- cron: '17 3 * * *' # staging
- cron: '17 4 * * *' # prod
workflow_dispatch:
permissions: {}
jobs:
drift:
runs-on: ubuntu-latest
permissions:
id-token: write
contents: read
issues: write # to open the issue
strategy:
fail-fast: false
matrix:
environment: [dev, staging, prod]
component: [network, data, app]
steps:
- uses: actions/checkout@v4
- uses: hashicorp/setup-terraform@v3
with:
terraform_version: ${{ env.TF_VERSION }}
# false: we need -detailed-exitcode to arrive intact.
terraform_wrapper: false
- uses: aws-actions/configure-aws-credentials@v4
with:
role-to-assume: arn:aws:iam::${{ vars[format('ACCOUNT_{0}', matrix.environment)] }}:role/ecomarket-terraform-plan-${{ matrix.environment }}
aws-region: eu-west-1
role-session-name: gha-drift-${{ matrix.environment }}-${{ github.run_id }}
- name: Detect drift
id: drift
# continue-on-error: code 2 is NOT a workflow failure,
# it is the finding we were looking for (08-01 §12).
continue-on-error: true
run: |
ci/detect-drift.sh ${{ matrix.environment }} ${{ matrix.component }}
echo "code=$?" >> "$GITHUB_OUTPUT"
- name: Open or update the issue
if: steps.drift.outputs.code == '2'
uses: actions/github-script@v7
with:
script: |
const environment = '${{ matrix.environment }}';
const component = '${{ matrix.component }}';
const title = `Drift detected: ${environment}/${component}`;
const detail = require('fs')
.readFileSync(`infra/${component}/drift.txt`, 'utf8')
.slice(0, 50000);
// Deduplication (08-01, solution 3): if there is already an open
// issue for this pair, we COMMENT instead of opening another.
const open = await github.rest.issues.listForRepo({
owner: context.repo.owner, repo: context.repo.repo,
state: 'open', labels: 'drift',
});
const existing = open.data.find(i => i.title === title);
const body = `Detection of ${new Date().toISOString().slice(0,10)}
(run ${context.runId}):
\`\`\`
${detail}
\`\`\``;
if (existing) {
await github.rest.issues.createComment({
owner: context.repo.owner, repo: context.repo.repo,
issue_number: existing.number, body: body,
});
// At 5 comments, escalate: 5 nights is a pending decision,
// not one more alert.
if (existing.comments >= 4) {
await github.rest.issues.addLabels({
owner: context.repo.owner, repo: context.repo.repo,
issue_number: existing.number, labels: ['chronic-drift'],
});
}
} else {
await github.rest.issues.create({
owner: context.repo.owner, repo: context.repo.repo,
title: title,
labels: ['drift', `environment:${environment}`],
body: `The infrastructure of \`${environment}/${component}\` does not match the code.
Possible ways out (one of the three, do not silence it):
1. **Correct**: apply the code and match again.
2. **Adopt**: if the manual change was right, bring it into the code.
3. **Exclude**: \`ignore_changes\` with a comment saying who manages it.
${body}`,
});
}
- name: Fail if the plan could not run
if: steps.drift.outputs.code == '1'
run: |
echo "The drift plan failed (code 1): credentials, network or syntax."
exit 1The distinction between continue-on-error and the if that follows is what translates the three codes into GitHub Actions. The step does not fail the workflow; the code is captured and the decision comes afterwards. Without continue-on-error, code 2 would abort the job before it could open the issue.
- GitHub Actions-specific security
pull_request versus pull_request_target
This is the most dangerous distinction in GitHub Actions, and with Terraform it is especially serious.
pull_request |
pull_request_target |
|
|---|---|---|
| Which code runs | The base branch's workflow; the checkout brings the PR's code | The base branch's workflow and context |
| Secrets available | No, if the PR comes from a fork | Yes, all of them |
GITHUB_TOKEN |
Read-only from a fork | Write |
| OIDC | The sub is :pull_request |
The sub is :ref:refs/heads/main |
| What it exists for | The normal case | Commenting on forks' PRs, labelling, etc. |
The concrete danger:
# CATASTROPHIC with Terraform. Do not write this.
on:
pull_request_target: # ← main's context, with secrets
jobs:
plan:
steps:
- uses: actions/checkout@v4
with:
ref: ${{ github.event.pull_request.head.sha }} # ← the PR's code
- run: terraform planThose two lines together run arbitrary code from a stranger with the production secrets and a write token. And with Terraform you do not even need to touch the workflow: a data "external" in any .tf file is enough, or a provisioner, or a .tflint.hcl that downloads a plugin.
Worse still: because the OIDC token's sub would be ref:refs/heads/main, the dev apply role would accept it.
The rule, with no caveats: in a Terraform repository, pull_request always. If you need to comment on forks' PRs, you do it in a separate workflow with workflow_run that does not run the PR's code, only reads the artefact.
Forks and secrets
In a PR from a fork with pull_request, GitHub exposes no secrets and does not allow OIDC with permissions. That breaks the plan workflow, which needs read credentials. The options:
| Option | What it implies |
|---|---|
| Do not accept forks' PRs in the infrastructure repository | The normal and recommended choice: infrastructure is internal |
| Require manual approval to run new contributors' workflows | An organisation setting; it reduces, it does not eliminate |
Run only fmt/validate/tflint on forks' PRs |
Useful in public module repositories: they need no cloud |
EcoMarket: ecomarket-infra is private and does not accept forks. The module repositories are public and their PR workflow runs only steps that need no credentials (§12).
Pinning actions by SHA
# Fragile: the tag can be moved.
- uses: actions/checkout@v4
# Correct: the SHA is immutable.
- uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # v4.1.1An action is third-party code that runs on your runner with access to your credentials. If the maintainer of a popular action moves the v4 tag to a malicious commit, everybody who references it by tag runs that code in their next workflow. This has happened.
It is the same supply-chain argument from 07-04, applied to actions: pinning by SHA is the equivalent of .terraform.lock.hcl. With the readable version as a trailing comment, and Dependabot to update them through a reviewable PR.
An organisation-level complement: restrict which actions can be used to an allowed list (only those created by GitHub and the verified ones, plus an explicit list).
GITHUB_TOKEN with minimum permissions
permissions: {} # nothing by default, at workflow level
jobs:
plan:
permissions: # and each job asks for exactly what it needs
id-token: write
contents: read
pull-requests: writeThe organisation's default setting should be read, not write. A GITHUB_TOKEN with write access lets a compromised workflow push commits, and in an infrastructure repository that means pushing to main and triggering the apply.
Self-hosted runners
| Risk | Detail |
|---|---|
| Persistence between jobs | One job can leave a binary, a variable or a process that the next one runs |
| Access to the internal network | They are usually inside the VPC: a compromised job can see internal databases and services |
| Instance credentials | If the runner has an EC2 role, any job inherits it: it is the problem from 08-02 §8 |
| Forks' PRs | Never in a public repository with self-hosted runners: it is remote code execution |
If they are needed — usually for access to private networks — the minimum conditions are: ephemeral (one per job, destroyed afterwards), in a restricted network, with no instance role holding permissions over the infrastructure, and never in public repositories.
- Reuse:
workflow_call and composite actions
workflow_call and composite actionsEcoMarket has the infrastructure repository and the module ones. There are two reuse mechanisms and they solve different things.
Reusable workflow (workflow_call) |
Composite action | |
|---|---|---|
| What it encapsulates | Whole jobs with their runners and permissions | Steps inside a job |
| Where it lives | A repository's .github/workflows/ |
.github/actions/<name>/action.yml or a repository of its own |
Can declare environment |
Yes | No |
Can declare permissions |
Yes | No: it inherits the job's |
Can use matrix |
Yes | No |
| Invoked with | uses: at job level |
uses: at step level |
| Used for what in EcoMarket | The whole pipeline of a module repository | The "download plan, decrypt, apply" block |
# .github/workflows/module-verify.yml (repository ecomarket/.github)
# A REUSABLE workflow: the complete pipeline of a published module.
name: Module · Verify
on:
workflow_call:
inputs:
terraform_version: { type: string, default: '1.9.8' }
with_integration: { type: boolean, default: false }
secrets:
test_role: { required: false }
jobs:
verify:
runs-on: ubuntu-latest
permissions:
contents: read
id-token: write
steps:
- uses: actions/checkout@v4
- uses: hashicorp/setup-terraform@v3
with: { terraform_version: ${{ inputs.terraform_version }} }
- run: terraform fmt -check -recursive -no-color
- run: terraform init -backend=false -lockfile=readonly -no-color
- run: terraform validate -no-color
- uses: terraform-linters/setup-tflint@v4
- run: tflint --init && tflint --recursive --format=compact
- name: terraform-docs checks, it does not generate
uses: terraform-docs/gh-actions@v1
with:
working-dir: .
output-file: README.md
output-method: inject
# --output-check: if the committed README does NOT match what
# would be generated, FAIL. It is what stops the documentation
# lying two weeks later.
fail-on-diff: true
- name: Unit tests
run: terraform test -filter=tests/unit -no-color
- name: Validate the examples
run: |
for ex in examples/*/; do
terraform -chdir="$ex" init -backend=false -lockfile=readonly -no-color
terraform -chdir="$ex" validate -no-color
done
- name: Integration tests
if: inputs.with_integration
uses: aws-actions/configure-aws-credentials@v4
with:
role-to-assume: ${{ secrets.test_role }}
aws-region: eu-west-1
- if: inputs.with_integration
run: terraform test -filter=tests/integration -no-colorAnd each module repository's workflow shrinks to four lines:
# .github/workflows/pr.yml of the terraform-aws-network repository
name: PR
on: { pull_request: {} }
jobs:
verify:
uses: ecomarket/.github/.github/workflows/[email protected]
# The VERSION, not @main: a change in the central workflow must not
# break twenty repositories at once. It is SemVer (04-05) applied
# to the pipeline, just like Jenkins's shared library.
- The published module's pipeline
08-01 §15 described a module's pipeline: no state, triggered by a tag, with terraform-docs --output-check and the CHANGELOG as guards. In GitHub Actions:
# .github/workflows/publish.yml (repository terraform-aws-network)
name: Module · Publish
on:
push:
tags: ['v*.*.*'] # the trigger is the TAG, not the merge
permissions: {}
jobs:
publish:
runs-on: ubuntu-latest
permissions:
contents: write # to create the Release
id-token: write # OIDC for the integration tests
steps:
- uses: actions/checkout@v4
with: { fetch-depth: 0 } # the history is needed for the CHANGELOG
- name: Validate the tag and the CHANGELOG
run: |
set -euo pipefail
VERSION="${GITHUB_REF_NAME#v}"
# 1. Strict SemVer (04-05).
echo "$VERSION" | grep -Eq '^[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.-]+)?$' || {
echo "The tag '${GITHUB_REF_NAME}' is not SemVer. Format: v3.2.1"; exit 1; }
# 2. A CHANGELOG entry for THIS version.
grep -q "^## \[${VERSION}\]" CHANGELOG.md || {
echo "'## [${VERSION}]' is missing from CHANGELOG.md."
echo "A version with no release note is a version nobody knows whether to adopt."
exit 1; }
# 3. If the CHANGELOG says BREAKING, require a migration guide.
if grep -A 40 "^## \[${VERSION}\]" CHANGELOG.md | grep -q 'BREAKING'; then
grep -A 80 "^## \[${VERSION}\]" CHANGELOG.md | grep -q '### Migration' || {
echo "Breaking change with no '### Migration' section."
echo "It blocks every consumer that wants to upgrade."; exit 1; }
fi
# 4. The tag must point at a commit on main.
git fetch --no-tags origin main
git merge-base --is-ancestor "$GITHUB_SHA" origin/main || {
echo "The tag does not point at a commit on main. Nothing is published."; exit 1; }
echo "version=$VERSION" >> "$GITHUB_ENV"
- uses: hashicorp/setup-terraform@v3
with: { terraform_version: '1.9.8' }
- uses: aws-actions/configure-aws-credentials@v4
with:
role-to-assume: arn:aws:iam::123456789012:role/ecomarket-modules-tests
aws-region: eu-west-1
role-session-name: gha-publish-${{ github.run_id }}
- name: The FULL suite before publishing
# Unit on PRs, integration nightly, the full suite before tagging
# (07-03). This is slow, and that is why it only runs here.
run: terraform test -no-color
- name: Create the Release
uses: actions/github-script@v7
with:
script: |
const fs = require('fs');
const v = process.env.version;
const text = fs.readFileSync('CHANGELOG.md', 'utf8');
// Extract ONLY this version's section for the body.
const m = text.match(new RegExp(`^## \\[${v.replace(/\./g,'\\.')}\\][^\\n]*\\n([\\s\\S]*?)(?=^## \\[|\\Z)`, 'm'));
await github.rest.repos.createRelease({
owner: context.repo.owner, repo: context.repo.repo,
tag_name: `v${v}`, name: `v${v}`,
body: m ? m[1].trim() : 'See CHANGELOG.md',
});The public module registry watches the repository's Releases and indexes the version automatically: there is no "upload" step for anything.
And check 4 is the one that usually goes missing. Without it, somebody can tag a working branch and publish code that never went through a review.
- Runner cost and timings
| Decision | Effect |
|---|---|
| A 3-environment matrix on every push to a PR | Triples the consumption; it is usually worth it to see all three plans |
cancel-in-progress on the plan |
A big saving on PRs with many pushes |
The paths filter |
The cheapest saving: a documentation PR consumes nothing |
| Provider cache | 30–60 s per job |
fetch-depth: 1 (the default) |
A fetch-depth: 0 in a large repository costs a fair amount; only when the history is needed |
| A larger runner | Terraform is more about network and waiting than CPU: it rarely helps |
| Self-hosted runners | Cheaper at volume; more attack surface (§10) |
Minutes are free in public repositories and billed in private ones. EcoMarket's infrastructure repository is private, so a matrix of 3 environments × 3 components on every push is noticeable. The path filter is what keeps it reasonable: a PR that only touches infra/app/** runs three jobs, not nine.
And the dominant time is still the same one from 08-01 §14: the plan querying the cloud API. No cache fixes it; only a smaller state does.
Common Mistakes and Tips
Forgetting permissions: id-token: write. The resulting error is Credentials could not be loaded, which looks like a role problem and is not. Tip: if configure-aws-credentials fails and the role looks right, check the permissions block before anything else.
Writing sub with a wildcard in the apply role. repo:org/repo:* includes :pull_request, so any PR gets write access. Tip: StringEquals with exact values on apply; the wildcard only in the read-only role, and commented.
Using pull_request_target with a checkout of the PR's code. Arbitrary code execution with your production secrets. Tip: in a Terraform repository, pull_request always; to comment on forks' PRs, a separate workflow that does not run their code.
Declaring permissions at workflow level. Every job inherits it, including the ones that do not need it. Tip: permissions: {} at the top and the minimum in each job.
Uploading plan.json as an artefact. It contains var.db_password in the clear and becomes downloadable. Tip: the JSON is generated, analysed and deleted inside the runner; what gets uploaded is the encrypted .tfplan and the plan.txt from terraform show.
Publishing the plan without truncating. A large plan exceeds 65,536 characters, the API fails and you lose the whole comment, including the headline. Tip: truncate with room to spare and keep the end, which is where the counts are.
Adding a new comment on every push. Fifteen plans on the PR and nobody knows which one is current. Tip: a hidden marker, github.paginate to find it, and updateComment.
Leaving terraform_wrapper: true in the drift workflow. The wrapper alters the exit code and -detailed-exitcode stops distinguishing "no changes" from "there is drift". Tip: false there, true where you want outputs.stdout.
cancel-in-progress: true in the apply workflow. Cancelling an apply half-way leaves the world inconsistent and the lock orphaned. Tip: true only on PR plans.
Referencing actions by tag rather than by SHA. A moved tag runs new third-party code on your runner with your credentials. Tip: the SHA with the version in a comment, and Dependabot to update them.
One concurrency group per repository. It serialises prod-data behind dev-app. Tip: tf-apply-<environment>-<component>.
Self-hosted runners in a public repository. Anybody who opens a PR runs code on your network. Tip: never; and if they are indispensable, ephemeral and with no instance role holding permissions over the infrastructure.
Consuming a reusable workflow with @main. A change in the central workflow breaks twenty repositories at once, with nobody having asked for it. Tip: @v2.4.0, and SemVer.
Not checking that the tag points at main when publishing a module. It allows publishing code that never went through review. Tip: git merge-base --is-ancestor in the publish workflow.
Exercises
Exercise 1: auditing four trust relationships
An organisation has these four roles configured for GitHub Actions. For each one: say whether it is correct, what exactly it grants, and how it would be exploited if it is not.
# A
Condition = {
StringLike = { "token.actions.githubusercontent.com:sub" = "repo:ecomarket/*" }
}
# B
Condition = {
StringEquals = {
"token.actions.githubusercontent.com:aud" = "sts.amazonaws.com"
"token.actions.githubusercontent.com:sub" = "repo:ecomarket/ecomarket-infra:ref:refs/heads/main"
}
}
# Role: ecomarket-terraform-prod (write access over production)
# C
Condition = {
StringLike = {
"token.actions.githubusercontent.com:sub" = "repo:ecomarket/ecomarket-infra:*"
}
}
# Role: ecomarket-terraform-plan-prod (ReadOnlyAccess + state lock)
# D
Condition = {
StringEquals = {
"token.actions.githubusercontent.com:aud" = "sts.amazonaws.com"
}
StringLike = {
"token.actions.githubusercontent.com:sub" = "repo:ecomarket/ecomarket-infra:environment:pro*"
}
}
# Role: ecomarket-terraform-prodExercise 2: the workflow that does not apply what was approved
This apply workflow has one serious design flaw and three minor ones. Find them and fix it.
name: Apply
on:
push: { branches: [main] }
permissions:
contents: write
id-token: write
jobs:
apply:
runs-on: ubuntu-latest
environment: production
steps:
- uses: actions/checkout@v4
- uses: hashicorp/setup-terraform@v3
- uses: aws-actions/configure-aws-credentials@v4
with:
role-to-assume: arn:aws:iam::123456789014:role/ecomarket-terraform-prod
aws-region: eu-west-1
- run: terraform init -backend-config=backends/prod.hcl
- run: terraform apply -auto-approve -var-file=environments/prod.tfvars
- run: terraform show -json > plan.json
- uses: actions/upload-artifact@v4
with: { name: plan, path: plan.json }Exercise 3: forks' PRs in the module repository
The ecomarket/terraform-aws-network repository is public and accepts external contributions. The current PR workflow fails on every fork PR with Credentials could not be loaded, because it tries to assume a role in order to run terraform test -filter=tests/integration.
Design the solution:
- A table of which steps can run on a fork's PR and which cannot, with the reason.
- The corrected workflow, which gives a useful signal to whoever contributes from a fork without exposing credentials.
- How the integration tests are run for that PR before merging it, without giving credentials to the fork's code.
Solutions
Solution 1
A — repo:ecomarket/* · SERIOUS, whatever the role.
It grants access to any repository in the organisation. It is also missing the aud condition, which widens the surface further still.
Exploitation: in most organisations, any member can create a repository. Somebody creates ecomarket/my-tests, writes a six-line workflow with role-to-assume pointing at this role, and has its permissions. They do not even need to be malicious: a prototype repository with fewer protections and one external collaborator is enough. An archived repository nobody watches works just as well.
Fix: the full repository name, and aud always present.
B — Correct for dev/staging, INSUFFICIENT for prod.
It is well written: StringEquals, with aud and with an exact sub. The problem is which sub that is: ref:refs/heads/main means "any job running on the main branch".
Exploitation: somebody adds a new workflow to main — say .github/workflows/cleanup.yml — triggered by schedule or workflow_dispatch, that assumes this role. Its sub is ref:refs/heads/main, it matches, and it applies to production without going through the protected environment or its reviewers. The approval gate exists only in GitHub's interface, not in AWS.
Fix for a production role:
Only a job that declares environment: prod gets that sub, and declaring it activates the reviewers. The gate now exists on both sides.
C — CORRECT, and deliberately so.
The wildcard covers :pull_request, so any PR in the repository can assume it. That is exactly what we want: PRs have to be able to plan. And it is acceptable because the role is ReadOnlyAccess plus the state lock.
Two caveats worth writing into the code itself:
- The
audcondition is missing. Even though thesubis scoped to the repository,audshould always be checked: it is free and it closes a whole class of confusions. - The wildcard is correct as long as the role remains read-only. The day somebody adds a write permission "for one specific thing", this role becomes mistake C from §3. It deserves an explicit comment in the code and an alert if its policy changes.
D — SERIOUS, and the subtlest of the four.
StringLike with environment:pro*. The wildcard does not cover only prod: it covers any environment whose name starts with pro.
Exploitation: somebody with permission to create environments in the repository — usually far more people than can approve deployments — creates an environment called prototype, pro-temporary or profiling, with no reviewers. A workflow declaring environment: prototype gets a sub that matches pro*, assumes the production role and applies with nobody's approval.
It is the same hole as B, but worse: it looks more restrictive than it is, and the attacker does not even need to touch main.
Fix: StringEquals with the exact value.
Summary:
| Role | Verdict | Grants | Fix |
|---|---|---|---|
| A | Serious | Any repository in the organisation | The full repository + aud |
| B | Insufficient for prod | Any workflow on main |
environment:prod as the only value |
| C | Correct | Any PR in the repository, read-only | Add aud; watch that it gains no permissions |
| D | Serious | Any environment starting with pro |
Exact StringEquals |
Solution 2
The serious flaw: terraform apply -auto-approve re-plans.
There is no saved plan. The workflow computes a new delta at apply time and executes it without anybody having seen it. Between the PR review and the merge, other merged PRs may have changed things, a data block with most_recent may return something else, or something may have been touched by hand in the console. What was approved and what was executed are not the same thing, which is the structural rule of 08-01 §3.
The three minor ones:
contents: write— the apply does not need to write to the repository. A compromised workflow with that permission can push tomainand trigger another apply.setup-terraformwith no version — it installs the latest. It can upgrade the state format irreversibly.terraform show -json > plan.jsonuploaded as an artefact — it dumps the sensitive values in the clear into a downloadable artefact. And it is also being misused: after anapply,show -jsonshows the state, not a plan, so the artefact is production's entire state in the clear. It is the worst of the three.
Also missing: concurrency, a freshness check, -input=false, -no-color, -lockfile=readonly, -reconfigure and role-session-name.
name: Terraform · Apply
on:
push:
branches: [main]
paths: ['infra/**', 'modules/**', 'environments/**', 'backends/**']
permissions: {}
env:
TF_IN_AUTOMATION: "1"
TF_INPUT: "false"
jobs:
apply:
runs-on: ubuntu-latest
environment: prod # mandatory reviewers + the token's sub
concurrency:
group: tf-apply-prod-app
cancel-in-progress: false # never cancel an apply
permissions:
id-token: write
contents: read # read-only
actions: read # to download the plan artefact
steps:
- uses: actions/checkout@v4
- name: Read the version the repository requires
id: v
run: echo "tf=$(cat .terraform-version)" >> "$GITHUB_OUTPUT"
- uses: hashicorp/setup-terraform@v3
with:
terraform_version: ${{ steps.v.outputs.tf }} # pinned
terraform_wrapper: false
# --- Retrieve THE plan that was approved, do not compute a new one ---
- name: Locate the plan run for this commit
id: find
uses: actions/github-script@v7
with:
script: |
const runs = await github.rest.actions.listWorkflowRuns({
owner: context.repo.owner, repo: context.repo.repo,
workflow_id: 'terraform-plan.yml', head_sha: context.sha,
});
if (!runs.data.workflow_runs.length) {
core.setFailed(`There is no plan for commit ${context.sha}.
WITH NO APPROVED PLAN THERE IS NO APPLY.`);
return;
}
core.setOutput('run_id', runs.data.workflow_runs[0].id);
- uses: actions/download-artifact@v4
with:
name: plan-prod
path: infra/app
run-id: ${{ steps.find.outputs.run_id }}
github-token: ${{ github.token }}
- name: Decrypt the plan
env:
KEY: ${{ secrets.PLAN_PRIVATE_KEY }}
run: |
set +x
set -euo pipefail
umask 077
printf '%s' "$KEY" > /tmp/k.age
cd infra/app
age --decrypt --identity /tmp/k.age -o prod-app.tfplan prod-app.tfplan.age
shred -u /tmp/k.age
- name: Check freshness and the window
run: |
ci/check-plan-freshness.sh infra/app/prod-app.tfplan
ci/deployment-window.sh
- uses: aws-actions/configure-aws-credentials@v4
with:
role-to-assume: arn:aws:iam::123456789014:role/ecomarket-terraform-prod
aws-region: eu-west-1
role-session-name: gha-apply-prod-${{ github.run_id }}
role-duration-seconds: 3600
mask-aws-account-id: true
- name: Apply THE saved plan
run: |
set -euo pipefail
terraform -chdir=infra/app init -reconfigure -lockfile=readonly -no-color \
-backend-config="$PWD/backends/prod.hcl"
# No -auto-approve (unnecessary) and no -var-file (it would error).
terraform -chdir=infra/app apply -no-color -lock-timeout=10m prod-app.tfplan
- name: Publish the NON-sensitive outputs
run: |
# -json respects sensitive by flagging it, but for publishing
# it is better to filter explicitly.
terraform -chdir=infra/app output -json \
| jq 'with_entries(select(.value.sensitive == false))' > public-outputs.json
- uses: actions/upload-artifact@v4
with:
name: outputs-prod
path: public-outputs.json
retention-days: 7
- name: Clean up
if: always()
run: find . -name '*.tfplan' -delete || trueSolution 3
1. What can run on a fork's PR.
| Step | On a fork's PR? | Reason |
|---|---|---|
terraform fmt -check |
Yes | It only reads files |
terraform init -backend=false |
Yes | It downloads providers from the public registry; no backend, no credentials |
terraform validate |
Yes | Static analysis |
tflint |
Yes | Likewise |
trivy config |
Yes | Likewise |
terraform-docs --output-check |
Yes | It compares files |
terraform test with mock_provider |
Yes | Mocks exist precisely for this (07-03) |
Validating the examples/ with -backend=false |
Yes | No state and no credentials |
Integration terraform test |
No | It creates real resources: it needs credentials |
| Posting a comment on the PR | Not directly | A fork's GITHUB_TOKEN is read-only |
The operational conclusion: the vast majority of a module's pipeline needs no credentials. The only problem is the integration part.
2. The corrected workflow.
# .github/workflows/pr.yml of the PUBLIC terraform-aws-network repository
name: PR
on:
pull_request: # NEVER pull_request_target
permissions: {}
jobs:
# --- Everything that does NOT need credentials: it always runs,
# forks' PRs included. It is the useful signal for contributors. ---
verify:
name: Static verification
runs-on: ubuntu-latest
permissions:
contents: read
steps:
- uses: actions/checkout@v4
- uses: hashicorp/setup-terraform@v3
with: { terraform_version: '1.9.8' }
- run: terraform fmt -check -recursive -no-color
- run: terraform init -backend=false -lockfile=readonly -no-color
- run: terraform validate -no-color
- uses: terraform-linters/setup-tflint@v4
- run: tflint --init && tflint --recursive --format=compact
- uses: aquasecurity/[email protected]
with: { scan-type: config, scan-ref: ., exit-code: '1', severity: HIGH,CRITICAL }
- name: Documentation up to date
uses: terraform-docs/gh-actions@v1
with: { working-dir: ., output-file: README.md, output-method: inject, fail-on-diff: true }
- name: Unit tests (mock_provider, no cloud)
run: terraform test -filter=tests/unit -no-color
- name: Validate the examples
run: |
for ex in examples/*/; do
terraform -chdir="$ex" init -backend=false -lockfile=readonly -no-color
terraform -chdir="$ex" validate -no-color
done
# The job summary is visible to anybody, including from a fork:
# it needs no write permissions over the PR.
- name: Summary for the contributor
if: always()
run: |
{
echo "## Module verification"
echo ""
echo "Formatting, validation, tflint, Trivy, documentation and unit tests."
echo ""
echo "The **integration** tests (which create real resources in AWS) do not"
echo "run on pull requests from a fork, because they require credentials."
echo "A maintainer will launch them after reviewing the code."
} >> "$GITHUB_STEP_SUMMARY"
# --- Integration: ONLY for PRs from the organisation itself. ---
integration:
name: Integration tests
# The key condition: the PR comes from the repository itself, not from a fork.
if: github.event.pull_request.head.repo.full_name == github.repository
runs-on: ubuntu-latest
permissions:
id-token: write
contents: read
steps:
- uses: actions/checkout@v4
- uses: hashicorp/setup-terraform@v3
with: { terraform_version: '1.9.8' }
- uses: aws-actions/configure-aws-credentials@v4
with:
role-to-assume: arn:aws:iam::123456789012:role/ecomarket-modules-tests
aws-region: eu-west-1
role-session-name: gha-integration-${{ github.run_id }}
- run: terraform test -filter=tests/integration -no-color3. How the integration runs for a fork's PR without giving the fork credentials.
Three options, from worst to best:
| Option | How | Trade-off |
|---|---|---|
A safe-to-test label |
A maintainer adds the label; a workflow with on: pull_request_target reacts |
Dangerous: if it checks out the fork's code, somebody else's code runs with credentials. It only works if the maintainer has read the whole diff, and the protection depends on their discipline |
| A mirror branch | A maintainer pushes the PR to a branch of the repository (fork/NN) and the integration runs there |
Manual, but safe by construction: the code goes through the repository, not through the event |
| A protected environment with reviewers | A job with environment: integration-forks and reviewers; the workflow waits for approval before assuming the role |
The best: automatic, with an explicit gate, and the approver sees the diff before granting it |
The third one, implemented:
integration-fork:
name: Integration (fork PR, requires approval)
if: github.event.pull_request.head.repo.full_name != github.repository
needs: verify # the static checks have to pass first
runs-on: ubuntu-latest
# This environment has mandatory reviewers. The job WAITS for a
# maintainer to approve, and only then does it get the OIDC token.
# The approver sees the full diff before deciding: reviewing the
# code IS the security measure.
environment: integration-forks
permissions:
id-token: write
contents: read
steps:
- uses: actions/checkout@v4
with:
# The SHA that is going to run is recorded EXPLICITLY, so that
# the approver can verify it is the one they reviewed.
ref: ${{ github.event.pull_request.head.sha }}
- name: Put on record what is being run
run: |
echo "Running code from fork ${{ github.event.pull_request.head.repo.full_name }}"
echo "SHA: ${{ github.event.pull_request.head.sha }}"
echo "Author: ${{ github.event.pull_request.user.login }}"
- uses: aws-actions/configure-aws-credentials@v4
with:
# A role SCOPED to the test account, with permissions over one
# specific prefix and nothing else. Even if the fork's code is
# malicious, the damage is limited by IAM.
role-to-assume: arn:aws:iam::123456789012:role/ecomarket-modules-tests-fork
aws-region: eu-west-1
role-session-name: gha-fork-${{ github.event.pull_request.number }}
role-duration-seconds: 1800
- uses: hashicorp/setup-terraform@v3
with: { terraform_version: '1.9.8' }
- run: terraform test -filter=tests/integration -no-color
- name: Always clean up
if: always()
run: terraform test -filter=tests/cleanup -no-color || trueThe two decisions that make this option safe:
- The protected environment's human approval is the code review. The maintainer is not approving "run tests": they are certifying that they have read the diff and that it contains no
data "external"orprovisionerthat exfiltrates credentials. - The role is different and much more tightly scoped than the one for internal PRs: the test account, permissions over one name prefix, a 30-minute duration. The human approval will fail one day; IAM will not.
Conclusion
GitHub Actions implements the flow from 08-01 with less scaffolding than Jenkins, and in exchange it concentrates all the risk in a handful of configurations you have to get right.
- OIDC end to end, at last. One
aws_iam_openid_connect_providerper account, reading the thumbprint from the real certificate and not from a blog; a plan role withStringLikeoverrepo:ecomarket/ecomarket-infra:*because it is read-only; and apply roles withStringEqualsand exact values. Inprod, the only acceptedsubisenvironment:prod. - That last decision is the heart of the lesson. Declaring
environment: prodin a job does two things at once: it activates GitHub's mandatory reviewers and it putsenvironment:prodin the token'ssub. The gate exists on both sides, and no new workflow can route around it. - The four
submistakes — the total wildcard, the organisation wildcard, the wildcard at the end of the correct repository andStringLikewith no wildcard — grant anything from "anybody on the internet" to "any PR". The third is especially insidious because it is correct in the plan role and catastrophic in the apply one. permissions: id-token: writeis what enables OIDC, its name misleads, and forgetting it produces an error that points at the role.permissions: {}at workflow level and the minimum per job.- Azure and GCP do the same thing under other names: federated credentials with no wildcards in Azure — more verbose and therefore harder to get wrong — and a mandatory
attribute_conditionin GCP. - The plan workflow orders its steps from cheap to expensive, with an environment matrix and no
fail-fast,cancel-in-progresson, a cache keyed by the lockfile hash, and aplan.jsonthat never leaves the runner. terraform_wrapperis convenient and it has a cost: it truncates at 1 MB and alters the exit code, which breaks-detailed-exitcode. On for the plan, off for the drift workflow.- The PR comment is updated using a hidden marker, the search is paginated so it is not lost on long PRs, it is truncated keeping the end — where the counts are — and what gets published is
terraform showwithout-json. - The apply workflow looks for the plan artefact by the commit's SHA and fails if it cannot find it, because with no approved plan there is no apply.
pushand notworkflow_run, because nothing originating in a PR should obtain write access. - The drift workflow uses
continue-on-errorto capture code 2 without aborting the job, opens or comments on an issue depending on whether one exists, and escalates tochronic-drifton the fifth night. pull_request_targetwith a checkout of the PR's code is remote code execution with your production secrets. In a Terraform repository it has no legitimate use whatsoever.- Actions are pinned by SHA: they are third-party code running with your credentials, and a moved tag is the equivalent of a trojanised provider.
- Reusable workflows encapsulate jobs and composite actions encapsulate steps; the former can declare
environmentandpermissions, and that is why they are the ones that serve as the complete pipeline for the twenty module repositories. Always consumed by version, never@main. - The published module's pipeline is triggered by a tag, and it requires SemVer, a CHANGELOG entry, a migration section if there are breaking changes, and that the tag points at a commit on
main.
With this there is a complete machine, built twice. And having got here, a legitimate question appears: did it need building? Between the two workflows, the roles, the trust relationships, the artefact encryption, the gate scripts, the issue deduplication and the SHA-pinned actions, there are several weeks of work for one person with good judgement, followed by indefinite maintenance.
The next lesson, Terraform Cloud and Enterprise, answers that question by showing the alternative: a managed platform that replaces a good part of this machinery — the state and its locking, remote execution, variables and secrets, approvals, the private registry and auditing — with configuration. There we settle the debt 06-01 left open about what HCP workspaces really are, Sentinel goes from overview to detail with real policies applied to EcoMarket and an honest comparison with OPA, cost estimation appears as a deployment gate, and it ends with the table this conclusion has just made inevitable: when paying for the platform pays off, and when the pipeline of your own that you have just built does.
