Terraform Hour 5: Automated Operations — CI/CD and Policy Governance

From “I run apply on my laptop” to “every change goes through PR, plan, policy and approval, and the apply runs exactly the reviewed plan”
Terraform v1.17.2hashicorp/setup-terraform v4.0.1Terraform Policy GA (1.17)Stacks GA (2025-09)Verified against official docs · 2026-11
Overall learning objectives
  • Design a GitOps-style Terraform workflow: PR-triggered plan → human review → after merge, use the same plan file to apply, with clear separation of duties for “who can plan, who can apply and who can approve”, and environment promotion from dev → staging → prod.
  • Use GitHub Actions + OIDC to remove all long-lived cloud credentials: on Azure, configure federated identity credentials (federated identity credential), on AWS configure IAM OIDC provider + role trust policy, and assign identities by sub claim: PRs, the main branch and the production environment each get their own identity.
  • Write production-grade workflows: pin Actions by commit SHA,permissions least privilege,concurrency serialize runs, upload the plan as an artifact, comment a plan summary on PRs,environment and approval gates.
  • Understand HCP Terraform workspaces, the VCS/CLI/API drivers, remote runs, variable sets, dynamic credentials and run tasks, and state accurately the 2026 free vs paid tier differences.
  • Use three policy-as-code engines to block non-compliant changes: Terraform Policy (HCL, since 1.17 -policies GA),Sentinel,OPA/conftest (checking terraform show -json the plan JSON), so choose the right one.
  • Set up drift detection (scheduled job + plan -detailed-exitcode or HCP health assessments),cost estimation (Infracost) and tag governance (default_tags + policy enforcement).
  • Understand Terraform Stacks the current status of Stacks (2025-09 GA, an HCP Terraform feature) and the component / deployment model, and judge when moving from “multiple workspaces + pipeline orchestration” to Stacks is worth it.

1-hour time allocation

#TimeModuleCore contentAnimation / interactionLab
0Before classSetup: GitHub repository and cloud identityPut the Hour 3 Azure stack into a Git repository; prepare the gh CLI, remote state and subscription permissionsEnvironment self-check checklistRepository myapp-infra Push succeeds
100–07GitOps-style Terraform workflowPR → plan → review → apply, environment promotion, separation of duties, branch protection, CODEOWNERSChange lifecycle state machine (including the consequences of “bypassing the process”)Branch protection + CODEOWNERS
207–17GitHub Actions + OIDC plan and applyOIDC token exchange, Azure federated credentials, AWS OIDC provider, plan artifact, PR comments, environment approval, concurrency, SHA pinningCore animation: the full pipeline of one PRTwo-stage workflow: PR plan / main plan → approval → apply
317–25HCP Terraform workspaces and runsOrganization/project/workspace, VCS vs CLI vs API driven, remote runs, variable sets, dynamic credentials, run tasks, free/paid tiersStage flow of one remote runcloud block + dynamic credentials
425–33Policy as codeTerraform Policy (.policy.hcl), Sentinel, OPA/conftest, enforcement levels, comparison of the threeThe same plan evaluated by three enginesconftest + Terraform Policy gate
533–40Drift detection and continuous complianceDrift sources -refresh-only and -detailed-exitcode scheduled jobs, HCP health assessments, remediation decisionsDrift simulator (portal manual change → detection → remediation)Nightly drift-detection workflow + automatic issue creation
640–47Cost estimation and tag governanceInfracost (v0.10 and 2.0 CLI), HCP cost estimation, AWS default_tags, Azure tag inheritance, policy-enforced tagsTag merge and cost-diff calculatorPR cost comments + tag policy
747–54Stacks and multi-deployment orchestrationStacks status,.tfcomponent.hcl / .tfdeploy.hcl, deployment, identity_token, limitations; alternativesMulti-deployment orchestration and deferred changesRead and rewrite a minimal Stack
854–60Hours 1–5 recap, self-check and cleanupKnowledge map of the five lessons, common CI failure troubleshooting, cleaning up OIDC identities and resourcesCI failure troubleshooting treeCleanup script
—After classCheat sheet · Capstone labBuild full CI/CD, policy gates and drift detection for the Hour 3 Azure stackFinal quiz (12 questions)Capstone lab

Knowledge Coverage Matrix

Target skillM1M2M3M4M5M6M7M8Key commands / configurationLab
Design a PR-driven change process and separation of duties✓✓✓····✓branch protection, CODEOWNERS, environmentsM1, capstone lab
Cloud authentication without long-lived keys (OIDC)·✓✓···✓✓id-token: write,ARM_USE_OIDC,role-to-assumeM2
apply the reviewed plan file✓✓✓····✓plan -out,apply tfplan, upload-artifactM2
Use HCP Terraform remote runs··✓✓✓✓✓·cloud block,terraform login, variable setsM3
Policy-as-code gate·✓✓✓✓✓·✓plan -policies,tfpolicy test,conftest testM4, M6
Drift detection and remediation··✓·✓··✓plan -refresh-only -detailed-exitcode, scheduleM5
Cost visibility and tag governance··✓✓·✓··infracost diff,default_tags,tags_allM6
Multi-deployment orchestration (Stacks / pipelines)✓·✓···✓·component,deployment,identity_tokenM7
Quick CI failure troubleshooting·✓✓✓✓··✓AADSTS700213, AccessDenied, Saved plan is staleM8 troubleshooting tree

What this lesson does not cover (and where to learn it)

TopicWhy not in this lessonWhere to learn
Repo and environment directory layout, state splitting, cross-stack referencesBelongs to architecture design; this lesson only uses the simplest layout, “one directory and one state per environment”Lesson 6
Handling secrets in CI with ephemeral resources and write-only parametersSecrets governance topicLesson 6, Module 5
tflint, Trivy/Checkov static scanning and terraform testCovered in Lesson 2; this lesson reuses it directly in the workflowLesson 2 Modules 6, 7
Third-party TACOS platforms such as Atlantis, Spacelift, env0, ScalrSame approach as this lesson (PR-driven + policy + approval); product details change quicklySee each vendor's official docs; m3 of this lesson gives the selection criteria
Terraform Enterprise self-hosted installation and operationsPlatform team responsibilitiesTerraform Enterprise documentation
Large-scale performance tuning (parallelism,-minimal-refresh, splitting)Belongs to optimization topicsLesson 7

How to use these course materials

10 pages per module
Concepts · Diagrams · Animation · Commands · Labs · Production cases · Troubleshooting · Quiz · Voice · Video. Read “Concepts” and “Animation” first, then do the “Lab”. The Module 2 animation is the core of this lesson: replay it repeatedly and switch the “fault injection” option.
Learning progress
A quiz score of 70% or more, or clicking “Mark this module complete”, counts toward progress; it is saved in this browser (cleared on refresh when local storage is blocked).
Chinese voice
The “Voice” page reads the script aloud with the browser's built-in Web Speech API (en-US); if no Chinese voice pack is installed, the script can still be read or passed to a TTS tool.
Version notes This lesson is based on Terraform v1.17.2 (2026-11-11) as the baseline. Since 1.17.0 (2026-10-21) Terraform Policy GA: plan / apply / query the -policies argument no longer needs an experimental build. GitHub Actions versions were all checked on 2026-11-15 using git ls-remote the commit SHAs matching each tag: hashicorp/setup-terraform v4.0.1 (requires the Node.js 24 runtime),actions/checkout v7.0.1,actions/upload-artifact v7.0.2,actions/download-artifact v8.0.2,azure/login v3.1.0,aws-actions/configure-aws-credentials v6.3.0. Provider: the latest azurerm on the registry is 5.14.0 (last 4.x release 4.81.0), aws is 6.73.0. This lesson's examples use ~> 5.0; if the Hour 3 stack is still on 4.x, first follow the 5.0 upgrade guide. OpenTofu is currently 1.13.9 (HCP Terraform and Stacks do not support OpenTofu).

Module 0 · Setup: GitHub repository and cloud identity (complete before class)

Put the Hour 3 Azure stack into a Git repository, confirm remote state works, and prepare the gh CLI and sufficient Entra ID / subscription permissions
Before class ≈ 15 minTerraform 1.17.2 · gh CLIRequires Owner or User Access Administrator
Prerequisites
  • CompletedHour 3 (Azure): resource group rg-tf-lab (region canadacentral) running myapp (Container Apps), with state in an azurerm backend (this lesson assumes resource group rg-tfstate, storage account sttfstate<suffix>, container tfstate, key lab3/myapp.tfstate). If your names differ, replace them throughout.
  • Optional: completedHour 4 (AWS), every Azure step in this lesson has an AWS equivalent (region ca-central-1, S3 backend + use_lockfile).
  • Workstation: Ubuntu 24.04 (or your local machine), with Terraform 1.17.x, Azure CLI, git,gh CLI; a GitHub account that can create repositories (environment approval reviewers for private repositories depend on your plan; see “Limitations” in Module 2).
  • Permissions: on the subscription, able to create role assignments (Owner or User Access Administrator); in Entra ID, able to create user-assigned managed identities (or app registrations).

Step 1: check the Hour 3 stack and state

cd ~/tf-lab/azure            # Hour 3 directory; change to your actual path
terraform version
az account show --query "{sub:id, tenant:tenantId, user:user.name}" -o table
terraform init -input=false
terraform plan -input=false -detailed-exitcode; echo "exit=$?"
Terraform v1.17.2
on linux_amd64
+ provider registry.terraform.io/hashicorp/azurerm v5.14.0

Sub                                   Tenant                                User
------------------------------------  ------------------------------------  ---------------
00000000-1111-2222-3333-444444444444  aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee  you@example.com
...
No changes. Your infrastructure matches the configuration.
exit=0

exit=0 means no diff,exit=2 means there is a diff (someone may have changed resources, the topic of Module 5),exit=1 means an error. Make the exit code 0 before starting this lesson, otherwise the first CI run will show changes you cannot make sense of.

Step 2 (only if the Hour 3 resources have been deleted): minimal runnable stack

If at the end of Hour 3 you ran terraform destroy, the minimal configuration below is enough to complete all labs in this lesson (resource group + Log Analytics + Container Apps environment + 1 Container App; pay-as-you-go cost about 0.1–0.5 USD per day, depending on replicas and traffic). The image uses Microsoft's official Container Apps sample image; you can also swap in the myapp image pushed to ACR in the Docker lesson.

terraform {
  required_version = ">= 1.17.0"
  required_providers {
    azurerm = {
      source  = "hashicorp/azurerm"
      version = "~> 5.0"      # 2026-11 latest 5.14.0; read the 5.0 upgrade guide before upgrading from 4.x
    }
  }
  backend "azurerm" {
    resource_group_name  = "rg-tfstate"
    storage_account_name = "sttfstateREPLACE"
    container_name       = "tfstate"
    key                  = "lab3/myapp.tfstate"
    use_azuread_auth     = true          # access Blob with Entra ID, not storage account keys
  }
}

provider "azurerm" {
  features {}
  # subscription_id is required from 4.0 on: locally, provide it via the ARM_SUBSCRIPTION_ID environment variable
}
locals {
  tags = {
    app         = "myapp"
    env         = var.env
    owner       = "platform-team"
    cost-center = "cc-1001"
    managed-by  = "terraform"
  }
}

variable "env" {
  type    = string
  default = "prod"
}

resource "azurerm_resource_group" "lab" {
  name     = "rg-tf-lab"
  location = "canadacentral"
  tags     = local.tags
}

resource "azurerm_log_analytics_workspace" "lab" {
  name                = "log-myapp-${var.env}"
  location            = azurerm_resource_group.lab.location
  resource_group_name = azurerm_resource_group.lab.name
  sku                 = "PerGB2018"
  retention_in_days   = 30
  tags                = local.tags
}

resource "azurerm_container_app_environment" "lab" {
  name                       = "cae-myapp-${var.env}"
  location                   = azurerm_resource_group.lab.location
  resource_group_name        = azurerm_resource_group.lab.name
  log_analytics_workspace_id = azurerm_log_analytics_workspace.lab.id
  tags                       = local.tags
}

resource "azurerm_container_app" "myapp" {
  name                         = "ca-myapp-${var.env}"
  container_app_environment_id = azurerm_container_app_environment.lab.id
  resource_group_name          = azurerm_resource_group.lab.name
  revision_mode                = "Single"
  tags                         = local.tags

  template {
    min_replicas = 0
    max_replicas = 2
    container {
      name   = "myapp"
      image  = "mcr.microsoft.com/k8se/quickstart:latest"
      cpu    = 0.25
      memory = "0.5Gi"
    }
  }
  ingress {
    external_enabled = true
    target_port      = 80
    traffic_weight {
      latest_revision = true
      percentage      = 100
    }
  }
}

output "url" {
  value = "https://${azurerm_container_app.myapp.ingress[0].fqdn}"
}

Step 3: create the GitHub repository and push

gh auth login                       # choose GitHub.com → HTTPS → browser login
mkdir -p ~/myapp-infra && cd ~/myapp-infra
git init -b main
mkdir -p azure policies/tfpolicy policies/opa .github/workflows
cp ~/tf-lab/azure/*.tf azure/
cp ~/tf-lab/azure/.terraform.lock.hcl azure/      # the lock file must be committed so CI can reproduce the same provider
cat > .gitignore <<'EOF'
.terraform/
*.tfstate
*.tfstate.*
*.tfplan
tfplan
plan.json
crash.log
*.tfvars.local
EOF
git add . && git commit -m "Import Azure stack from lesson 3"
gh repo create myapp-infra --private --source=. --push
gh repo view --json nameWithOwner -q .nameWithOwner
✓ Created repository yourname/myapp-infra on GitHub
✓ Added remote https://github.com/yourname/myapp-infra.git
✓ Pushed commits to https://github.com/yourname/myapp-infra.git
yourname/myapp-infra
Lock file and multiple platforms CI runs on linux_amd64, while your laptop may be darwin_arm64 or windows_amd64. If the lock file only records hashes for your local platform, CI's init will fail on a checksum mismatch. Before committing, run: terraform providers lock -platform=linux_amd64 -platform=darwin_arm64 -platform=windows_amd64 (covered in Hour 1, Module 3).

Step 4: set the variables used repeatedly in this lesson

export REPO=$(gh repo view --json nameWithOwner -q .nameWithOwner)   # e.g. yourname/myapp-infra
export SUB_ID=$(az account show --query id -o tsv)
export TENANT_ID=$(az account show --query tenantId -o tsv)
export STATE_RG=rg-tfstate
export STATE_SA=$(az storage account list -g $STATE_RG --query "[0].name" -o tsv)
echo "$REPO $SUB_ID $STATE_SA"

Warm-up: answer from memory (30 seconds)

What is inside a saved plan file (terraform plan -out=tfplan)? Can it be shared freely?

It contains a full configuration snapshot, variable values, prior state and planned changes,which may include sensitive values in plaintext (sensitive only affects display, it does not encrypt). So in CI, a plan file must be treated as a secret artifact: short retention, restricted access. This foreshadows Module 2.

When is the remote state lock acquired?

plan and apply both acquire the state lock (the azurerm backend uses a Blob lease; the S3 backend uses use_lockfile a .tflock object). So a “plan-only” identity still needs write access to the state container; Module 2's permission design covers this.

Environment self-check checklist

Module 1 · GitOps-style Terraform workflow

00:00 – 07:00 · Git is the only entry point for changes: a PR is the proposal, the plan is the evidence, review is the decision, apply is the execution
7 minProcess design · tool-agnostic★★★★★
Learning objectives
  • Draw the PR → fmt/validate/lint → plan → review → merge → apply the full chain, and explain the “evidence” each step produces (plan output, approval records, run logs).
  • Compare three apply timings: “apply before merge (apply-before-merge)”, “apply after merge (apply-after-merge)” and “after merge: plan + approval + apply the same plan”, and know the risk of each.
  • Design environment promotion (dev → staging → prod) and separation of duties: the person writing code, the person approving, and the identity with apply permission must be kept separate.
Prerequisites: CLI workflow and remote state from Hours 1–2; Git branches and PRs. Importance:★★★★★ (almost every Terraform production incident review asks “did this change go through the process?”)

What: what is a GitOps-style Terraform workflow

The core principle of GitOps is: desired state is stored declaratively in Git, changes enter through Git's review mechanism, and are executed by an automated system rather than by people. For Terraform, the “desired state” is .tf files + lock file + variable files; the “automated system” is CI (GitHub Actions, Azure Pipelines) or a TACOS platform (HCP Terraform, Atlantis, etc.).

Unlike Argo CD/Flux for Kubernetes (controllers that continuously pull and converge), Terraform's typical GitOps is push-based, event-driven: a PR or merge event triggers one plan/apply; continuous convergence is provided by “regular drift detection” (Module 5).

Why: why you should not keep applying from a laptop

Problems with local applyHow the GitOps workflow solves it
Everyone's Terraform/provider versions, variables and credentials differ, so results are not reproducibleCI uses a pinned version + lock file + the same variables, running on a clean runner
Long-lived high-privilege credentials are scattered across personal computersOnly the CI identity can apply, using short-lived OIDC tokens (Module 2)
“Nobody looked at the plan before I applied”The plan is posted as a PR comment for review; apply can only execute an approved plan
Hard to audit: who changed production, when, and whyPR descriptions, review records, workflow logs and environment deployment history naturally form an audit trail
Code and the real environment gradually diverge (unmerged branches got applied)main branch = desired production state; drift detection checks it continuously

How: the standard flow (the pattern used in this lesson)

  1. Create a branch, open a PR: change azure/*.tf.
  2. PR checks (read-only identity): terraform fmt -check,validate, tflint/Trivy (Hour 2),terraform plan (speculative plan, not saved, or saved for display only), post the plan summary as a PR comment, and run policy checks (Module 4) and cost estimation (Module 6).
  3. Code review: approval from the platform team named in CODEOWNERS; branch protection requires all checks to pass.
  4. Merge to main: triggers the “release workflow”. Re-run plan -out=tfplan (based on the merged code and the latest state), and upload the plan as an artifact.
  5. Deployment approval: the apply job is bound to a GitHub environment: production, which requires a designated approver to click Approve; the approver sees the plan from step 4.
  6. Apply the same plan file: terraform apply tfplan. If someone changes the state between plan and apply, Terraform refuses to run (Saved plan is stale), which guarantees that “approved” = “executed”.
  7. Promotion: after dev succeeds, run the same steps on staging and prod (same commit SHA).

Comparison of the three apply timings

PatternApproachProsRisksExample
Apply directly after mergeAutomatically after merging to main apply -auto-approveSimple; main always reflects the deployed stateThe plan on the PR may be stale (other PRs merged or someone changed resources in the meantime), and the change actually applied was never reviewed; if apply fails, main already contains bad codeSmall teams, non-production
Apply before mergeComment on the PR atlantis apply, then merge after it succeedsmain only contains code that has been applied successfullyParallel PRs need locking (Atlantis locks per directory); unmerged code has already reached productionAtlantis default flow
After merge: plan → approval → apply the same planRe-plan on main and save it; after approval, apply that fileThe executed change = the approved change; state changes automatically invalidate itOne extra wait; the plan file is a sensitive artifactThis lesson; HCP Terraform's “Needs Confirmation”

Environment promotion and separation of duties

  • Same code, different inputs: one state per environment (separate backend key or separate workspace), variable files env/dev.tfvars,env/prod.tfvars. Promotion = using the same commit deployed to higher environments in turn, rather than copying code between branches.
  • Three identities: PR plan identity (read-only + state lock writes), dev apply identity, prod apply identity; the OIDC trust condition of the prod identity only accepts environment:production (Module 2).
  • Three roles: author (opens the PR), reviewer (CODEOWNERS), deployment approver (environment required reviewers; can enable “Prevent self-review” so the author cannot approve their own deployment).
  • Break-glass process (break-glass): in an incident, controlled manual actions are allowed, but a PR must be added afterward and drift detection must confirm that code and environment match.

When: when to use it and when not to

  • Any shared environment (staging, prod, shared networking/identity) should only allow CI to run apply.
  • Personal sandboxes can apply locally, but it is still recommended to use the same modules and backend layout, to reduce “works locally, fails in CI”.
  • For small teams with infrequent changes, starting with “PR plan + apply approved after merge” is enough; for larger teams with many repositories, consider HCP Terraform or another TACOS platform (Module 3).

Comparison with similar technologies

Self-built GitHub ActionsHCP Terraform (VCS-driven)AtlantisArgo CD / Flux
TriggerWorkflow eventsVCS webhookPR webhook + comment commandsController polls Git
State and lockSelf-managed backendPlatform-managedSelf-managed backend + Atlantis directory locksNot applicable (K8s objects)
Approvalenvironment required reviewersConfirm & Apply / policy overridePR approval + apply requirementSync policy / PR
Policyconftest / -policies Self-integratedSentinel, OPA, native Terraform Policyconftest integrationGatekeeper/Kyverno
CostActions minutesBilled per managed resource (see Module 3)Self-hostedSelf-hosted
Common misconceptions① “Looking at the plan on the PR is enough” — by the time it runs after merge, state and code may both have changed; the PR plan is only a preview. ② “Running with -auto-approve is the same as having no approval” — approval can be done at the environment gate before apply,-auto-approve it only stops Terraform from prompting; applying a saved plan file never prompts anyway. ③ “GitOps means automatic apply to production” — GitOps emphasizes that Git is the single entry point and is auditable; the degree of automation can differ per environment.

Architecture diagram: change path from PR to production

feature branchDeveloper edits .tf PR checks (read-only identity)fmt · validate · tflint · trivyspeculative plan → PR commentPolicy · cost Code reviewCODEOWNERS approval Merge to main= desired state plan -out=tfplanUpload artifact (retained 1–5 days)based on merged code + latest state environment approvalrequired reviewersSelf-review prohibited apply tfplanprod identity (only this job can obtain it)state change → plan invalidated cloud resources + remote staterg-tf-lab · tfstate/lab3/myapp.tfstate Scheduled drift detection (Module 5)plan -refresh-only -detailed-exitcode → exit 2 → open issue Forbiddenlocal apply to productionmanual portal changes
Figure 1-1: PR checks use only a read-only identity; after merge, re-plan and save; after approval, apply the same plan; drift detection provides “continuous convergence”.

Flow chart: environment promotion and identity separation

same commit SHA (e.g. 9f3c2ab) promoted in turn devenv/dev.tfvars · key myapp-dev.tfstateAutomatic apply (no approval) stagingenv/staging.tfvars · key myapp-stg.tfstate1 approver productionenv/prod.tfvars · key myapp-prod.tfstate2 approvers · self-review prohibited · main only Identity id-tf-devsub: repo:org/myapp-infra:environment:dev Identity id-tf-stagingsub: …:environment:staging Identity id-tf-prod (Contributor on prod subscription only)sub: …:environment:production
Figure 1-2: what gets promoted is the same commit; each environment has its own state, identity and approval rules

Interactive animation: one change's lifecycle (and the consequences of bypassing the process)

Click “Play” to see how a standard change passes through each gate; tick “someone applied directly to prod from a laptop”, then play again to see how state, code and audit records diverge. The log below is the real output you would see in GitHub and Terraform.

Core commands and configuration

Command / configurationPurposeKey parameters / notes
terraform fmt -check -recursiveFormat check (does not modify files in CI, only returns non-zero)-diff Show diff
terraform validateSyntax and type validation (requires init -backend=false first)-json Machine-readable
terraform plan -out=tfplan -input=falseGenerate and save the plan-lock-timeout=5m,-var-file
terraform apply -input=false tfplanApply the saved plan (no more prompts)Reports stale when state changes
gh api … /branches/main/protectionConfigure branch protectionRequired checks, required reviews, CODEOWNERS
.github/CODEOWNERSRequired reviewers for specified pathsRequires pairing with “Require review from Code Owners”
gh api … /environments/productionCreate environments, reviewers, branch restrictionsreviewers,prevent_self_review,deployment_branch_policy

CODEOWNERS: infrastructure code must be reviewed by the platform team

# the last matching rule takes precedence
*                     @yourname
/azure/               @yourorg/platform-team
/policies/            @yourorg/security-team
/.github/workflows/   @yourorg/platform-team @yourorg/security-team

Why the workflow directory must also be protected: Whoever can modify the workflow can change how OIDC token requests are made and the conditions for apply. A personal repository has no teams, so you can start by writing your own username.

Branch protection (REST API, safe to re-run)

gh api -X PUT "repos/$REPO/branches/main/protection" \
  -H "Accept: application/vnd.github+json" --input - <<'EOF'
{
  "required_status_checks": { "strict": true, "contexts": ["terraform-plan"] },
  "enforce_admins": true,
  "required_pull_request_reviews": {
    "required_approving_review_count": 1,
    "require_code_owner_reviews": true,
    "dismiss_stale_reviews": true
  },
  "restrictions": null,
  "required_linear_history": true,
  "allow_force_pushes": false,
  "allow_deletions": false
}
EOF
gh api "repos/$REPO/branches/main/protection" --jq '{checks: .required_status_checks.contexts, reviews: .required_pull_request_reviews.required_approving_review_count, codeowners: .required_pull_request_reviews.require_code_owner_reviews}'
{"checks":["terraform-plan"],"codeowners":true,"reviews":1}

How to verify: Pushing directly git push origin main should be rejected (protected branch hook declined). Common errors:contexts must match the workflow job's name (or job id) exactly, otherwise the PR will wait forever for a check that does not exist. Production use: Branch protection / rulesets for private repositories are limited on GitHub Free; organizations usually use Team/Enterprise and prefer the newer Rulesets (repos/{repo}/rulesets) to manage multiple repositories centrally.

Environments and promotion: create dev / staging / production

ME_ID=$(gh api user --jq .id)
for ENV in dev staging; do
  gh api -X PUT "repos/$REPO/environments/$ENV" >/dev/null && echo "created $ENV"
done
gh api -X PUT "repos/$REPO/environments/production" --input - <<EOF
{
  "wait_timer": 0,
  "prevent_self_review": false,
  "reviewers": [ { "type": "User", "id": $ME_ID } ],
  "deployment_branch_policy": { "protected_branches": true, "custom_branch_policies": false }
}
EOF
gh api "repos/$REPO/environments" --jq '.environments[] | {name, rules: [.protection_rules[].type]}'
created dev
created staging
{"name":"dev","rules":[]}
{"name":"production","rules":["required_reviewers","branch_policy"]}
{"name":"staging","rules":[]}

In this lab you are the only person, so prevent_self_review set it to false (otherwise you cannot approve your own deployment). In production it should be true, and at least 2 approvers or one team should be configured. deployment_branch_policy.protected_branches: true means only workflows on the protected branch (main) can deploy to production; a feature branch cannot obtain the prod environment even if it edits the workflow, and therefore cannot obtain the prod OIDC subject.

Lab 1: add process guardrails to myapp-infra (about 5 min)

Commit CODEOWNERS and a minimal PR check (the full workflow is in Module 2; here we first make sure the check name referenced by branch protection exists):
name: terraform-pr
on:
  pull_request:
    paths: ["azure/**", "policies/**", ".github/workflows/**"]
permissions:
  contents: read
jobs:
  terraform-plan:
    name: terraform-plan
    runs-on: ubuntu-24.04
    defaults: { run: { working-directory: azure } }
    steps:
      - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
      - uses: hashicorp/setup-terraform@dfe3c3f87815947d99a8997f908cb6525fc44e9e # v4.0.1
        with: { terraform_version: "1.17.2" }
      - run: terraform fmt -check -recursive
      - run: terraform init -backend=false -input=false
      - run: terraform validate
cd ~/myapp-infra
mkdir -p .github && printf '* @%s\n/azure/ @%s\n' "$(gh api user --jq .login)" "$(gh api user --jq .login)" > .github/CODEOWNERS
git add .github && git commit -m "Add CODEOWNERS and PR checks" && git push
Enable branch protection and create environments: run the two gh api scripts from the “Commands” page.
Verify the guardrails:
echo "# test" >> README.md && git commit -am "direct push test" && git push origin main
remote: error: GH006: Protected branch update failed for refs/heads/main.
remote: - Changes must be made through a pull request.
 ! [remote rejected] main -> main (protected branch hook declined)
git reset --hard HEAD~1
git switch -c chore/fmt-test
sed -i 's/retention_in_days   = 30/retention_in_days = 30/' azure/main.tf   # deliberately break formatting
git commit -am "Break formatting on purpose" && git push -u origin chore/fmt-test
gh pr create --fill
gh pr checks --watch
X  terraform-plan  12s  https://github.com/yourname/myapp-infra/actions/runs/…
main.tf
Error: Process completed with exit code 3.

terraform fmt -check The exit code is 3 when a file needs formatting. Fix: terraform fmt -recursive → commit → checks turn green.

Cleanup: terraform fmt -recursive && git commit -am fmt && git push, then gh pr close --delete-branch (or merge). Keep branch protection and environments for the capstone lab.

Case 1: the plan on the PR does not match what actually ran

Problem: The team uses “automatic apply after merge”. The plan in PR #120 showed only one NSG rule changing; but PR #118 had already merged and changed the same subnet, so when it actually ran after merge, #120 also replaced the subnet association, causing a 3-minute outage. Fix: Changed to “re-plan and save after merge → production environment approval → apply the same plan”; branch protection enabled with strict (requires the branch to be up to date with main before merging, so PR checks re-run against the latest main). Limitation: Strict mode causes queuing when merges are frequent; it can be combined with GitHub merge queue.

Case 2: after a break-glass fix, the code rolled the fix back

Problem: During a night-time incident, the on-call engineer raised the Container App's max replicas from 2 to 10 in the portal to stop the bleeding; the next day an unrelated PR merged, and apply changed it back to 2, so the incident recurred. Fix: The break-glass process requires a PR with the equivalent change within 1 hour of any manual edit; nightly drift detection (Module 5) automatically opens an issue on any difference and @-mentions the on-call engineer. Configuration: Azure Activity Log alert for “write operations by non-CI identities”. Limitation: Alerts can only detect issues after the fact and cannot prevent them; they must be combined with RBAC to tighten people's write permissions.

Case 3: separation of duties to satisfy audit (SOX/ISO 27001)

Problem: The audit requires that “developers cannot deploy changes to production on their own”. Fix: CODEOWNERS requires platform team review; production environment required reviewers = change approval group, with prevent self-review enabled; the prod OIDC identity only trusts environment:production; audit evidence is exported directly from PR and deployment history (gh api repos/$REPO/deployments). Limitation: Repository admins can still change environment rules, so monitor them with organization-level rulesets and audit logs.

Common errors and fixes

Required status check "terraform-plan" is expected. Waiting for status to be reported

Cause: The check name required by branch protection does not match the name the workflow actually reports, or the workflow did not trigger because of a paths filter.

gh api "repos/$REPO/branches/main/protection/required_status_checks" --jq .contexts
gh pr checks

Fix: Make the job's name: match the contexts; for required checks that may be skipped by paths, use a lightweight job without a paths filter that always reports, or use “required workflows” in rulesets.

remote: error: GH006: Protected branch update failed for refs/heads/main.

Cause: This is expected behavior: main is protected, so changes must go through a PR. Fix: Create a branch and open a PR. Admins are also blocked because enforce_admins: true, which should stay enabled in production.

Error acquiring the state lock … state blob is already locked

Cause: CI and someone's local plan/apply accessed the same state at the same time, or the lease was not released after a previous CI run was cancelled.

az storage blob show --account-name $STATE_SA -c tfstate -n lab3/myapp.tfstate --auth-mode login --query "properties.lease"

Fix: After confirming no apply is running, use the Lock ID from the error to run terraform force-unlock <ID>. Prevention: in the workflow, use concurrency to serialize (Module 2), and do not run any local write operations other than plan/apply against shared environments.

Deployment is waiting for approval, but no one in the reviewer list can click “Approve”

Cause: Turned on prevent_self_review while the only reviewer is the triggering person; or the reviewer team has no read access to the repository.

Fix: Add other reviewers or teams to the environment and confirm they have at least read access to the repository; in a lab environment you may temporarily turn off prevent self-review.

Command-line tasks
1. Use gh to check whether branch protection on main requires CODEOWNERS review.
gh api "repos/$REPO/branches/main/protection" --jq .required_pull_request_reviews.require_code_owner_reviews
2. List the protection rule types of the production environment.
gh api "repos/$REPO/environments/production" --jq '[.protection_rules[].type]'
Scenario analysis
The team wants “merge means go live” but worries that the plan on the PR becomes stale. Without adding manual approval, how would you design this?

① Enable strict (or a merge queue) on branch protection so PR checks run against the latest main; ② after merge, the workflow re-plans and saves the plan. Then runs an automated review of the plan: use terraform show -json to count delete/replace actions; if there are deletions or replacements, or a policy check fails, it automatically switches to manual approval (puts the apply job in an environment that requires approval); otherwise it automatically applies the same plan file; ③ concurrency serializes runs; ④ drift detection as a safety net. This way routine changes that only add resources are fully automatic, and only high-risk changes need a human.

Verified teaching videos

▶
Day 15 - Terraforming with GitHub Actions with Ned Bellavance — Festive Tech Calendar
English · the end-to-end approach to running Terraform with GitHub Actions, matching this module's process design (Action versions follow this lesson)
▶
Terraform Automation with Atlantis — Engineering with Morris
English · the “apply before merge” pattern (Atlantis) for comparison

Official documentation

Video storyboard script (about 90 seconds)

This courseware cannot generate video or MP3 directly; the storyboard and narration script are provided for a video tool to generate.

Shot 1 · 0–15s
Visual: a laptop connects directly to the cloud, with a question mark floating beside it reading “who changed this?”.
Narration: applying to production from a laptop gives non-reproducible results, scattered credentials, and no audit trail.
Shot 2 · 15–45s
Visual: a PR card passes through three green gates in turn (fmt, validate, plan), and the plan output becomes a PR comment.
Narration: GitOps makes Git the single entry point. The PR is the proposal, the plan is the evidence, and review is the decision.
Shot 3 · 45–70s
Visual: after merge, a tfplan file with a lock icon is generated; the approver clicks Approve, and the same file is fed into apply.
Narration: after merge, the plan is regenerated and saved; once approved, the same plan is executed. If the state changes, the plan automatically becomes invalid.
Shot 4 · 70–90s
Visual: three boxes (dev, staging, production) light up in turn with the same commit number, each with a different key attached.
Narration: what gets promoted is the same commit; each environment has its own state, its own identity and its own approver.
or score ≥ 70% on the “Quiz”

Module 2 · GitHub Actions + OIDC plan and apply

07:00 – 17:00 · No long-lived keys: each job obtains a cloud token valid for a few tens of minutes on the spot, and apply uses the approved plan file
10 minsetup-terraform v4.0.1 · azure/login v3.1.0 · configure-aws-credentials v6.3.0Core module of this lesson★★★★★
Learning objectives
  • Explain the full OIDC federation chain: GitHub issues a JWT (iss/sub/aud) → the cloud validates it against trust conditions → exchanges it for a short-lived access token; and reads sub claims, and uses them to configure different identities for PRs, main and production.
  • On Azure, use a user-assigned managed identity + federated identity credentials, on AWS, use IAM OIDC provider + role trust policy to complete the setup (both CLI and Terraform variants).
  • Write a two-stage workflow: plan on PR and comment; on main plan -out → upload artifact → environment approval → download and apply the same plan; use concurrency, least permissions, pin Actions by SHA.
Prerequisites: Module 1; Hour 3 azurerm authentication (Hour 4 AWS authentication is optional). Importance:★★★★★

What: Workload Identity Federation

GitHub Actions is an OIDC identity provider (issuer https://token.actions.githubusercontent.com). When a job declares permissions: id-token: write , the runner gets two environment variables ACTIONS_ID_TOKEN_REQUEST_URL and ACTIONS_ID_TOKEN_REQUEST_TOKEN, it can request a signed JWT, which describes which repository, which branch or environment, and which run it is. The cloud platform is pre-configured to trust tokens from that issuer that sub/aud meet the conditions, so it exchanges the JWT for its own short-lived access token. No long-lived keys are stored in GitHub Secrets at any point.

The most important claims in the JWT

ClaimExamplePurpose
isshttps://token.actions.githubusercontent.comThe cloud uses it to find the OIDC discovery document and signing public keys (JWKS)
audAzure: api://AzureADTokenExchange; AWS: sts.amazonaws.comPrevents a token issued for A from being used for B
subrepo:yourname/myapp-infra:pull_request
repo:yourname/myapp-infra:ref:refs/heads/main
repo:yourname/myapp-infra:environment:production
Core of trust conditions. If the job is bound to environment then sub is the environment form; for PR-triggered runs it is pull_request; otherwise it is ref form (tag is ref:refs/tags/…)
repository,ref,sha,workflow,job_workflow_ref,run_id,actor…for auditing; AWS can add conditions on more claims in the trust policy; GitHub also supports custom sub claim templates

Why: why OIDC must replace keys

  • No keys to leak: service principal passwords and access keys, once leaked (logs, forks, a compromised third-party Action), stay valid until rotated; OIDC tokens are only valid within the job and expire after a few tens of minutes.
  • Fine-grained trust: PRs from the same repository can only get a read-only identity; only jobs in the production environment can get a write-permission identity, which keys cannot do.
  • Zero-rotation operations: there are no expiring passwords to remind about and rotate.

How: key configuration points for the two clouds

Azure (Entra ID)AWS (IAM)
Trust targeton a user-assigned managed identity (or app registration) federated identity credential: issuer + subject + audienceAccount-level IAM OIDC identity provider + role trust policy (sts:AssumeRoleWithWebIdentity)
subject matchingDefault exact match; each identity or app can have at most 20 federated credentials (for wildcard “flexible federated credentials”, follow the current official docs)StringEquals or StringLike (can use *), always validate aud
token exchangePOST login.microsoftonline.com/{tenant}/oauth2/v2.0/token,client_assertion=<GitHub JWT>STS AssumeRoleWithWebIdentity, returns temporary AK/SK/SessionToken
On the Terraform sideARM_USE_OIDC=true + ARM_CLIENT_ID/ARM_TENANT_ID/ARM_SUBSCRIPTION_ID; the azurerm provider and azurerm backend automatically read ACTIONS_ID_TOKEN_REQUEST_* to get the tokenaws-actions/configure-aws-credentials ; it writes temporary credentials into environment variables, and the provider and S3 backend use these directly
for authorizationRBAC role assignments (Reader / Contributor / Storage Blob Data Contributor)the role's permission policy

Key design points for the two-stage workflow

  • plan file as artifact: the plan job uses actions/upload-artifact to upload tfplan (set retention-days to 1–5 days); the apply job runs on a brand-new runner and init runs init (same Terraform version, same lock file), then downloads and apply tfplan. The plan file contains plaintext sensitive values; anyone with read access to the repository can download the artifact, so use a private repository with short retention, and encrypt if needed.
  • environment approval: the apply job writes environment: production, GitHub pauses the job before it starts and waits for approval; before approval the job gets no environment-level variables or secrets, nor environment:production an OIDC token for the subject.
  • concurrency: put deployment workflows for the same state in the same concurrency group and set cancel-in-progress: false—never cancel mid-apply. GitHub's concurrency group allows at most one running and one pending run; a new pending run replaces the old pending one (which is cancelled). This is reasonable for Terraform, because the latest commit includes all previous changes.
  • Pin Actions by SHA: a tag is a movable pointer; a compromised Action repository can repoint v4 to a malicious commit (this is what happened in the March 2025 tj-actions/changed-files incident). Write it as uses: owner/repo@<40-char SHA> # vX.Y.Z, use Dependabot to upgrade automatically; organizations can enforce full SHA pinning in their Actions policy.
  • Minimal permissions: set the top level of the workflow to contents: read, and grant only in the jobs that need it id-token: write,pull-requests: write.
  • setup-terraform's wrapper: the default terraform_wrapper: true wraps the terraform binary to expose stdout/stderr/exitcode as step outputs. When you need to redirect terraform show -json to a file or handle the exit code yourself, set it to false is more controllable. v4 requires runners that support Node.js 24 (GitHub-hosted runners already do; self-hosted runners need the runner upgraded).

When: which scenarios need extra care

  • PRs from forks: from forks, the pull_request event cannot get id-token: write, and only a read-only token is available. In public repositories the plan job should skip forks (or be triggered manually). Do not use pull_request_target to check out and run a fork's code: this hands your permissions to a stranger's Terraform configuration (external data sources and malicious providers can both run arbitrary commands).
  • A PR plan is also code execution: plan runs providers and external/http data sources, so the PR identity must be read-only and cannot read production secrets.
  • The plan identity also needs to write the state lock: the azurerm backend lock is a Blob lease and requires Storage Blob Data Contributor (scoped to the tfstate container).

Comparison with similar technologies

OIDC federationService principal keys / access keys stored in SecretsSelf-hosted runner + managed identity
Leak riskVery low (short-lived tokens, bound to aud/sub)High (long-lived)Medium (compromising the runner grants the identity)
GranularityBy branch / environment / PROne key for all jobsBy runner pool
OperationsNo rotationRegular rotationMaintain runners
Suitable forGitHub-hosted runners accessing public clouds (preferred)Legacy systems that do not support OIDCNeeds access to a private network (e.g., state behind a private endpoint)
Common misconceptions① “Using OIDC,sub making the subject broad is fine” —repo:org/* means any repository in the organization (including newly created test repositories) can get this identity. ② “aud not checking is fine” — AWS must validate token.actions.githubusercontent.com:aud. ③ “Environment approval is just a UI confirmation” — it controls environment secrets, environment variables and OIDC sub tokens, which makes it the identity boundary. ④ “Re-planning and then applying at apply time is equally fine” — that does not execute the approved plan.

Architecture diagram: OIDC token exchange (Azure and AWS)

GitHub-hosted runner job: apply · environment: production permissions: id-token: write ACTIONS_ID_TOKEN_REQUEST_URL ACTIONS_ID_TOKEN_REQUEST_TOKEN terraform (azurerm / aws provider) GitHub OIDC Provider token.actions.githubusercontent.com issues JWT (RS256) sub=repo:o/r:environment:production ① request ② JWT Microsoft Entra ID federated credential: issuer + subject + aud fetch JWKS to verify signature · compare sub → ARM access token (managed identity) RBAC: Contributor@rg-tf-lab AWS STS AssumeRoleWithWebIdentity IAM OIDC provider + trust policy aud=sts.amazonaws.com · sub condition → temporary AK/SK/SessionToken ③ client_assertion=JWT ③' WebIdentityToken=JWT ④ use the short-lived token to call the cloud API ARM: PUT /subscriptions/…/containerApps/ca-myapp-prod Blob: lease on tfstate/lab3/myapp.tfstate (state lock) Token expires in about 1 hour; invalidated when the job ends
Figure 2-1: GitHub only proves “who I am”; the cloud decides “which identity you get” based on trust conditions; authorization is still decided by RBAC / IAM

Flow chart: two-stage workflow (plan on PR / plan after merge → approval → apply)

terraform-pr.yml (on: pull_request) · identity id-tf-plan (sub …:pull_request) checkout fmt · initvalidate plan -out-detailed-exitcode show -jsonconftest / -policies gh pr commentplan summary + collapsed full text terraform-deploy.yml (on: push main) · concurrency: tf-deploy-azure-prod (do not cancel in-progress runs) job plan (id-tf-plan, sub …:ref:refs/heads/main) init → plan -out=tfplanpolicy check (failure stops the run)upload-artifact tfplan-${sha}outputs.exitcode = 0 | 2 environment: productionwait for required reviewersonly protected branches can deploy job apply (id-tf-prod, sub …:environment:production) if: needs.plan.outputs.exitcode == '2'init (same version + lock file) → download-artifactterraform apply tfplanstate changed → Saved plan is stale
Figure 2-2: the PR stage is read-only and comments; the plan from after merge is saved as an artifact, and after approval the same file is applied on a fresh runner

Core animation: the full pipeline after a PR is merged

Step by step: OIDC exchange for a cloud token → init (remote state) → plan (provider gRPC) → policy evaluation → manual approval → on the new runner apply the same plan file. Tick “fault injection” to see which step the real error appears at.

① triggerpush main ② OIDCJWT → Entra token ③ initazurerm backend ④ plangRPC Plan…Change ⑤ policyplan JSON evaluation ⑥ artifactupload tfplan ⑦ approvalenv: production ⑧ new runner OIDCsub …:environment:production ⑨ init + downloadsame version · same lock file ⑩ apply tfplangRPC Apply…Change ⑪ write stateserial+1 · release lease job plan (id-tf-plan) ↑ | ↓ job apply (id-tf-prod, fresh runner, shares only the artifact and commit)

Core commands and configuration

Command / configurationPurposeKey parameters
az identity createCreate user-assigned managed identity-g -n -l; output clientId,principalId
az identity federated-credential createAdd federated identity credential--issuer --subject --audiences
az role assignment createRBAC authorization--assignee-object-id --assignee-principal-type ServicePrincipal --role --scope
aws iam create-open-id-connect-providerRegister GitHub OIDC provider (once per account)--url --client-id-list
aws iam create-roleCreate a role that web identities can assume--assume-role-policy-document
gh variable setSet repository/environment variables (client ID is not a secret)--env production
gh run watch / gh run view --log-failedTrack and troubleshoot runs--exit-status

Azure: two identities, three federated credentials (CLI approach)

LOC=canadacentral
# 1) plan identity: used for plans on both PRs and main
az identity create -g $STATE_RG -n id-tf-plan -l $LOC -o none
az identity federated-credential create -g $STATE_RG --identity-name id-tf-plan -n gh-pull-request \
  --issuer https://token.actions.githubusercontent.com \
  --subject "repo:${REPO}:pull_request" --audiences api://AzureADTokenExchange -o none
az identity federated-credential create -g $STATE_RG --identity-name id-tf-plan -n gh-main \
  --issuer https://token.actions.githubusercontent.com \
  --subject "repo:${REPO}:ref:refs/heads/main" --audiences api://AzureADTokenExchange -o none

# 2) prod apply identity: trusts only the production environment
az identity create -g $STATE_RG -n id-tf-prod -l $LOC -o none
az identity federated-credential create -g $STATE_RG --identity-name id-tf-prod -n gh-env-production \
  --issuer https://token.actions.githubusercontent.com \
  --subject "repo:${REPO}:environment:production" --audiences api://AzureADTokenExchange -o none

PLAN_CLIENT=$(az identity show -g $STATE_RG -n id-tf-plan --query clientId -o tsv)
PLAN_OID=$(az identity show -g $STATE_RG -n id-tf-plan --query principalId -o tsv)
PROD_CLIENT=$(az identity show -g $STATE_RG -n id-tf-prod --query clientId -o tsv)
PROD_OID=$(az identity show -g $STATE_RG -n id-tf-prod --query principalId -o tsv)

# 3) authorization: plan = Reader (workload RG) + Blob Data Contributor (tfstate container only, for lease locking)
LAB_SCOPE=/subscriptions/$SUB_ID/resourceGroups/rg-tf-lab
STATE_SCOPE=/subscriptions/$SUB_ID/resourceGroups/$STATE_RG/providers/Microsoft.Storage/storageAccounts/$STATE_SA/blobServices/default/containers/tfstate
az role assignment create --assignee-object-id $PLAN_OID --assignee-principal-type ServicePrincipal --role Reader --scope $LAB_SCOPE -o none
az role assignment create --assignee-object-id $PLAN_OID --assignee-principal-type ServicePrincipal --role "Storage Blob Data Contributor" --scope $STATE_SCOPE -o none
#    prod = Contributor (workload RG) + Blob Data Contributor
az role assignment create --assignee-object-id $PROD_OID --assignee-principal-type ServicePrincipal --role Contributor --scope $LAB_SCOPE -o none
az role assignment create --assignee-object-id $PROD_OID --assignee-principal-type ServicePrincipal --role "Storage Blob Data Contributor" --scope $STATE_SCOPE -o none

az identity federated-credential list -g $STATE_RG --identity-name id-tf-plan --query "[].{name:name,subject:subject}" -o table
Name             Subject
---------------  ------------------------------------------
gh-pull-request  repo:yourname/myapp-infra:pull_request
gh-main          repo:yourname/myapp-infra:ref:refs/heads/main

How to verify:az role assignment list --assignee $PROD_OID --all -o table. Common errors: Role assignments take tens of seconds to a few minutes to propagate, so running the workflow immediately may return 403; case or extra spaces in the subject will cause AADSTS700213. Production use: The prod identity's scope should be the production subscription or resource group, not the whole tenant; if Terraform also needs to create role assignments, use “Role Based Access Control Administrator” (which can be conditioned to limit assignable roles) rather than Owner.

azurerm resource provider registration Since azurerm 4.0 (carried into 5.x), it uses resource_provider_registrations (default "core") registers a set of resource providers at startup, which requires subscription-level */register/action permission. The read-only plan identity does not have this permission and may report AuthorizationFailed … register/action. Fix: the platform team pre-registers the required RPs and sets them in the provider resource_provider_registrations = "none" (exact values and the default set depend on the azurerm version docs you use).

Azure: manage the same configuration with Terraform (recommended in a separate “bootstrap” stack)

variable "github_repo" { type = string }   # e.g. "yourname/myapp-infra"

locals {
  gh_issuer = "https://token.actions.githubusercontent.com"
  gh_aud    = ["api://AzureADTokenExchange"]
}

resource "azurerm_user_assigned_identity" "tf_prod" {
  name                = "id-tf-prod"
  resource_group_name = "rg-tfstate"
  location            = "canadacentral"
}

resource "azurerm_federated_identity_credential" "tf_prod_env" {
  name                      = "gh-env-production"
  user_assigned_identity_id = azurerm_user_assigned_identity.tf_prod.id
  issuer                    = local.gh_issuer
  audience                  = local.gh_aud
  subject                   = "repo:${var.github_repo}:environment:production"
}

data "azurerm_resource_group" "lab" { name = "rg-tf-lab" }

resource "azurerm_role_assignment" "tf_prod_contrib" {
  scope                = data.azurerm_resource_group.lab.id
  role_definition_name = "Contributor"
  principal_id         = azurerm_user_assigned_identity.tf_prod.principal_id
  principal_type       = "ServicePrincipal"
}

azurerm_federated_identity_credential The parameters are name,user_assigned_identity_id,audience,issuer,subject (see provider docs; earlier versions used parent_id). The bootstrap stack itself is run by an admin locally or in a separate high-privilege pipeline —do not let the prod identity change its own federated credentials.

AWS: OIDC provider + role (Terraform version, matching Hour 4)

resource "aws_iam_openid_connect_provider" "github" {
  url            = "https://token.actions.githubusercontent.com"
  client_id_list = ["sts.amazonaws.com"]
  # In the aws provider 6.x, thumbprint_list can be omitted (AWS validates this issuer with trusted root CAs)
}

data "aws_iam_policy_document" "gh_prod_trust" {
  statement {
    actions = ["sts:AssumeRoleWithWebIdentity"]
    principals {
      type        = "Federated"
      identifiers = [aws_iam_openid_connect_provider.github.arn]
    }
    condition {
      test     = "StringEquals"
      variable = "token.actions.githubusercontent.com:aud"
      values   = ["sts.amazonaws.com"]
    }
    condition {
      test     = "StringEquals"
      variable = "token.actions.githubusercontent.com:sub"
      values   = ["repo:yourname/myapp-infra:environment:production"]
    }
  }
}

resource "aws_iam_role" "gh_tf_prod" {
  name                 = "gh-tf-prod"
  assume_role_policy   = data.aws_iam_policy_document.gh_prod_trust.json
  max_session_duration = 3600
}
# Permission policy: attach the minimum permissions required by the Hour 4 stack (ECS, EC2/VPC, IAM PassRole, read/write *.tfstate and *.tflock in the S3 state bucket)
    permissions: { id-token: write, contents: read }
    steps:
      - uses: aws-actions/configure-aws-credentials@e1253824e5c10ff9df46874f81ed3ec929e19cfd # v6.3.0
        with:
          role-to-assume: arn:aws:iam::123456789012:role/gh-tf-prod
          aws-region: ca-central-1
          role-session-name: gh-${{ github.run_id }}
      - run: aws sts get-caller-identity
{
    "UserId": "AROAXXXXXXXXXXXXXXXXX:gh-123456789",
    "Account": "123456789012",
    "Arn": "arn:aws:sts::123456789012:assumed-role/gh-tf-prod/gh-123456789"
}

Write the non-secret IDs into repository / environment variables

gh variable set AZURE_TENANT_ID       --body "$TENANT_ID"
gh variable set AZURE_SUBSCRIPTION_ID --body "$SUB_ID"
gh variable set AZURE_PLAN_CLIENT_ID  --body "$PLAN_CLIENT"
gh variable set AZURE_CLIENT_ID       --env production --body "$PROD_CLIENT"   # visible only to the production environment
gh variable list; gh variable list --env production

Client ID, tenant ID and subscription ID are not secrets (you cannot log in with them alone), and they are placed in vars so they are easy to troubleshoot in logs. The real protection comes from the federated credential subject and environment rules.

Lab 2: two-stage Terraform pipeline (about 10 min)

Complete the Azure identity and variable setup on the “Commands” page (two managed identities, three federated credentials, four role assignments, four variables). Wait 1–2 minutes for RBAC to propagate.
PR workflow: plan + comment (simplified version of Module 1):
name: terraform-pr
on:
  pull_request:
    branches: [main]
permissions:
  contents: read
concurrency:
  group: tf-pr-${{ github.event.pull_request.number }}
  cancel-in-progress: true          # old plans on a PR have no value and can be cancelled
env:
  TF_IN_AUTOMATION: "true"
  TF_INPUT: "false"
  ARM_USE_OIDC: "true"
  ARM_CLIENT_ID: ${{ vars.AZURE_PLAN_CLIENT_ID }}
  ARM_TENANT_ID: ${{ vars.AZURE_TENANT_ID }}
  ARM_SUBSCRIPTION_ID: ${{ vars.AZURE_SUBSCRIPTION_ID }}
jobs:
  terraform-plan:
    name: terraform-plan
    # public repos: skip forks (they cannot get id-token)
    if: github.event.pull_request.head.repo.full_name == github.repository
    runs-on: ubuntu-24.04
    permissions:
      contents: read
      id-token: write
      pull-requests: write
    defaults: { run: { working-directory: azure } }
    steps:
      - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
      - uses: hashicorp/setup-terraform@dfe3c3f87815947d99a8997f908cb6525fc44e9e # v4.0.1
        with:
          terraform_version: "1.17.2"
          terraform_wrapper: false
      - run: terraform fmt -check -recursive
      - run: terraform init -lockfile=readonly
      - run: terraform validate
      - id: plan
        run: |
          set +e
          terraform plan -lock-timeout=5m -out=tfplan -detailed-exitcode
          ec=$?
          echo "exitcode=$ec" >> "$GITHUB_OUTPUT"
          if [ "$ec" -eq 1 ]; then exit 1; fi
      - run: terraform show -json tfplan > plan.json
      - name: Comment plan on PR
        env:
          GH_TOKEN: ${{ github.token }}
          PR: ${{ github.event.pull_request.number }}
          EC: ${{ steps.plan.outputs.exitcode }}
        run: |
          terraform show -no-color tfplan > plan.txt
          SUMMARY=$(grep -E '^Plan:|^No changes' plan.txt | tail -1)
          {
            echo "### Terraform plan · \`azure\` · ${SUMMARY:-see details}"
            echo "exitcode=${EC} · commit ${GITHUB_SHA::7} · run ${GITHUB_RUN_ID}"
            echo "<details><summary>Expand full plan</summary>"
            echo; echo '```'; head -c 60000 plan.txt; echo '```'; echo "</details>"
          } > comment.md
          gh pr comment "$PR" --repo "$GITHUB_REPOSITORY" --body-file comment.md --edit-last \
            || gh pr comment "$PR" --repo "$GITHUB_REPOSITORY" --body-file comment.md

-lockfile=readonly: in CI, do not init modify the lock file; if the lock file is missing hashes for the current platform, fail immediately instead of rewriting it silently. head -c 60000: GitHub comment bodies are limited to about 65536 characters. --edit-last Keep only one latest plan comment per PR (fall back to creating a new one when there is no editable comment yet).

Deployment workflow: plan → artifact → approval → apply the same plan:
name: terraform-deploy
on:
  push:
    branches: [main]
    paths: ["azure/**"]
  workflow_dispatch:
permissions:
  contents: read
concurrency:
  group: tf-deploy-azure-prod
  cancel-in-progress: false         # never cancel an apply midway
env:
  TF_IN_AUTOMATION: "true"
  TF_INPUT: "false"
  TF_VERSION: "1.17.2"
  ARM_USE_OIDC: "true"
  ARM_TENANT_ID: ${{ vars.AZURE_TENANT_ID }}
  ARM_SUBSCRIPTION_ID: ${{ vars.AZURE_SUBSCRIPTION_ID }}
jobs:
  plan:
    runs-on: ubuntu-24.04
    permissions: { contents: read, id-token: write }
    env:
      ARM_CLIENT_ID: ${{ vars.AZURE_PLAN_CLIENT_ID }}
    defaults: { run: { working-directory: azure } }
    outputs:
      exitcode: ${{ steps.plan.outputs.exitcode }}
    steps:
      - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
      - uses: hashicorp/setup-terraform@dfe3c3f87815947d99a8997f908cb6525fc44e9e # v4.0.1
        with: { terraform_version: "${{ env.TF_VERSION }}", terraform_wrapper: false }
      - run: terraform init -lockfile=readonly
      - id: plan
        run: |
          set +e
          terraform plan -lock-timeout=5m -out=tfplan -detailed-exitcode
          ec=$?; echo "exitcode=$ec" >> "$GITHUB_OUTPUT"
          if [ "$ec" -eq 1 ]; then exit 1; fi
          terraform show -no-color tfplan >> "$GITHUB_STEP_SUMMARY"
      - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
        if: steps.plan.outputs.exitcode == '2'
        with:
          name: tfplan-${{ github.sha }}
          path: azure/tfplan
          retention-days: 3
          if-no-files-found: error

  apply:
    needs: plan
    if: needs.plan.outputs.exitcode == '2'
    runs-on: ubuntu-24.04
    environment: production           # approval gate + OIDC sub = environment:production
    permissions: { contents: read, id-token: write }
    env:
      ARM_CLIENT_ID: ${{ vars.AZURE_CLIENT_ID }}   # from the production environment variable
    defaults: { run: { working-directory: azure } }
    steps:
      - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
      - uses: hashicorp/setup-terraform@dfe3c3f87815947d99a8997f908cb6525fc44e9e # v4.0.1
        with: { terraform_version: "${{ env.TF_VERSION }}", terraform_wrapper: false }
      - run: terraform init -lockfile=readonly
      - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
        with:
          name: tfplan-${{ github.sha }}
          path: azure
      - run: terraform apply -lock-timeout=5m tfplan
git add .github/workflows && git commit -m "Add OIDC plan/apply workflows"
git push origin HEAD:refs/heads/ci/oidc && gh pr create --head ci/oidc --fill
gh pr checks --watch
Make a real change: change the Container App's max_replicas from 2 to 3, open a PR, and check the PR comment:
### Terraform plan · `azure` · Plan: 0 to add, 1 to change, 0 to destroy.
exitcode=2 · commit 4e1a9c2 · run 11873420551
▸ Expand full plan
  # azurerm_container_app.myapp will be updated in-place
  ~ resource "azurerm_container_app" "myapp" {
        id   = "/subscriptions/…/containerApps/ca-myapp-prod"
      ~ template {
          ~ max_replicas = 2 -> 3
            # (3 unchanged attributes hidden)
        }
    }
Merge and approve:
gh pr merge --squash --delete-branch
gh run list --workflow terraform-deploy.yml --limit 1
gh run watch          # apply job shows "Waiting for review"
# Browser: Actions → that run → Review deployments → tick production → Approve and deploy
Acquiring state lock. This may take a few moments...
azurerm_container_app.myapp: Modifying... [id=/subscriptions/…/containerApps/ca-myapp-prod]
azurerm_container_app.myapp: Modifications complete after 18s [id=/subscriptions/…/containerApps/ca-myapp-prod]
Releasing state lock. This may take a few moments...

Apply complete! Resources: 0 added, 1 changed, 0 destroyed.
Verify that “apply runs exactly the approved plan”: open another PR and merge it; while apply waits for approval, run one terraform apply -refresh-only -auto-approve (changes the state serial) against the same state from a local machine, then approve. The apply job should fail:
Error: Saved plan is stale

The given plan file can no longer be applied because the state was changed by another operation after the plan was created.

Fix: re-run the whole workflow (gh run rerun <id>), generate a new plan and approve it. This is the safety property we want.

Cleanup: keep the identities and workflow for the capstone lab; Module 8 provides the commands to delete identities, federated credentials and role assignments in one place.

Case 1: migrating from service principal keys to OIDC

Problem: 40 repositories shared one Contributor-level service principal, with its key stored in organization Secrets; each annual rotation broke a batch of pipelines, and a compromised third-party Action forced an emergency key rotation. Fix: Create managed identities and federated credentials per “repository × environment” (generated in bulk with a Terraform bootstrap stack); PR identities get Reader, and the prod identity is scoped to the matching resource group; finally delete the old service principal keys. Configuration: In the workflow, remove ARM_CLIENT_SECRET, and add ARM_USE_OIDC: "true". Limitation: Each managed identity can have at most 20 federated credentials; with many environments, use GitHub custom sub claim templates, or one identity per environment.

Case 2: lock conflicts and duplicate changes caused by concurrent applies

Problem: Two PRs merged one minute apart; both deploy runs planned at the same time; the second one got stuck on the state lock during apply and timed out; when re-run, it was based on old code. Fix: In the deployment workflow, add concurrency: tf-deploy-azure-prod + cancel-in-progress: false: GitHub queues the second run, and if a third arrives it replaces the second (keeping only the latest). Limitation: concurrency only applies within the same repository; when multiple repositories write the same state (not recommended), you still rely on the state lock and -lock-timeout.

Case 3: Action supply-chain attack

Problem: In March 2025, a tag was repointed to a malicious commit, which printed secrets from runner memory into the logs; every repository that used @v45 was affected, whereas repositories pinned to a SHA were not. Fix: Pin all third-party Actions to full SHAs with the version noted; Dependabot package-ecosystem: github-actions automatically opens PRs to upgrade; the organization Actions policy allows only allowlisted Actions and requires SHA pinning. Limitation: SHA pinning does not protect against “a pinned version that itself has a vulnerability”; you still need to watch security advisories.

Common errors and fixes

AADSTS700213: No matching federated identity record found for presented assertion subject 'repo:yourname/myapp-infra:environment:production'

Cause: The JWT's sub claim and the federated credential's subject do not match exactly. The most common cause: the job added environment: , after which sub changed from ref:refs/heads/main to environment:production; or the repository was renamed or has different casing.

az identity federated-credential list -g $STATE_RG --identity-name id-tf-prod --query "[].subject" -o tsv
# temporarily print sub in the workflow (print only the claim, not the token itself):
curl -sH "Authorization: bearer $ACTIONS_ID_TOKEN_REQUEST_TOKEN" "$ACTIONS_ID_TOKEN_REQUEST_URL&audience=api://AzureADTokenExchange" \
  | jq -r .value | cut -d. -f2 | tr '_-' '/+' | base64 -d 2>/dev/null | jq '{sub,aud,ref,environment}'

Fix: Add a federated credential for the actual sub (the error message already shows the full sub).

Error: Unable to get ACTIONS_ID_TOKEN_REQUEST_URL env variable

Cause: The job lacks permissions: id-token: write; the PR comes from a fork; or a job-level permissions overrides the top level (job-level replaces rather than merges).

Fix: In the job that needs it, explicitly set id-token: write (while also keeping contents: read, otherwise checkout fails); skip fork PRs or switch them to manual trigger.

Error: Failed to get existing workspaces: … StatusCode=403 … AuthorizationPermissionMismatch

Cause: The backend uses Entra authentication (use_azuread_auth = true), the identity lacks a Storage Blob Data role, or the role assignment has not propagated yet. Note that Contributor/Owner are management-plane roles,do not include read/write access to Blob data.

az role assignment list --assignee $PLAN_OID --all --query "[].{role:roleDefinitionName,scope:scope}" -o table

Fix: Grant “Storage Blob Data Contributor” scoped to the tfstate container, wait a few minutes, and retry.

Error: Saved plan is stale

Cause: The state changed after the plan was generated (another apply, refresh-only, state mv, etc.). Terraform checks the state lineage and serial recorded in the plan.

Fix: Re-run the whole deployment workflow and approve again. Prevention: serialize with concurrency; do not perform other operations that write state while waiting for approval.

Error: Failed to load "tfplan" as a plan file … plan file was created by Terraform 1.17.2, but this is 1.17.1

Cause: The plan and apply jobs used different Terraform versions (for example, one pinned a version and the other used latest).

Fix: Both jobs use env.TF_VERSION; also make sure the apply job's init uses the same lock file (the plan file records provider checksums).

Error: building account: … AuthorizationFailed … does not have authorization to perform action 'Microsoft.App/containerApps/listSecrets/action'

Cause: The Reader role only contains */read, but some resources need POST-style list actions (to read keys/secrets) when refreshed, such as listKeys,listSecrets.

Fix: Create a custom role for the plan identity: "Actions": ["*/read", "Microsoft.App/containerApps/listSecrets/action", "Microsoft.Storage/storageAccounts/listKeys/action"], add the missing actions one by one according to the actual errors; it still contains no write operations.

Command-line tasks
1. Add a federated credential to the id-tf-dev identity that trusts only the dev environment.
az identity federated-credential create -g rg-tfstate --identity-name id-tf-dev -n gh-env-dev \
  --issuer https://token.actions.githubusercontent.com \
  --subject "repo:${REPO}:environment:dev" --audiences api://AzureADTokenExchange
2. View the logs of the failed step in the most recent deployment run.
gh run list --workflow terraform-deploy.yml --limit 1 --json databaseId -q '.[0].databaseId' | xargs gh run view --log-failed
Scenario analysis
The security team found that the prod identity's federated credential subject is repo:yourorg/* (AWS StringLike), and the workflow uses @v4 tags. List the risks and a remediation plan.

Risk: any repository in the organization (including personally created test repositories and compromised low-value repositories) can assume the prod role; any branch or PR can obtain it; if a third-party Action tag is tampered with, malicious code runs in the job that holds the prod token. Remediation: ① pin sub exactly to repo:yourorg/myapp-infra:environment:production, also validate aud; ② restrict the production environment to protected branches, approvers and no self-review; ③ pin all Actions by SHA and use Dependabot; ④ narrow the prod role's permissions to the services and resources needed; ⑤ CloudTrail / activity log alerts on “this role assumed in an unexpected repository or workflow” (you can add conditions to job_workflow_ref in the trust policy).

Verified teaching video

▶
GitHub Actions with AWS and OIDC Integration | Wahl Network — channel display name: Uglarvisk
English · Full setup for GitHub Actions assuming an AWS role via OIDC (the Action version is older; this lesson takes precedence)
▶
Configuring Manual Approval in Terraform Deployments with GitHub Environments — vlogize
English · Short demo of the environment approval gate

Official docs

Video storyboard script (about 120 seconds)

This courseware cannot generate video or MP3 directly, so a storyboard and narration script are provided instead.

Shot 1 · 0–20s
Visual: a glowing key in GitHub Secrets is copied into the logs, with a red alert.
Narration: once a long-lived secret leaks, it stays valid until it is rotated. OIDC means the pipeline stores no secrets at all.
Shot 2 · 20–50s
Visual: the runner requests an “ID card” JWT from GitHub, zoomed in to show the iss, aud, and sub fields.
Narration: the token GitHub issues states the repository, branch, and environment. The sub field is the core of the cloud trust condition.
Shot 3 · 50–80s
Visual: the JWT is sent to two gates, Entra ID and AWS STS. The gatekeepers check the subject and return a one-hour ticket.
Narration: the cloud checks the issuer, audience, and subject. On a match, it exchanges them for a short-lived access token. Access is still decided by role assignments.
Shot 4 · 80–120s
Visual: the plan file is uploaded inside a locked box. After approval, another runner takes the same box and runs apply. If the state was changed, the seal on the box turns red and shows “Saved plan is stale”.
Narration: after merge, the plan is generated and saved as an artifact. After approval, the same plan runs on a new runner. Once the state changes, the plan is automatically invalidated.
Or score ≥ 70% on the Quiz

Module 3 · HCP Terraform workspaces and runs

17:00 – 25:00 · Hand state, locks, runners, credentials, policy, and approvals to the platform. Your DIY pipeline needs all of them, and the platform builds them in.
8 minSaaS · continuously updatedThe legacy free plan ended on 2026-03-31★★★★
Learning objectives
  • Understand the Organization → Project → Workspace hierarchy. A workspace = one state + one set of variables + one set of run settings and permissions.
  • Compare VCS-driven, CLI-driven (cloud block), API-driven workflows, and the Remote / Local / Agent execution modes.
  • Configure variable sets and dynamic provider credentials (HCP Terraform as the OIDC issuer), and understand the four stages of run tasks.
  • Accurately state the 2026 billing model (per managed resource) and the differences between tiers.
Prerequisites: OIDC concepts from Module 2; remote state from Lesson 2. Importance:★★★★ (one of the most common managed options in enterprises)

What: what HCP Terraform is

HCP Terraform (formerly Terraform Cloud) is HashiCorp's managed service. It provides remote state and locking, remote runners, VCS integration, team permissions, a private module registry, policy as code, run tasks, cost estimation, health assessments (drift detection), and Stacks. Terraform Enterprise is its self-hosted version, with largely the same features and a slightly later release cadence.

Core concepts

ConceptDescription
OrganizationBoundaries of billing, SSO, teams, policy sets, and VCS connections
ProjectA grouping of workspaces, used for authorization (team permissions on projects) and for variable set scope
WorkspaceOne state + variables + run history + settings (Terraform version, working directory, execution mode, auto-apply, trigger paths). Not the same as the CLI terraform workspace .
Variable setA reusable set of variables (Terraform variables or environment variables) that applies to the whole organization, certain projects, or certain workspaces. Can be marked sensitive (cannot be read back after it is written).
RunOne plan (optionally followed by apply). A speculative plan only plans and cannot apply (used on PRs).
Run taskCalls external services at the pre-plan / post-plan / pre-apply / post-apply stages (security scans, cost, tickets). Results can be set to advisory or mandatory.
Policy setA set of Sentinel / OPA / Terraform Policy rules, applied to an organization, project, or workspace (Module 4).

Why: when a platform is worth it instead of a DIY pipeline

  • With a DIY setup you assemble everything yourself: state backend, locking, OIDC, plan comments, artifacts, approvals, policy, drift detection, and the permission model. The Module 2 workflow alone is already 150 lines, and every repo has to copy it.
  • In HCP Terraform these are workspace settings; the platform team can use the tfe provider to manage workspaces, teams, and variable sets in bulk as code.
  • Trade-offs: billed per managed resource, data is stored in SaaS (with a separate EU region), and runners that need private network access require an Agent.

How: the three workflows and three execution modes

WorkflowTriggerPR experienceBest for
VCS-drivenThe workspace connects a repo and branch; a push triggers a run, which can be filtered by path (trigger patterns)A PR automatically triggers a speculative plan and writes back a commit status and linkSimplest and most “GitOps”; the first choice for most teams
CLI-drivenWrite the cloud block, runs locally or in CI terraform plan/apply, the configuration is uploaded and runs on a remote runner, with logs streamed backDecided by your CIYou want to keep your existing CI but still use remote state, policies, and credentials; local development and debugging
API-drivenCI uploads a configuration version through the API and creates a runImplemented in CI (official GitHub Actions example provided)Complex orchestration, custom platforms

Note: for a workspace connected to VCS,not allowed to run from the CLI apply (speculative plan only), to ensure changes come from the repository.

Execution modeWhere plan/apply runsstateDescription
Remote (default)HashiCorp-managed runnerPlatformNeeds access to public APIs; dynamic credentials can be used
AgentHCP Terraform Agent in your network (pulls tasks)PlatformAccesses private networks and local resources; no inbound ports to open
LocalYour machine or CIPlatform (stores only state and locks)Uses the platform only as a backend; policies and run tasks are not executed in local runs

Dynamic Provider Credentials

Same principle as Module 2, except that the issuer is replaced with HCP Terraform (https://app.terraform.io). Each stage of every run issues a JWT,sub in the form:

organization:yourorg:project:myapp:workspace:myapp-azure-prod:run_phase:plan
organization:yourorg:project:myapp:workspace:myapp-azure-prod:run_phase:apply

So you can assign different identities to the plan and apply stages (read-only / read-write). Set environment variables in the workspace or variable set: for Azure, set TFC_AZURE_PROVIDER_AUTH=true + TFC_AZURE_RUN_CLIENT_ID (or set them separately TFC_AZURE_PLAN_CLIENT_ID / TFC_AZURE_APPLY_CLIENT_ID), then add ARM_SUBSCRIPTION_ID,ARM_TENANT_ID; for AWS, set TFC_AWS_PROVIDER_AUTH=true + TFC_AWS_RUN_ROLE_ARN (the default audience on the AWS side aws.workload.identity). Variable names and defaults follow the official “Dynamic provider credentials” documentation.

2026 pricing and tiers (verified 2026-11)

TierPriceKey points
Free (Enhanced)FreeUp to 500 managed resources, unlimited users; includes SSO, policy as code (Sentinel and OPA), run tasks, and HCP Terraform agents (HashiCorp 2025-12-17 blog post). Beyond 500, you must choose a paid tier or new resources cannot be added. Third-party sources say concurrent runs are 1; follow the console.
EssentialsAbout $0.10 / resource / monthRemote state, VCS, projects, remote runs, private registry, team management
StandardAbout $0.47 / resource / monthBuilds on Essentials, adding no-code modules, team notifications, and more; Health assessments (drift detection + continuous validation) are available from Standard
PremiumAbout $0.99 / resource / monthFull feature set (module revocation, Waypoint actions, etc.)
Legacy Free / Team plans—The legacy free plan was retired on 2026-03-31 and automatically migrated to Enhanced Free; Stacks are not available on legacy Team plans

A “managed resource” is roughly a resource in state resource instance (excluding data sources,null_resource/terraform_data generally not counted). Definitions and the per-tier feature matrix may change, so check hashicorp.com/pricing the official pricing page for current details.

When: selection criteria

  • Few resources, small team: Free tier + VCS-driven, with almost no operational overhead.
  • Many resources (thousands or more): compare per-resource billing with the total cost of self-managed GitHub Actions and a self-managed backend (staff time + risk), or consider Spacelift, env0, Scalr, Atlantis, and similar tools.
  • Strict compliance, data must stay on-premises: self-hosted Terraform Enterprise or a DIY setup.
  • OpenTofu users: HCP Terraform does not support OpenTofu; consider other TACOS platforms.

Comparison with a DIY setup

CapabilityDIY GitHub Actions (Module 2)HCP Terraform
state + lockingazurerm/S3 backendBuilt in, with version history and rollback (state versions)
CredentialsGitHub OIDCDynamic credentials (plan/apply separated)
Approvalenvironment reviewersConfirm & Apply, controlled by team permissions
PolicyIntegrate conftest yourself / -policiesPolicy sets, enforcement levels, and override auditing
DriftScheduled workflow (Module 5)Health assessments (from Standard)
Multi-environment orchestrationChained workflowsRun triggers, Stacks (Module 7)
Common misconceptions① “An HCP workspace is the same as terraform workspace”—the former is an independent unit of state, settings, and permissions; the latter is just a namespace for multiple states under one backend. ② “Using the cloud block, the plan runs locally”—under the default Remote mode it runs remotely and only the output is streamed locally; local environment variables (such as ARM_CLIENT_SECRET) are not carried over. ③ “The free tier has no policy”—since 2025-12, Enhanced Free includes Sentinel/OPA policies and run tasks, but health assessments require Standard.

Architecture diagram: organization, projects, workspaces, and credentials

Organization: yourorg (SSO · teams · VCS connection · policy sets) Project: myapp ws: myapp-azure-devVCS: main · auto-apply ws: myapp-azure-prodVCS: main · manual confirmation Variable set azure-oidc (project scope)TFC_AZURE_PROVIDER_AUTH=true … Policy set baselineSentinel / OPA / Terraform PolicyApplies to project myappmandatory · advisory Run taskspre-plan · post-planpre-apply · post-applySecurity scan / cost / tickets GitHub repowebhook → runPR ← commit status + plan link Entra ID / AWS STSTrusts issuer app.terraform.iosub …:workspace:…:run_phase:apply Agent pool (optional)Outbound polling for tasks inside the private network
Figure 3-1: a workspace is the unit of state + variables + settings + permissions; variable sets and policy sets are reused across projects

Flowchart: VCS-driven vs CLI-driven

VCS-driven git push / PR webhookThe platform pulls the configuration for that commit Remote runPR = speculative plan Merge → plan → confirm → applyCLI apply rejected CLI-driven (cloud block) terraform planLocal or CI Package and upload the configurationRespects .terraformignore Runs on the remote runnerLogs stream back to the terminal Variables/credentials come from the workspaceLocal environment variables are not uploaded
Figure 3-2: both run remotely; the difference is “who triggers” and “where the configuration comes from”

Interactive animation: stage flow of a remote run

Choose a workflow and options, then watch how the run status moves through HCP Terraform (status names match the run status in the API).

Core commands and configuration

Command / configurationPurposeNotes
terraform loginGet an API token and write it to ~/.terraform.d/credentials.tfrc.jsonIn CI, use the environment variable TF_TOKEN_app_terraform_io
cloud { … }CLI-driven workspaceorganization,workspaces { name | tags, project }
terraform init -migrate-stateMigrate state from an existing backend to HCPBack up the state before migrating
terraform plan / applyRun remotelyCtrl+C only disconnects the streamed output; the remote run may keep going
.terraformignoreControls which files are uploadedSyntax is similar to .gitignore
tfe providerManage organizations/projects/workspaces/variable sets/teams as codetfe_workspace,tfe_variable_set,tfe_variable

CLI-driven workspace

terraform {
  required_version = ">= 1.17.0"
  cloud {
    organization = "yourorg"           # Replace with your organization name
    workspaces {
      project = "myapp"
      name    = "myapp-hcp-demo"
    }
  }
  required_providers {
    azurerm = { source = "hashicorp/azurerm", version = "~> 5.0" }
  }
}

provider "azurerm" {
  features {}
  resource_provider_registrations = "none"
  # Credentials come from dynamic credentials: TFC_AZURE_PROVIDER_AUTH / TFC_AZURE_RUN_CLIENT_ID / ARM_SUBSCRIPTION_ID / ARM_TENANT_ID
}
data "azurerm_resource_group" "demo" { name = "rg-tf-hcp-demo" }

resource "azurerm_user_assigned_identity" "demo" {     # Free resource, for demo purposes
  name                = "id-hcp-demo"
  resource_group_name = data.azurerm_resource_group.demo.name
  location            = data.azurerm_resource_group.demo.location
  tags                = { app = "myapp", env = "demo", owner = "platform-team", cost-center = "cc-1001" }
}

output "principal_id" { value = azurerm_user_assigned_identity.demo.principal_id }
terraform login           # Browser generates the token; paste it back into the terminal
cd hcp-demo && terraform init
terraform plan
Running plan in HCP Terraform. Output will stream here. Pressing Ctrl-C
will stop streaming the logs, but will not stop the plan running remotely.

Preparing the remote plan...

To view this run in a browser, visit:
https://app.terraform.io/app/yourorg/myapp-hcp-demo/runs/run-AbCdEf123456

Waiting for the plan to start...

Terraform v1.17.2
on linux_amd64
Initializing plugins and modules...
data.azurerm_resource_group.demo: Reading...
...
Plan: 1 to add, 0 to change, 0 to destroy.

How to verify: Open the run link in a browser; you should see the plan log and the “Dynamic credentials” information. Common errors: If the workspace does not exist, init you will be prompted to create it. The Terraform version defaults to the workspace setting; it does not matter if it differs from local, because the run happens remotely. Production use: In CI, set TF_TOKEN_app_terraform_io (team token). This is enough to drive remote runs from GitHub Actions while still getting the platform's policies and credentials.

Dynamic credentials: Azure trusts HCP Terraform

az group create -n rg-tf-hcp-demo -l canadacentral -o none
az identity create -g rg-tf-hcp-demo -n id-tfc-demo -o none
for PHASE in plan apply; do
  az identity federated-credential create -g rg-tf-hcp-demo --identity-name id-tfc-demo -n tfc-$PHASE \
    --issuer https://app.terraform.io \
    --subject "organization:yourorg:project:myapp:workspace:myapp-hcp-demo:run_phase:$PHASE" \
    --audiences api://AzureADTokenExchange -o none
done
TFC_OID=$(az identity show -g rg-tf-hcp-demo -n id-tfc-demo --query principalId -o tsv)
TFC_CLIENT=$(az identity show -g rg-tf-hcp-demo -n id-tfc-demo --query clientId -o tsv)
az role assignment create --assignee-object-id $TFC_OID --assignee-principal-type ServicePrincipal \
  --role Contributor --scope /subscriptions/$SUB_ID/resourceGroups/rg-tf-hcp-demo -o none
echo "TFC_AZURE_RUN_CLIENT_ID=$TFC_CLIENT"

Manage variable sets as code with the tfe provider (platform team approach)

resource "tfe_variable_set" "azure_oidc" {
  name         = "azure-oidc-myapp"
  organization = "yourorg"
}
resource "tfe_project_variable_set" "myapp" {
  project_id      = tfe_project.myapp.id
  variable_set_id = tfe_variable_set.azure_oidc.id
}
resource "tfe_variable" "auth" {
  variable_set_id = tfe_variable_set.azure_oidc.id
  category        = "env"
  key             = "TFC_AZURE_PROVIDER_AUTH"
  value           = "true"
}
resource "tfe_variable" "client" {
  variable_set_id = tfe_variable_set.azure_oidc.id
  category        = "env"
  key             = "TFC_AZURE_RUN_CLIENT_ID"
  value           = var.tfc_client_id
}
# Also add ARM_SUBSCRIPTION_ID and ARM_TENANT_ID (category = "env")

tfe_project definition omitted; for resource and argument names, see the tfe provider documentationas the authority.

Lab 3: CLI-driven workspace + dynamic credentials (about 8 minutes, Azure cost: $0)

Sign up and create an organization: Visit app.terraform.io to sign up, create an organization (this lesson uses yourorg) and a project myapp. New organizations use Enhanced Free (free up to 500 managed resources).
Establish trust in Azure: Run the “Dynamic credentials” script on the Commands page, and note TFC_AZURE_RUN_CLIENT_ID.
Create the workspace and set variables: In the repo, create hcp-demo/ two files, then run terraform login and terraform init (this creates a CLI-driven workspace myapp-hcp-demo). On the workspace's Variables page, add environment variables: TFC_AZURE_PROVIDER_AUTH=true,TFC_AZURE_RUN_CLIENT_ID=<output from previous step>,ARM_SUBSCRIPTION_ID,ARM_TENANT_ID.
Remote apply:
terraform apply
Running apply in HCP Terraform. Output will stream here. ...
Plan: 1 to add, 0 to change, 0 to destroy.

Do you want to perform these actions in workspace "myapp-hcp-demo"?
  Enter a value: yes

azurerm_user_assigned_identity.demo: Creating...
azurerm_user_assigned_identity.demo: Creation complete after 4s
Apply complete! Resources: 1 added, 0 changed, 0 destroyed.

Outputs:
principal_id = "9c1e…"

View the run in the browser and confirm that the plan and apply stages each used the run_phase:plan / run_phase:apply subject token. Delete tfc-apply the federated credential, then apply once more; you will see AADSTS700213 in the apply stage. This proves that the plan and apply identities are issued separately for each stage.

(Optional) switch to VCS-driven: In the workspace's Settings → Version Control, connect myapp-infra the repository, with working directory hcp-demo and trigger path hcp-demo/**. Open a PR, and an HCP Terraform speculative plan check will appear on it.
Cleanup:
terraform destroy
az group delete -n rg-tf-hcp-demo --yes --no-wait
# HCP Terraform: Workspace Settings → Destruction and Deletion → Delete workspace

Case 1: migrating from “one workflow per repo” to HCP Terraform

Problem: 60 repos each maintain their own Terraform workflow, so versions and security fixes cannot be standardized. Approach: The platform team uses the tfe provider to manage projects, workspaces (VCS-driven), variable sets (dynamic credentials), and team permissions; application teams write only Terraform code. terraform init -migrate-state Migrate state, and freeze changes during the migration. Limitations: The number of managed resources directly determines cost, so inventory them first (a large number of azurerm_role_assignment, DNS records significantly increase the count).

Case 2: runners accessing state and APIs over private endpoints

Problem: Key Vault and the AKS API expose only private endpoints, so HashiCorp-managed runners cannot reach them. Approach: Deploy the HCP Terraform Agent (container) in the hub VNet and change the workspace execution mode to Agent; the Agent only needs outbound access to HCP. Limitations: You are responsible for upgrading, scaling, and hardening the Agent hosts; the free tier limits the number of agents, so check the pricing page.

Case 3: separating plan and apply identities to meet least privilege

Problem: Audit requires that “read-only operations must not use write-permission identities.”Approach: In the variable set, set TFC_AZURE_PLAN_CLIENT_ID (a custom Reader + listSecrets role) and TFC_AZURE_APPLY_CLIENT_ID (Contributor); federated credentials separately trust run_phase:plan and run_phase:apply. Limitations: The apply stage refreshes some data again, so the write-permission identity still needs read permissions.

Common errors and fixes

Error: Apply not allowed for workspaces with a VCS connection

Cause: The workspace is connected to VCS, so the CLI can only run a speculative plan. Fix: Trigger runs through commits and merges. If a CLI apply is really needed, switch to a CLI-driven workspace (you lose automatic VCS triggering).

Error: Invalid credentials … Required token could not be found. Run the following command to generate a token for app.terraform.io: terraform login

Cause: No token locally, or CI has not set TF_TOKEN_app_terraform_io.

jq '.credentials | keys' ~/.terraform.d/credentials.tfrc.json   # Only check the hostnames; do not print the token

Fix:terraform login; in CI, use a team token and store it in Secrets.

Error: building account: … could not configure AzureCli Authorizer: … az: command not found (during a remote run)

Cause: The remote runner has no Azure CLI and no dynamic credentials configured, so azurerm falls back to CLI authentication. Your local az login identity is not carried over to the remote run.

Fix: In the workspace or variable set, set TFC_AZURE_PROVIDER_AUTH=true and TFC_AZURE_RUN_CLIENT_ID, and check that the variable category is environment variables rather than Terraform variables.

Error: Required variable not set: env (the remote run ignored the local terraform.tfvars?)

Cause: With a CLI-driven workspace, *.auto.tfvars and terraform.tfvars are uploaded with the configuration, but -var-file the file paths specified by TF_VAR_* and local environment variables are not used; or .terraformignore excludes tfvars.

Fix: Set it as a Terraform variable in the workspace, or rename the file to *.auto.tfvars; check .terraformignore.

Command-line exercises
1. Write the steps to migrate state from an existing azurerm backend to an HCP Terraform workspace.
terraform state pull > backup-$(date +%F).tfstate      # Back up
# Replace the backend "azurerm" block with cloud { organization = "yourorg" workspaces { name = "myapp-azure-prod" } }
terraform login
terraform init -migrate-state
terraform plan      # Should show No changes
2. What is needed so that CLI-driven runs in GitHub Actions can authenticate to HCP Terraform?
env:
  TF_TOKEN_app_terraform_io: ${{ secrets.TFC_TEAM_TOKEN }}
# Or the cli_config_credentials_token input of hashicorp/setup-terraform
Scenario analysis
A company has 800 managed resources and 12 engineers, and needs drift detection and policy. Compare “HCP Terraform” with “continuing to self-build GitHub Actions.”

HCP: exceeds Free's 500-resource limit, and drift detection (health assessments) requires at least Standard. At about $0.47/resource/month, the estimate is about $376/month (subject to quote). That gets you managed state, dynamic credentials, policy sets, health assessments, and team permissions, with almost no operations work. DIY: Actions minutes are cheap, but you must maintain all the workflows, identities, and backends from Modules 2, 4, and 5, and ensure auditing and consistency yourself. The decision depends on platform team staffing and compliance requirements; you can also evaluate other TACOS platforms' pricing models (per run or per concurrency).

Verified teaching video

▶
Getting into Terraform, Part 9: HCP Terraform — HashiCorp, an IBM Company
English · Official introductory series on HCP Terraform workspaces and remote runs
▶
Day 25/28 - HCP Terraform Explained - Terraform Cloud Tutorial — Tech Tutorials with Piyush
English · Hands-on demo (pricing and tiers verified as of 2026-11 in this lesson)
▶
Terraform Cloud - Managing Your Workspaces with Projects — Ned in the Cloud
English · Organizing projects and workspaces

Official docs

Video storyboard script (about 90 seconds)

This courseware cannot generate video or MP3 directly, so a storyboard and narration script are provided instead.

Shot 1 · 0–20s
Visual: an organization box containing projects and workspaces; each workspace has three small icons for state, variables, and run history.
Narration: an HCP Terraform workspace is one state, one set of variables, and one set of settings. It is not the same as the command-line workspace.
Shot 2 · 20–50s
Visual: on the left, git push triggers a webhook; on the right, a terminal runs terraform plan and uploads the configuration. The two lines converge on the remote runner.
Narration: VCS-driven runs are triggered by commits and CLI-driven runs by your command, but both execute remotely, with credentials and policies coming from the workspace.
Shot 3 · 50–75s
Visual: the run progress bar lights up in order: plan, run task, cost estimate, policy check, waiting for confirmation, apply.
Narration: a run goes through run tasks, cost estimation, and policy checks, and is finally confirmed for execution by someone with permission.
Shot 4 · 75–90s
Visual: price sign: Free for 500 resources; Essentials, Standard, and Premium billed per resource.
Narration: the legacy free plan ended in late March 2026. The free tier now allows up to 500 managed resources, and health assessments require Standard or higher.
Or score ≥ 70% on the Quiz

Module 4 · Policy as code: Terraform Policy / Sentinel / OPA

25:00 – 33:00 · Reviewers get tired; policies don't. Write “no public storage” and “must be tagged” as code, and block violations before apply
8 minTerraform Policy GA · Terraform 1.17conftest v0.71.1★★★★★
Learning objectives
  • Understand the three policy evaluation points: setup (before provider/module download), plan (before changes), and post-apply (can only report after the fact), and the difference between “policy checks the plan JSON” and “tflint/Trivy checks the source code.”
  • Write three kinds of policy: Terraform Policy (.policy.hcl,resource_policy + enforce), Sentinel (tfplan/v2), OPA Rego (conftest checks terraform show -json output).
  • Understand enforcement levels: Terraform Policy's advisory / mandatory_overridable / mandatory, Sentinel's advisory / soft-mandatory / hard-mandatory, and OPA (HCP)'s advisory / mandatory, and be able to choose one for your team.
Prerequisites: Plan JSON from Module 2; validation/check blocks and static scanning from Lesson 2. Importance:★★★★★

What: what policy as code is

Policy as code expresses an organization's compliance and security requirements as machine-executable rules, evaluates them automatically at fixed stages in CI or on the platform, and returns a “pass / warn / block” verdict. Unlike the in-module validation,precondition differ; policies are maintained by the platform/security team centrally, applying to all teams' configurations; code authors cannot bypass them within their own modules.

Three engines

Terraform PolicySentinelOPA (Rego)
LanguageHCL (policy,resource_policy,provider_policy,module_policy,input,locals)Sentinel DSLRego (general-purpose policy language)
StatusTerraform 1.17.0 (2026-10-21) GA; CLI plan/apply/query -policies; HCP Terraform policy setsBuilt into HCP Terraform / Enterprise; Sentinel CLI for local testingCNCF graduated project; native HCP support; for local/CI, use conftest or opa eval
inputReference attributes directly by resource type: attrs.,prior_attrs.,meta.tfplan/v2,tfconfig/v2,tfstate/v2,tfrun importplan JSON (resource_changes[]); in HCP it is input.plan
Enforcement leveladvisory / mandatory_overridable / mandatory (default: mandatory)advisory / soft-mandatory / hard-mandatoryHCP: advisory / mandatory; conftest: deny / warn
Cross-resource lookupsbuilt in core::getresources,core::getdatasourcemanual traversal and matchingwrite comprehensions over the plan JSON
Evaluation timingCan check provider/module sources and versions at the init stage (before download); after plan; values known only after apply are reported after applyAfter plan (policy check stage)After plan
Testingtfpolicy test (.policytest.hcl)sentinel testopa test / conftest verify

The comparison table is based on the “Compare policy frameworks” page on developer.hashicorp.com (2026-11). That page recommends Terraform Policy for Terraform workflows, and existing Sentinel/OPA policies must be rewritten in HCL to migrate. The page does not announce any deprecation of Sentinel or OPA.

Why: why code review and static scanning alone are not enough

  • Review fatigue: a 300-line plan is hard for people to notice every time public_network_access_enabled = true.
  • Static scanning cannot see computed values: tflint/Trivy checks the source code; variables, module outputs,for_each and expanded real values exist only in the plan. A policy check on the plan sees “what is about to happen.”
  • Centralized governance: the security team changes a policy once, it applies to all workspaces, and override auditing is recorded.

How: where this lesson's gates sit

  1. In PR and deploy workflows: terraform plan -policies=../policies/tfpolicy -out=tfplan (Terraform Policy, no experimental build required since 1.17).
  2. Same plan: terraform show -json tfplan > plan.json → conftest test plan.json -p ../policies/opa (OPA).
  3. If any check fails, the job fails: the PR cannot merge, and the apply job does not start.
  4. In an HCP Terraform workspace: put the same policies into a policy set, and the platform evaluates them at the post-plan stage.

Key structure of plan JSON (both OPA and Sentinel are based on it)

{
  "format_version": "1.2",
  "terraform_version": "1.17.2",
  "resource_changes": [
    {
      "address": "azurerm_storage_account.logs",
      "type": "azurerm_storage_account",
      "change": {
        "actions": ["create"],
        "before": null,
        "after": { "allow_nested_items_to_be_public": true, "min_tls_version": "TLS1_2", "tags": {"env":"prod"} },
        "after_unknown": { "id": true, "primary_blob_endpoint": true }
      }
    }
  ]
}

actions may be ["no-op"],["create"],["update"],["delete"],["delete","create"] (replace),["create","delete"] (create_before_destroy replace), or ["read"]. Policies must handle after_unknown: when a value is only known after apply,after does not contain the key.

When: how to choose

  • New project, Terraform-first: Terraform Policy. HCL has the lowest learning curve, can block non-compliant providers/modules before download, and works in both CLI and HCP.
  • Large existing Sentinel assets: keep using them and migrate gradually as needed.
  • One policy must cover multiple object types, such as Terraform, Kubernetes, and Dockerfile: OPA/Rego (conftest supports multiple formats), and shares skills with Gatekeeper.
  • In every case,static scanning (Trivy/Checkov) + plan policies are complementary.
Common misconceptions① “Writing the policy in a module's validation block is enough”—module authors can change the module, so policies must be independent of the code they constrain. ② “Checking after is enough”—for delete actions after the after value is null, and for unknown values the key does not exist, so policies must filter by actions and handle null. ③ “Mandatory policies can never be bypassed”—in HCP mandatory_overridable/soft-mandatory they can be overridden by someone with permission (overrides are logged). In the CLI, whoever can change the workflow can remove the gate, so the workflow directory must be protected by CODEOWNERS.

Architecture diagram: three evaluation paths for the same plan

terraform planCore graph buildprovider gRPC Terraform Policy (in-process)-policies=DIR · *.policy.hclsetup stage + plan stage + post-apply tfplan binary → show -jsonplan.json (resource_changes) HCP Terraform runPost-plan policy check stageSentinel · OPA · Terraform Policy policy sets conftestRego deny/warn Blockjob fails / run stops Pass / warnProceed to approval
Figure 4-1: Terraform Policy evaluates in-process inside Terraform; OPA and Sentinel read the plan's JSON or imported data; HCP evaluates everything at the post-plan stage

Flowchart: how enforcement levels determine the outcome

Policy failscondition = false advisoryWarn, continue mandatory_overridable(Sentinel: soft-mandatory) mandatory(Sentinel: hard-mandatory) Approved by someone with override permissionRecord override audit Proceed to apply Run terminates
Figure 4-2: three enforcement levels; in a DIY CI, “override” is usually implemented with an approval-gated environment or a policy exception list

Interactive evaluator: the same change goes to three engines

Adjust the properties of the storage account to be created, then click “Evaluate”. Each engine shows the input it sees, the rules it matches, and its final verdict (the enforcement levels differ, so the verdicts differ too).

Enforcement level of the tags rule:

Core commands

CommandPurposeNotes
terraform plan -policies=DIREvaluate Terraform Policy at plan time1.17 GA; apply,query also supported; check the argument form in terraform plan -help the official reference.
tfpolicy validate --policies=DIRValidate policy syntaxInstall the tfpolicy CLI from the official Install page
tfpolicy test --policies=DIR --tests=DIRRun .policytest.hcl TestInput variables are available TFPOLICY_INPUT_<name>
terraform show -json tfplanGenerate plan JSONContains plaintext sensitive values; protect it
conftest test plan.json -p DIRCheck the plan with Regodefault namespace main; --all-namespaces,-o github
conftest verify -p DIRRun Rego unit teststest_ Prefix rules
sentinel apply / sentinel testRun and test Sentinel locallyNeeds mock data (can be downloaded from an HCP run)

Terraform Policy: block public blobs, enforce minimum TLS, enforce tags

policy {
  required_providers {
    azurerm = {
      source = "hashicorp/azurerm"
    }
  }
}

resource_policy "azurerm_storage_account" "no_public_blob" {
  enforcement_level = "mandatory"
  enforce {
    condition     = attrs.allow_nested_items_to_be_public == false
    error_message = "Storage accounts must block public blob access (allow_nested_items_to_be_public = false)."
  }
}

resource_policy "azurerm_storage_account" "min_tls" {
  enforcement_level = "mandatory"
  enforce {
    condition     = attrs.min_tls_version == "TLS1_2"
    error_message = "Storage account minimum TLS version must be TLS1_2."
  }
}
policy {
  required_providers {
    azurerm = { source = "hashicorp/azurerm" }
  }
}

locals {
  required_tags = ["owner", "cost-center", "env"]
}

resource_policy "azurerm_resource_group" "required_tags" {
  enforcement_level = "mandatory_overridable"
  enforce {
    condition = attrs.tags != null && core::alltrue([
      for t in local.required_tags : core::contains(core::keys(attrs.tags), t)
    ])
    error_message = "Resource groups must have owner, cost-center, and env tags."
  }
}

Syntax notes (verified against developer.hashicorp.com/terraform/policy, 2026-11): File extension .policy.hcl; files with resource/provider policies must have a required_providers matching policy block; enforce Each block's condition is required,error_message,info_message optional; enforcement_level takes "advisory"/"mandatory_overridable"/"mandatory", default mandatory; filter Restricts which objects it applies to (e.g., filter = attrs.tags.env == "prod"); resource_policy is evaluated on create and update by default; can be adjusted with operations ; functions are invoked with core:: a namespace (official examples include core::length,core::semverconstraint,core::getresources). In the example above, core::alltrue/core::contains/core::keys the function is inferred from the note that “most Terraform built-in functions are available”; verify it first with tfpolicy validate .

cd ~/myapp-infra/azure
terraform plan -policies=../policies/tfpolicy -out=tfplan
…
Error: Policy violation: no_public_blob

  on ../policies/tfpolicy/storage.policy.hcl line 9, in resource_policy "azurerm_storage_account" "no_public_blob":
  resource azurerm_storage_account.logs

Storage accounts must block public blob access (allow_nested_items_to_be_public = false).

OPA / conftest: write the same rules in Rego

package main

import rego.v1

changes contains rc if {
  some rc in input.resource_changes
  some a in rc.change.actions
  a in {"create", "update"}
}

deny contains msg if {
  some rc in changes
  rc.type == "azurerm_storage_account"
  rc.change.after.allow_nested_items_to_be_public == true
  msg := sprintf("%s: block public blob access", [rc.address])
}

deny contains msg if {
  some rc in changes
  rc.type == "azurerm_storage_account"
  rc.change.after.min_tls_version != "TLS1_2"
  msg := sprintf("%s: min_tls_version must be TLS1_2, current %v", [rc.address, rc.change.after.min_tls_version])
}

# Only warn when deleting or replacing production resources; leave the decision to manual approval
warn contains msg if {
  some rc in input.resource_changes
  "delete" in rc.change.actions
  msg := sprintf("%s will be deleted (actions=%v)", [rc.address, rc.change.actions])
}
package main

import rego.v1

test_public_blob_denied if {
  count(deny) > 0 with input as {"resource_changes": [{
    "address": "azurerm_storage_account.x", "type": "azurerm_storage_account",
    "change": {"actions": ["create"], "after": {"allow_nested_items_to_be_public": true, "min_tls_version": "TLS1_2"}}
  }]}
}

test_private_ok if {
  count(deny) == 0 with input as {"resource_changes": [{
    "address": "azurerm_storage_account.x", "type": "azurerm_storage_account",
    "change": {"actions": ["create"], "after": {"allow_nested_items_to_be_public": false, "min_tls_version": "TLS1_2"}}
  }]}
}
# Install conftest (v0.71.1, 2026-10-06)
CV=0.71.1
curl -sSLo /tmp/conftest.tgz https://github.com/open-policy-agent/conftest/releases/download/v${CV}/conftest_${CV}_Linux_x86_64.tar.gz
tar -xzf /tmp/conftest.tgz -C /tmp conftest && sudo mv /tmp/conftest /usr/local/bin/
conftest --version
conftest verify -p ../policies/opa
terraform show -json tfplan > plan.json
conftest test plan.json -p ../policies/opa
2 tests, 2 passed, 0 warnings, 0 failures, 0 exceptions
FAIL - plan.json - main - azurerm_storage_account.logs: block public blob access

2 tests, 1 passed, 0 warnings, 1 failure, 0 exceptions

Check the conftest releases page for the exact release package file name. import rego.v1 Still accepted in OPA 1.x; including it lets the policy also parse with v1 syntax on older OPA versions. In CI you can add -o github so failures appear as GitHub annotations.

Sentinel: equivalent policy in HCP Terraform

import "tfplan/v2" as tfplan

storage_accounts = filter tfplan.resource_changes as _, rc {
  rc.type is "azurerm_storage_account" and
  (rc.change.actions contains "create" or rc.change.actions contains "update")
}

deny_public = rule {
  all storage_accounts as _, sa {
    sa.change.after.allow_nested_items_to_be_public is false
  }
}

main = rule { deny_public }
policy "deny-public-storage" {
  source            = "./deny-public-storage.sentinel"
  enforcement_level = "hard-mandatory"
}

OPA in HCP Terraform: policy set configuration

policy "deny_public_storage" {
  query             = "data.terraform.policies.public_storage.deny"
  enforcement_level = "mandatory"
}

HCP Terraform's OPA input puts the plan under input.plan (whereas conftest takes the plan JSON directly as its input). When migrating the same Rego, adjust the path and package; see the “Defining OPA policies” documentation for details.

Lab 4: add a dual-engine policy gate to the pipeline (about 8 minutes)

Write the policy files: copy the storage.policy.hcl,tags.policy.hcl,storage.rego,storage_test.rego into the repo's policies/ directory, then run locally:
cd ~/myapp-infra
conftest verify -p policies/opa
cd azure && terraform plan -policies=../policies/tfpolicy -out=tfplan && terraform show -json tfplan > plan.json
conftest test plan.json -p ../policies/opa
2 tests, 2 passed, 0 warnings, 0 failures, 0 exceptions
...
No changes. Your infrastructure matches the configuration.
0 tests, 0 passed, 0 warnings, 0 failures, 0 exceptions
Add to the workflow: in the terraform-pr.yml and terraform-deploy.yml plan steps, add -policies=../policies/tfpolicy, and after show -json add:
      - name: Install conftest
        working-directory: ${{ runner.temp }}
        run: |
          CV=0.71.1
          curl -sSLo conftest.tgz "https://github.com/open-policy-agent/conftest/releases/download/v${CV}/conftest_${CV}_Linux_x86_64.tar.gz"
          tar -xzf conftest.tgz conftest && sudo mv conftest /usr/local/bin/
      - name: OPA policy check
        run: |
          conftest verify -p ../policies/opa
          conftest test plan.json -p ../policies/opa -o github

In production, verify the SHA256 of the downloaded file (the releases page provides checksums), or pre-install conftest into your self-hosted runner image.

Submit a violating change: create a branch and add to azure/main.tf :
resource "random_string" "sa" {
  length  = 6
  special = false
  upper   = false
}

resource "azurerm_storage_account" "logs" {
  name                            = "stmyapplogs${random_string.sa.result}"
  resource_group_name             = azurerm_resource_group.lab.name
  location                        = azurerm_resource_group.lab.location
  account_tier                    = "Standard"
  account_replication_type        = "LRS"
  min_tls_version                 = "TLS1_2"
  allow_nested_items_to_be_public = true      # Violation
  tags                            = local.tags
}

You also need to make the change in required_providers by adding random = { source = "hashicorp/random", version = "~> 3.7" } and running terraform init -upgrade to update the lock file (for the random version, follow the registry). After the PR is opened, the PR check should fail, and the logs should show both the Terraform Policy and conftest denial messages.

Fix and verify: change it to allow_nested_items_to_be_public = false, push, and the check turns green. After merge and approval, a storage account is created (LRS, almost no cost).
Cleanup: the integrated lab keeps using this storage account; if you do not need it, delete logs.tf it via a PR → apply cycle (which is itself practice).

Case 1: staged enforcement to avoid blanket blocking

Problem: The security team rolled out 40 mandatory policies at once; the next day, 30% of workspaces could not deploy, and everything had to be rolled back. Approach: New policies first run as advisory for two weeks to collect alerts and notify teams; then they are upgraded to mandatory_overridable (the security team can override them and record the reason); once stable, they change to mandatory. Limitations: Override records must be reviewed regularly, or “overridable” becomes “always overridden.”

Case 2: blocking unapproved providers and modules

Problem: Someone introduced a community provider of unknown origin, and a module references GitHub's main branch directly. Approach: Terraform Policy's provider_policy/module_policy checks, at the init stage (before download), meta.source and meta.version, allowing only private registry sources and >= 2.0.0 versions (the official example uses core::semverconstraint). Limitations: Only Terraform Policy can perform this kind of check before download; OPA and Sentinel can only catch it after plan.

Case 3: unifying multiple formats on OPA

Problem: One team maintains Terraform, Kubernetes manifests, and Dockerfiles, and wants rules like “no latest images” written only once. Approach: conftest runs against plan JSON, YAML, and Dockerfiles, sharing a Rego helper library; inside Kubernetes clusters, Gatekeeper reuses some of the same rules. Limitations: Rego has a steep learning curve and needs accompanying unit tests and code review.

Common errors and fixes

flag provided but not defined: -policies

Cause: The Terraform version is below 1.17 (before 1.17, this argument existed only in experimental builds and required -allow-experimental-features), or setup-terraform in CI installed an old version.

terraform version

Fix: Upgrade to 1.17.x and explicitly set terraform_version in the workflow.

rego_parse_error: `if` keyword is required before rule body / var cannot be used for rule name

Cause: The old syntax (Rego v0: deny[msg] { … }) is no longer accepted by default in OPA 1.x or newer conftest.

Fix: Switch to v1 syntax: deny contains msg if { … }; or temporarily use conftest's v0 compatibility flag (the authoritative reference is conftest test --help ).

conftest passed, but the violating resource was actually created

Cause:① the rule's package is not main and there is no --namespace/--all-namespaces; ② the value is in after_unknown , and after does not contain the key, so the comparison is undefined; ③ only create was checked, not update.

jq '.resource_changes[] | select(.type=="azurerm_storage_account") | {address, actions: .change.actions, after: .change.after.allow_nested_items_to_be_public, unknown: .change.after_unknown.allow_nested_items_to_be_public}' plan.json

Fix: Adopt a “deny by default” approach for unknown values (not rc.change.after.x == false); write both positive and negative unit tests for each rule.

Sentinel: Error: import "tfplan/v2" is not available

Cause: Running locally sentinel apply without mock data; or the policy set's VCS path is set incorrectly.

Fix: Download the Sentinel mocks from the HCP run page, and in sentinel.hcl use mock "tfplan/v2" { module { source = "mock-tfplan-v2.sentinel" } } to reference them (the Sentinel documentation is authoritative for syntax).

Command-line exercises
1. List the addresses of all resources in the plan that will be deleted or replaced.
terraform show -json tfplan | jq -r '.resource_changes[] | select(.change.actions | index("delete")) | "\(.address)\t\(.change.actions | join(","))"'
2. Run the policies for all namespaces with conftest and output them in GitHub annotation format.
conftest test plan.json -p policies/opa --all-namespaces -o github
Scenario analysis
The security team requires that “only the canadacentral and canadaeast regions may be used in the production subscription, and no resource may be deleted unless the change ticket number is in the PR.” Which mechanism implements each requirement?

Region restriction: Terraform Policy resource_policy (or OPA) checks attrs.location is in the allowlist, mandatory; also use Azure Policy “Allowed locations” as a cloud-side backstop (to block manual creation in the portal). Delete control: OPA warn/Terraform Policy's operations identifies delete actions, set to mandatory_overridable. In CI, override works by reading the change ticket number from the PR body (passed to the policy as input through a workflow input), or by routing plans that include deletes to an environment that requires the change-approval group. Explain that “policies govern Terraform paths; cloud-native policies govern all paths.”

Verified teaching video

▶
Open Policy Agent and Terraform - Examining a Terraform Execution Plan with Rego — Ned in the Cloud
English · Checking plan JSON with Rego, corresponding to the conftest part of this module (note the Rego v1 syntax changes)
▶
Using OPA with Terraform - Rego Basics — Ned in the Cloud
English · Rego basics
▶
Terraform Cloud Learn Lab: Validate Infrastructure, Detect Drift & Enforce OPA Policies — HashiCorp, an IBM Company
English · OPA policies and drift detection in HCP (also applies to Module 5)

Terraform Policy (tfpolicy) is a new feature that became GA in 2026-10; no verified dedicated video was found, so follow the official docs and the storyboard below.

Official docs

Video storyboard script (about 100 seconds)

This courseware cannot generate video or MP3 directly, so a storyboard and narration script are provided instead.

Shot 1 · 0–20s
Visual: a reviewer yawns at a 300-line plan; one line, public = true, flashes past.
Narration: people get tired; policies don't. Write organizational rules as code and check them automatically before apply.
Shot 2 · 20–50s
Visual: the same plan splits into three beams, each entering one of three checkpoints: Terraform Policy, Sentinel, and OPA.
Narration: Terraform Policy uses HCL and evaluates inside the Terraform process; Sentinel and OPA read the plan data.
Shot 3 · 50–80s
Visual: three traffic lights. advisory shows a yellow light and lets the change through; an overridable enforcement level shows a yellow light and waits for a signature; mandatory shows a red light and blocks.
Narration: the enforcement level determines the consequence of failure: warn, override, or hard block.
Shot 4 · 80–100s
Visual: the provider download arrow is stopped midway by a gate written in HCL.
Narration: Terraform Policy can also check provider and module sources and versions before download, which the other two engines cannot do.
Or score ≥ 70% on the Quiz

Module 5 · Drift detection and continuous compliance

33:00 – 40:00 · Terraform looks at the world only when it runs; without regular checks, code and reality quietly drift apart
7 minplan -refresh-only · resource_driftHCP health assessments: Standard / Premium★★★★
Learning objectives
  • Distinguish “drift” (real resources diverging from state) from “unapplied changes” (code diverging from state), and know plan and plan -refresh-only what each one can see.
  • Use a scheduled task + -detailed-exitcode / the plan JSON's resource_drift to build drift detection and automatically open issues.
  • Understand HCP Terraform health assessments (drift detection + continuous validation: check blocks and pre/post conditions), along with their prerequisites, and the four ways to handle drift: roll back, adopt, ignore, or import.
Prerequisites: Lesson 1 on refresh and state; Lesson 2 check blocks and lifecycle. Importance:★★★★

What: what drift is

Drift refers to real infrastructure attributes that no longer match the values recorded in the Terraform state. Each time Terraform plan runs, it first refresh: for each resource in state, calls the provider's ReadResource (gRPC) → cloud API GET, and compares the result with state. Differences show in the “Note: Objects have changed outside of Terraform” section at the top of the plan output, and in the plan JSON's resource_drift array.

CommandWhat is comparedTypical use
terraform planCode vs (refreshed) real state: both drift and unapplied code changes appearPre-deployment review
terraform plan -refresh-onlyState vs real resources: only checks drift, ignoring codeDrift detection; after confirmation, use apply -refresh-only to accept into state
terraform plan -refresh=falseCode vs state, no cloud API accessFast preview of large stacks (misses drift)

Common sources of drift

  • Manual changes in the portal or CLI (break-glass fixes, debugging).
  • Other automation: Azure Policy's modify/deployIfNotExists effect (e.g., auto-adding tags, enabling diagnostic settings), AWS Config remediation, and autoscaling that changes replica counts.
  • Platform-side default changes, or resources reclaimed by the platform (certificate renewal, SKU retirement).
  • A resource is deleted (it disappears from state after refresh, and plan proposes recreating it).
  • After a provider upgrade, the way attributes are normalized changes (shows up as “phantom drift”, common with JSON strings and casing).

Why: why continuous detection is required

  • Drift gets reverted by the next unrelated apply : emergency manual fixes are quietly undone (Module 1, Case 2).
  • Security drift (for example, someone temporarily opening NSG port 22) persists until it is found.
  • Audits require proof that “production matches the approved code.”

How: two implementations

A. DIY: scheduled task + plan

  1. GitHub Actions schedule (cron, UTC) runs once a day with a read-only plan identity.
  2. terraform plan -refresh-only -out=drift.tfplan, then uses terraform show -json drift.tfplan | jq '.resource_drift | length' to count the drifted resources, which is clearer than relying on the exit code alone.
  3. It also runs a regular plan -detailed-exitcode: exit code 2 means “code and reality differ” (either drift, or changes merged but not applied).
  4. When differences exist, automatically open (or update) an issue labeled drift issue and mention the on-call engineer or CODEOWNERS.

B. HCP Terraform health assessments

  • Includes drift detection and continuous validation (re-evaluates check blocks, pre/post conditions), available from Standard tier and above.
  • Prerequisites: Remote or Agent execution mode; the workspace has been successfully applied at least once; the most recent run must have succeeded (failed, canceled, or discarded runs pause assessments); drift detection needs Terraform 0.15.4+, and continuous validation needs 1.3.0+.
  • Assessments run periodically (the docs example is every 24 hours; the next assessment is counted from the most recent apply or assessment), and can also be triggered manually in the UI. Organization owners can force them on for all workspaces.
  • Assessments are read-only and do not modify infrastructure; results appear on the workspace's Health page and can send notifications.

Four ways to handle drift

OptionActionWhen to use
Roll back (restore the code definition)Apply through the normal PR/deploy process (or rerun the deploy workflow)Unapproved manual changes, security-related drift
Adopt (code follows reality)Change the code to match reality and open a PR; the plan should show No changesA break-glass fix was truly necessary
Ignorelifecycle { ignore_changes = [tags["CreatedBy"], template[0].max_replicas] }Attribute is legitimately managed by another system (autoscaling, tags added by Azure Policy)
Accept into stateterraform apply -refresh-onlyOnly updates the state record (e.g., a resource was deleted and must be removed from state before deciding); does not change code

A resource created in the portal that is not in code is not “drift” (Terraform cannot see it); use import blocks to bring it under management (Lesson 2), or use Azure Resource Graph / AWS Config to inventory “resources not managed by Terraform.”

When: frequency and scope

  • Production: at least once a day; security-sensitive stacks (networking, identity) can run every few hours.
  • Refresh on large stacks makes many cloud API calls, so watch rate limits; stagger runs (cron minutes that avoid the top of the hour), batch by stack, and use 1.17's -minimal-refresh for regular plans to reduce API calls (but it only refreshes resources with planned changes,so it is not suitable for drift detection).
  • Prevention beats detection: tighten human write permissions, resource locks (CanNotDelete), Azure Policy deny, and activity log alerts.
Common misconceptions① “The refresh-only exit code always reflects drift”—behavior has varied across versions and edge cases, so the plan JSON's resource_drift is the more reliable indicator. ② “ignore_changes solves all drift”—it makes Terraform completely blind to that attribute, including when you later want to change it through code. ③ “Drift detection needs apply permissions”—detection only needs read permissions; fixes go through the normal deploy process. ④ “Put drift detection in the same concurrency group as deployments”—a GitHub concurrency group keeps only one waiting run, so a scheduled job can replace a deployment run that is waiting.

Architecture diagram: three-way comparison of code, state, and real resources

Code (main branch)max_replicas = 2tags.env = "prod" State (tfstate blob)max_replicas = 2serial 42 Real resources (ARM)max_replicas = 10 (changed in the portal)tags.CreatedBy (Azure Policy) ReadResource plan -refresh-onlystate ↔ realresource_drift: 1= drift plan (default)code ↔ refreshed real~ max_replicas 10 -> 2= apply will “roll back” drift Not visibleResources created in the portal that are not in code→ import block / Resource Graph inventory
Figure 5-1: refresh-only compares only state and real resources; the default plan mixes drift and code changes together

Flowchart: automated drift detection and handling

cron 06:17 UTCPlan identity (read-only) plan -refresh-only-lock=false -out jq resource_driftCount N N = 0 → end N > 0 → issuelabel drift · @oncall Manual decisionRoll back: rerun deploymentAdopt: code change PRIgnore: ignore_changesAccept: apply -refresh-only
Figure 5-2: detection is read-only and automatic; remediation must go through people and the normal change process

Drift simulator: create drift → detect → remediate

First click one or more “Create drift” buttons, then run detection, and finally choose a remediation option. The table shows the values for code, state, and real resources; the log shows real Terraform output.

Create drift:
Detect:
Remediate:

Core commands

CommandPurposeNotes
terraform plan -refresh-onlyShow drift onlyCan add -out Save
terraform apply -refresh-onlyWrite the detected real values into stateDoes not modify any cloud resources; review before running
terraform plan -detailed-exitcode0 no differences / 1 error / 2 differencesIn scripts, you must set +e capture
terraform show -json PLAN | jq '.resource_drift'Get the drift list in structured formEach item contains address and before/after
-lock=falseDo not acquire the state lock during read-only detectionAvoids blocking deployments; do not use for apply
gh issue create / commentReport drift--label drift
cd ~/myapp-infra/azure
terraform plan -refresh-only -lock=false -out=drift.tfplan
terraform show -json drift.tfplan | jq '[.resource_drift[]? | {address, changed: [.change.before as $b | .change.after | to_entries[] | select(.value != $b[.key]) | .key]}]'
Note: Objects have changed outside of Terraform

Terraform detected the following changes made outside of Terraform since the
last "terraform apply" which may have affected this plan:

  # azurerm_container_app.myapp has changed
  ~ resource "azurerm_container_app" "myapp" {
        id   = "/subscriptions/…/containerApps/ca-myapp-prod"
      ~ template {
          ~ max_replicas = 2 -> 10
        }
    }
…
[
  { "address": "azurerm_container_app.myapp", "changed": ["template"] }
]

How to verify: When the drift count is 0, output []. Common errors: Without -out you cannot show -json; in jq, use []? to stay compatible when fields are missing. Production use: Write the JSON result into the issue body, so reviewers can see at a glance which attribute of which resource changed.

Drift detection workflow

name: terraform-drift
on:
  schedule:
    - cron: "17 6 * * *"        # Daily at 06:17 UTC, avoiding the top-of-hour peak
  workflow_dispatch:
permissions:
  contents: read
concurrency:
  group: tf-drift-azure-prod    # Separate from deployments: avoids replacing a deployment run that is waiting for approval
  cancel-in-progress: true
env:
  TF_IN_AUTOMATION: "true"
  TF_INPUT: "false"
  ARM_USE_OIDC: "true"
  ARM_CLIENT_ID: ${{ vars.AZURE_PLAN_CLIENT_ID }}
  ARM_TENANT_ID: ${{ vars.AZURE_TENANT_ID }}
  ARM_SUBSCRIPTION_ID: ${{ vars.AZURE_SUBSCRIPTION_ID }}
jobs:
  drift:
    runs-on: ubuntu-24.04
    permissions: { contents: read, id-token: write, issues: write }
    defaults: { run: { working-directory: azure } }
    steps:
      - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
      - uses: hashicorp/setup-terraform@dfe3c3f87815947d99a8997f908cb6525fc44e9e # v4.0.1
        with: { terraform_version: "1.17.2", terraform_wrapper: false }
      - run: terraform init -lockfile=readonly
      - id: drift
        run: |
          terraform plan -refresh-only -lock=false -no-color -out=drift.tfplan > drift.txt
          N=$(terraform show -json drift.tfplan | jq '[.resource_drift[]?] | length')
          set +e
          terraform plan -lock=false -detailed-exitcode -no-color > full.txt; EC=$?
          set -e
          if [ "$EC" -eq 1 ]; then cat full.txt; exit 1; fi
          echo "drift=$N" >> "$GITHUB_OUTPUT"; echo "pending=$EC" >> "$GITHUB_OUTPUT"
          echo "drift=$N pending_exitcode=$EC"
      - name: Report drift
        if: steps.drift.outputs.drift != '0' || steps.drift.outputs.pending == '2'
        env: { GH_TOKEN: "${{ github.token }}" }
        run: |
          {
            echo "Drifted resources: ${{ steps.drift.outputs.drift }}; code and reality differ (exit 2): ${{ steps.drift.outputs.pending == '2' }}"
            echo "Run: ${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}/actions/runs/${GITHUB_RUN_ID}"
            echo '```'; head -c 50000 drift.txt; echo '```'
          } > body.md
          gh label create drift --color B60205 --description "Terraform drift" --force
          NUM=$(gh issue list --label drift --state open --json number -q '.[0].number')
          if [ -n "$NUM" ]; then gh issue comment "$NUM" --body-file body.md
          else gh issue create --title "Terraform drift detected: azure (prod)" --label drift --body-file body.md; fi

Scheduled jobs run on the default branch, and OIDC sub the subject is repo:…:ref:refs/heads/main, which exactly matches the Module 2 plan identity's gh-main federated credential. In public repos, GitHub automatically disables scheduled workflows after 60 days of no activity.

Ignore attributes legitimately managed by other systems

resource "azurerm_container_app" "myapp" {
  # …
  lifecycle {
    ignore_changes = [
      tags["CreatedBy"],            # Tag auto-added by Azure Policy modify
    ]
  }
}

Lab 5: create drift and let the pipeline detect it (about 7 min)

Commit the drift detection workflow: copy the terraform-drift.yml from the Commands page and merge it to main via a PR.
Create drift in the portal/CLI:
az containerapp update -g rg-tf-lab -n ca-myapp-prod --max-replicas 10 -o none
az containerapp show -g rg-tf-lab -n ca-myapp-prod --query properties.template.scale.maxReplicas
10
Trigger detection manually:
gh workflow run terraform-drift.yml
sleep 5; gh run watch $(gh run list --workflow terraform-drift.yml --limit 1 --json databaseId -q '.[0].databaseId')
gh issue list --label drift
drift=1 pending_exitcode=2
…
#7  Terraform drift detected: azure (prod)  drift  about 1 minute ago
Remediate (roll back): the code still says 3 (changed in Module 2); rerun the deploy workflow: gh workflow run terraform-deploy.yml, and after approval the plan shows max_replicas 10 -> 3, then after apply, trigger drift detection again and confirm drift=0, then close the issue: gh issue close 7 -c "Reverted by run …".
(Optional) Adopt: if 10 is reasonable, change the code to 10 and open a PR; the PR plan should show No changes, and after merge the drift disappears. This is the correct way to adopt.

Case 1: Azure Policy auto-tagging causes “permanent drift”

Problem: The subscription enabled “Inherit a tag from the resource group if missing” (modify effect). Every night, drift detection reports tag changes on dozens of resources; the alerts are ignored, and real security drift gets buried. Approach: Declare these tags explicitly in Terraform (with the same values Policy inherits) to remove the difference at the source; for the few tags that cannot be predicted, use ignore_changes = [tags["X"]]. Limitations: Do not blanket-ignore ignore_changes = [tags], or tag governance (Module 6) stops working.

Case 2: a security group temporarily opened on port 22

Problem: While troubleshooting, an engineer added a 0.0.0.0/0:22 rule to an NSG and forgot to remove it. Approach: Drift detection runs every 4 hours; for drift on security resources such as NSGs and firewalls, the issue is automatically assigned to the security team with high priority. Also configure an activity log alert for “NSG modified by a non-CI identity.”Limitations: There is still risk within the 4-hour window; for critical resources, use Azure Policy deny or JIT access instead of manual rules.

Case 3: health assessments replace a DIY detection setup

Problem: 300 workspaces; the DIY drift workflow is expensive to maintain. Approach: Upgrade to HCP Terraform Standard, enforce health assessments at the organization level, and send drift notifications to Slack; combine with check blocks for continuous validation (for example, checking daily that the app /healthz returns 200 and how many days remain on its certificate). Limitations: Health assessments require the most recent run to succeed; workspaces that fail for a long time stop being assessed and need separate monitoring.

Common errors and fixes

Error: Saved plan is stale (deployment fails after drift detection)

Cause: Someone ran terraform apply -refresh-only (which changed the state serial) while the deployment was waiting for approval. Drift detection itself only runs plan, so it does not cause staleness.

Fix: Rerun the deployment; require apply -refresh-only to also be run through the pipeline.

Every detection reports JSON attribute drift (policy, tag order, casing)

Cause: The cloud API returns normalized JSON (key order, whitespace, casing), which differs from the configuration's string literal; the provider's diff suppression does not cover it.

terraform show -json drift.tfplan | jq '.resource_drift[] | {address, before: .change.before.policy, after: .change.after.policy}'

Fix: Use jsonencode() to generate JSON instead of hand-written strings; upgrade the provider; if needed, add ignore_changes for that attribute and note it in the issue.

Scheduled workflow does not run on time / does not run at all

Cause: cron uses UTC; runs at peak times (top of the hour) may be delayed or dropped; public repos are automatically disabled after 60 days of no activity; the workflow file is not on the default branch.

Fix: Stagger the minute (e.g., minute 17) gh workflow enable terraform-drift.yml; confirm the file is on main.

Error: Resource not found … 404 (a deleted resource makes the plan fail instead of prompting a recreate)

Cause: Most providers, on a 404 during refresh, remove the resource from state and plan to recreate it. But for child resources that depend on a parent resource ID, or data sources that reference a deleted object, the plan fails outright.

Fix: Confirm whether the deletion was expected. If it was, use terraform state rm or a removed block; if not, apply normally to recreate it and investigate the source of the deletion (activity log).

Command-line exercises
1. Write only the detected real values into state, without modifying any resources (review first).
terraform plan -refresh-only -out=refresh.tfplan
terraform show refresh.tfplan       # Review
terraform apply refresh.tfplan
2. In a script, distinguish between “no differences / differences / error.”
set +e; terraform plan -detailed-exitcode -lock=false >/dev/null; ec=$?; set -e
case $ec in 0) echo clean;; 2) echo diff;; *) echo error; exit 1;; esac
Scenario analysis
Drift detection found that a production Container App's CPU was changed from 0.25 to 1, and also found a storage account that does not exist in code. How do you handle both?

The CPU change is drift: first check the activity log to confirm who made it and why (an emergency fix?). If it is justified, adopt it (change the code via PR); otherwise roll back (rerun the deployment). The storage account that is not in code is not Terraform drift (Terraform cannot see it) and needs inventory: after confirming ownership, use import a block to bring it under the appropriate stack, or delete it through the standard process; and tighten access with Azure Policy and permissions to prevent it from being created in the portal again.

Verified teaching video

▶
Terraform Cloud Learn Lab: Validate Infrastructure, Detect Drift & Enforce OPA Policies — HashiCorp, an IBM Company
English · Demo of drift detection and continuous validation in health assessments (the video uses the older product name Terraform Cloud)

Official docs

Video storyboard (about 80 seconds)

This courseware cannot generate video/MP3 directly, so the storyboard and narration script are provided instead.

Shot 1 · 0–20s
Scene: three columns for code, state and real resources. Late at night someone changes the number 2 to 10 in the portal, and the real-resources column turns red.
Narration: Terraform only looks at the world when it runs. One change made in the portal quietly separates reality from the code.
Shot 2 · 20–45s
Scene: the clock reaches 6:17, the pipeline runs refresh-only, and a “1 resource drift” item pops up.
Narration: a scheduled daily refresh-only plan counts drift using resource drift in the plan JSON.
Shot 3 · 45–65s
Scene: a GitHub issue appears automatically, tagged drift, @ on-call.
Narration: when drift is found, an issue is opened automatically and a person decides how to handle it.
Shot 4 · 65–80s
Scene: four buttons: Roll back, Adopt, Ignore, Accept into state.
Narration: roll back by re-running the deployment, adopt by changing the code, use Ignore with care; every disposition goes through the normal process.
or score ≥ 70% on the Quiz

Module 6 · Cost estimation and tag governance

40:00 – 47:00 · See “how much this change costs per month” in the PR, and make sure every cent traces back to a team and a cost center.
7 minInfracost v0.10.49 · Infracost 2.0 CLIaws default_tags · tags_all★★★★
Learning objectives
  • Use Infracost to generate a cost-diff comment in a PR. Understand how it works (parse Terraform → match cloud vendor prices → usage assumptions) and its limits (usage-billed services).
  • Understand HCP Terraform's built-in cost estimation, and use cost data in policies (Sentinel tfrun.cost_estimate).
  • Set up tag governance: the AWS provider default_tags and tags_all Azure locals merging, tag inheritance, enforcing required tags via policy, and a cloud-native policy backstop.
Prerequisites: Module 4 policies; resources from Lessons 3/4. Importance:★★★★ (the starting point for FinOps)

What: IaC cost estimation

Cost estimation tools parse Terraform code or plan JSON to get “which resources will exist and what sizes”, then look up public cloud vendor prices (Infracost maintains a pricing API) and calculate the monthly cost and the difference this change makes. It does not connect to your cloud account, so it cannot know actual usage. Usage-based parts (traffic, request counts, Container Apps vCPU-seconds, Log Analytics ingestion) need a usage file to supply assumptions; otherwise they show as “depends on usage”.

Tool status (verified 2026-11)

ToolStatusUsage
Infracost v0.10.x (classic CLI)Still released (v0.10.49, 2026-11-10); since v0.10.45 it shows a notice about migrating to v2infracost breakdown / diff / comment github; requires a free API key (infracost auth login or INFRACOST_API_KEY)
Infracost 2.0 (new CLI, repo infracost/cli)The codebase moved to a separate repo; commands are mainly infracost scan,infracost inspect,infracost setup and similarFor CI authentication, use INFRACOST_CLI_AUTHENTICATION_TOKEN; for command details, see its README
HCP Terraform cost estimationEnabled in workspace settings; supports some resource types on AWS/Azure/GCPa “Cost estimation” stage in the run; Sentinel can read it tfrun.cost_estimate
Cloud vendor calculators / budget alertsAzure Pricing Calculator, AWS Pricing Calculator; Azure Cost Management budgets, AWS BudgetsBeyond estimation,after-the-fact control; must be configured together

Why: why look at cost at the PR stage

  • Changing the size from Standard_D2s_v5 to Standard_E16s_v5 In code it is just a string; on the bill it can be a tenfold difference. Reviewers only ask questions when they see “+$1,240/month” in the PR.
  • Cost is an architectural property: the earlier you catch it, the cheaper it is to change.

Tag governance

Tags (Azure tags / AWS tags) are the foundation for cost allocation (showback/chargeback), owner lookup and automation (shutdown schedules, backup policies). Governance has three layers:

  1. Default injection: the AWS provider's default_tags block merges tags automatically into all resources that support tags; the result goes in the read-only attribute tags_all (resource-level tags tags with the same key override defaults). The azurerm provider has no equivalent provider-level default tags, so the usual approach is locals locals { tags = {...} } + merge(local.tags, {...}), or enforce it in an internal module through a tags variable.
  2. Policy enforcement: Terraform Policy / OPA checks required keys at the plan stage (AWS checks tags_all, since default tags appear only there).
  3. Cloud backstop: Azure Policy “Require a tag on resources” (deny) or “Inherit a tag from the resource group” (modify); AWS Organizations Tag Policies + SCP. The backstop covers paths outside Terraform, such as the portal and CLI, but the modify effect creates drift (Module 5, Case 1).
AWSAzure
Provider default tagsdefault_tags → tags_allNone; locals + merge / module convention
Key caseCase-sensitiveKeys are case-insensitive (values are case-sensitive)
Cloud enforcementTag Policies (canonical values) + SCP (deny creation of untagged resources, per service support)Azure Policy deny / modify / append
Cost allocationRequires activating cost allocation tags in BillingCost Management groups directly by tag; tag inheritance setting

When: gate strength

  • Cost difference: first as an informational comment; above a threshold (for example +$500/month per change) require FinOps approval (route apply to an environment with approval, or use Sentinel soft-mandatory in HCP).
  • Required tags: new projects go straight to mandatory; existing environments start as advisory and are upgraded after remediation.
Common misconceptions① “Infracost shows $0, so it is free”: this may be because the resource is usage-based and no usage file was given, or the resource type is unsupported (listed under “not supported”). ② “AWS uses default_tags, so checking tags is enough”: default tags only appear in tags_all . ③ “Azure Policy modify adds tags automatically, so Terraform does not need to manage them”: this causes persistent drift. Write the tags in code and use cloud policy only as a backstop.

Architecture diagram: cost and tag checks in a PR

PR codebase: mainhead: feature Infracostbreakdown(base) → baseline.jsondiff(head, compare-to baseline)+ infracost-usage.yml usage assumptions plan JSON → tag policyAWS: tags_all = default_tags ∪ tagsAzure: merge(local.tags, …)Required keys: owner · cost-center · env Price APIPublic prices (region/SKU)Does not read your bill PR comment+$38.40/monthTag check ✓/✗
Figure 6-1: cost estimates are based on code and public prices; tag checks are based on plan JSON; both give results before merge

Flowchart: AWS default_tags merge rules

provider default_tagsapp = myappenv = prodowner = platform-teamcost-center = cc-1001 Resource tagsowner = data-team (overrides)Name = myapp-alb tags_all (read-only, computed)app = myapp · env = prodowner = data-teamcost-center = cc-1001Name = myapp-alb← policy should check here
Figure 6-2: a resource-level key with the same name takes precedence; the policy checks tags_all, otherwise it falsely reports missing default tags

Interactive calculator: tag merging + cost difference

On the left, adjust the tag sources and observe tags_all the policy conclusion; on the right, adjust the size and observe how the cost-diff comment changes. Prices are illustrative values (to explain the mechanism; they do not represent actual prices in any region).

Tags
Cost (illustrative prices)
VM size:
Instance count: 2
Monthly egress traffic (usage file): 0 GB

Core commands

CommandPurposeNotes
infracost auth loginGet a free API key (v0.10)Used in CI INFRACOST_API_KEY
infracost breakdown --path DIR|plan.jsonFull cost breakdown--format json --out-file,--usage-file
infracost diff --path DIR --compare-to base.jsondifference from the baselineMost used in PRs
infracost comment githubComment the result on the PR--behavior update Keep only one comment
infracost generate configGenerate for a monorepo infracost.ymlmulti-project
infracost scan / inspectScan and view with the Infracost 2.0 CLISee the infracost/cli README

Try locally (classic CLI)

curl -fsSL https://raw.githubusercontent.com/infracost/infracost/master/scripts/install.sh | sh
infracost --version
infracost auth login
cd ~/myapp-infra/azure
infracost breakdown --path . --usage-file infracost-usage.yml
version: 0.1
resource_usage:
  azurerm_log_analytics_workspace.lab:
    monthly_data_ingestion_gb: 5
  azurerm_storage_account.logs:
    storage_gb: 20
    monthly_write_operations: 100000
    monthly_read_operations: 500000
Project: yourname/myapp-infra/azure

 Name                                            Monthly Qty  Unit        Monthly Cost

 azurerm_log_analytics_workspace.lab
 └─ Log data ingestion                                     5  GB               $13.80

 azurerm_storage_account.logs
 ├─ Capacity                                              20  GB                $0.42
 ├─ Write operations                                      10  10k operations    $0.55
 └─ Read operations                                       50  10k operations    $0.22

 azurerm_container_app.myapp                Monthly cost depends on usage …

 OVERALL TOTAL                                                                 $14.99
──────────────────────────────────
4 cloud resources were detected:
∙ 2 were estimated
∙ 2 were free / usage-based without usage data

Whether a resource name is supported, and usage key names (for example monthly_data_ingestion_gb) follow Infracost's resource docs and infracost-usage-example.yml the reference page. Common errors: If not logged in, it reports “No INFRACOST_API_KEY environment variable is set”. Production use: Keep both the baseline and the diff in CI and comment on the PR; the FinOps team can see trends across all repos in Infracost Cloud (commercial feature).

Cost job in the PR workflow (classic CLI)

name: infracost
on:
  pull_request:
    paths: ["azure/**"]
permissions:
  contents: read
  pull-requests: write
jobs:
  cost:
    runs-on: ubuntu-24.04
    steps:
      - uses: infracost/actions/setup@e9d6e6cd65e168e76b0de50ff9957d2fe8bb1832 # v3 (the commit the tag pointed to as of 2026-11)
        with:
          api-key: ${{ secrets.INFRACOST_API_KEY }}
      - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
        with: { ref: "${{ github.event.pull_request.base.ref }}" }
      - run: infracost breakdown --path azure --format json --out-file /tmp/base.json
      - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
      - run: infracost diff --path azure --compare-to /tmp/base.json --format json --out-file /tmp/diff.json
      - run: |
          infracost comment github --path /tmp/diff.json \
            --repo "$GITHUB_REPOSITORY" --github-token "${{ github.token }}" \
            --pull-request "${{ github.event.pull_request.number }}" --behavior update

This approach parses only HCL and needs no cloud credentials; variable values come from defaults in the code, or --terraform-var-file. To use plan JSON as input (variables and modules already evaluated), in the plan job run infracost breakdown --path plan.json. infracost/actions The v3 is a movable major-version tag; after the SHA is pinned, Dependabot follows it. For the Infracost 2.0 CI integration, follow the infracost/cli docs.

AWS: default_tags and tag policy (see Lesson 4)

provider "aws" {
  region = "ca-central-1"
  default_tags {
    tags = {
      app           = "myapp"
      env           = "prod"
      owner         = "platform-team"
      "cost-center" = "cc-1001"
      managed-by    = "terraform"
    }
  }
}
package main

import rego.v1

required := {"owner", "cost-center", "env"}

# Check only resources that support tags: those with tags_all in after (AWS) or tags (Azure)
tag_map(after) := after.tags_all if after.tags_all != null
tag_map(after) := after.tags if {
  not after.tags_all
  after.tags != null
}

deny contains msg if {
  some rc in input.resource_changes
  some a in rc.change.actions
  a in {"create", "update"}
  tags := tag_map(rc.change.after)
  missing := required - {k | some k, _ in tags}
  count(missing) > 0
  msg := sprintf("%s is missing required tags %v", [rc.address, missing])
}
terraform show -json tfplan > plan.json
conftest test plan.json -p ../policies/opa
FAIL - plan.json - main - azurerm_container_app_environment.lab is missing required tags {"cost-center"}

3 tests, 2 passed, 0 warnings, 1 failure, 0 exceptions

Note: tags_all Some values may be unknown in the plan (for example, referencing an attribute of a resource not yet created), and then after does not include that key; the rule must choose “allow” or “deny” per team policy. On Azure you can also add an Azure Policy backstop: az policy assignment create --policy "871b6d14-10aa-478d-b590-94f262ecfa99" --params '{"tagName":{"value":"cost-center"}}' --scope /subscriptions/$SUB_ID/resourceGroups/rg-tf-lab (built-in policy “Require a tag on resources”; verify the definition ID in the portal).

Lab 6: PR cost comment + required-tags gate (about 7 min)

Register Infracost and save the API key:
infracost auth login
infracost configure get api_key | gh secret set INFRACOST_API_KEY
Add the workflow and tag policy: commit the infracost.yml,infracost-usage.yml and policies/opa/tags.rego (the conftest step in Module 4 runs it automatically).
Make one “expensive” change: change the Container App's cpu = 0.25/memory = "0.5Gi" to cpu = 2/memory = "4Gi",min_replicas = 1, and add usage assumptions for it in the usage file; also deliberately delete the local.tags in the cost-center. Open a PR.
infracost: 💰 Monthly cost will increase by $xx.xx
  azurerm_container_app.myapp  +$xx.xx

terraform-plan: ✗
  FAIL - plan.json - main - azurerm_resource_group.lab is missing required tags {"cost-center"}
  FAIL - plan.json - main - azurerm_container_app.myapp is missing required tags {"cost-center"}
  …
Fix: restore the cost-center tags so the check turns green; use the cost comment to decide whether to keep the size change (after the lab, it is recommended to revert to 0.25 vCPU,min_replicas = 0).
Cleanup: close the PR and delete the branch: gh pr close --delete-branch. The API key secret can be kept.

Case 1: one “size change” doubles the monthly bill

Problem: A developer changed the AKS node pool from D4s to E32s for load testing and forgot to change it back, adding $18k to the monthly bill. Approach: Add an Infracost comment in the PR; in the HCP workspace, use Sentinel to read tfrun.cost_estimate.delta_monthly_cost, set soft-mandatory above $1,000 so FinOps must override; cloud budget alerts act as the last line of defense. Limitations: Estimates are based on list prices and exclude enterprise discounts and reserved instances.

Case 2: missing tags leave 30% of costs unallocated

Problem: In the monthly cost report, 30% of spend has no cost-center. Approach: On all AWS stacks, enable default_tags; in Azure, have the shared internal module enforce the tags variable with validation; OPA tag rules run as advisory for two weeks, then mandatory; Azure Policy denies missing tags on resource groups, and resources inherit tags from the resource group on modify. Limitations: Some resource types do not support tags (or in AWS default_tags does not take effect for a few resources, for example propagated tags on Auto Scaling groups need separate configuration), so an exception list is needed.

Case 3: driving automation with tags

Problem: Non-production environments sit unused overnight. Approach: Tag schedule = office-hours + Azure Automation/Lambda scheduled shutdowns; in Terraform, use ignore_changes to ignore the power-state attributes that the shutdown script modifies. Limitation: Do not use tags to carry secrets or permission decisions (anyone with write permission can edit tags; ABAC scenarios need extra controls).

Common errors and fixes

Error: No INFRACOST_API_KEY environment variable is set.

Cause: Not logged in, or the secret was not passed in CI; fork PRs cannot get repository secrets.

Fix:infracost auth login; in the workflow, pass it via infracost/actions/setup the api-key input; fork PRs skip the cost job.

Infracost: "x resources were not supported" / Monthly cost depends on usage

Cause: Resource type not yet supported, or usage-billed with no usage provided.

infracost breakdown --path . --show-skipped

Fix: Add infracost-usage.yml; unsupported resources are noted in the comment as “needs manual estimate”.

Every plan shows a tags change: ~ tags = { + "CreatedOn" = … } (or default_tags and resource tags conflict)

Cause: A cloud policy or another system added tags to the resource; or in AWS, default_tags and the resource tags have a same-named key with a different value (the resource-level value wins, which can cause repeated changes); or timestamp() generates the tag values.

Fix: Do not use timestamp() in tags; for keys added externally, use ignore_changes = [tags["CreatedOn"]]; in AWS, avoid setting the same key in two places; upgrade to a newer aws provider (6.x fixed many tags_all related issues).

RequestDisallowedByPolicy: Resource 'rg-x' was disallowed by policy. Policy identifiers: 'Require a tag on resource groups'

Cause: Azure Policy deny took effect and ARM rejected the change at apply time, meaning Terraform's tag policy missed it (or is not yet enabled).

Fix: Add the missing tags; add the same rule to the plan-stage policy so the problem surfaces in the PR rather than at apply.

Command-line tasks
1. Use jq to list all AWS resources in the plan that are missing the cost-center tag (check tags_all).
jq -r '.resource_changes[] | select(.change.after.tags_all? != null) | select(.change.after.tags_all["cost-center"] == null) | .address' plan.json
2. Generate a baseline and calculate the cost difference of the current branch relative to main.
git stash; git switch main
infracost breakdown --path azure --format json --out-file /tmp/base.json
git switch -; git stash pop
infracost diff --path azure --compare-to /tmp/base.json
Scenario analysis
Finance requires that “any change that raises monthly cost by more than $500 must be approved by FinOps.” How would you implement this in self-hosted GitHub Actions?

Run infracost diff --format json, using jq to read diffTotalMonthlyCost; above 500: ① add a label in the PR needs-finops and require FinOps team review via CODEOWNERS/rulesets; ② in the deploy workflow, switch the apply job's environment to production-finops (approver: FinOps). Estimates exclude discounts, so the threshold should be conservative; also configure cloud budget alerts as a backstop.

Verified teaching videos

▶
Infracost - Cloud cost estimates for Terraform — Anton Babenko
English · Infracost principles and usage (recorded earlier; for 2.0 CLI changes, follow this lesson)
▶
Estimate Azure Costs from Terraform with Infracost — Talking tech with Techielass
English · Cost estimation demo for an Azure scenario

Official docs

Video storyboard (about 80 seconds)

This courseware cannot generate video/MP3 directly; the storyboard and narration script are provided instead.

Shot 1 · 0–20s
Scene: in the code, a string changes from D4s to E32s, and the bill number next to it soars.
Narration: in code it is just a string; on the bill it can be a tenfold difference.
Shot 2 · 20–45s
Scene: a cost comment appears on the PR page, listing how many extra dollars per month, item by item.
Narration: the cost estimation tool parses the code, compares it with public prices, and tells you before merging how much more this change costs per month.
Shot 3 · 45–65s
Scene: the provider default tags card and the resource tags card merge into tags all.
Narration: AWS default tags merge into tags all, where the policy should check; Azure has no default tags, so use locals to merge.
Shot 4 · 65–80s
Scene: three layers of shields: default injection, plan-stage policy, cloud-policy backstop.
Narration: tag governance has three layers: default injection, enforcement at the plan stage, and a cloud backstop.
or score ≥ 70% on the Quiz

Module 7 · Stacks and multi-deployment orchestration

47:00 – 54:00 · Deploy the same set of components to N environments/regions: from “copy workspaces + chain pipelines” to declarative deployments
7 minStacks GA (HashiConf 2025-09)HCP Terraform / Terraform Enterprise feature★★★
Learning objectives
  • Accurately describe the status of Terraform Stacks: GA was announced at HashiConf in September 2025; it runs in HCP Terraform (and in Terraform Enterprise with the TF_STACKS_HOSTNAME setting enabled); the legacy team plan is not available; beta-period configurations must be updated for GA.
  • Understand the two file types in a Stack: *.tfcomponent.hcl (component, provider, variable, output) and *.tfdeploy.hcl (deployment, identity_token, store, deployment_group), plus an independent state for each deployment.
  • Compare Stacks with “multiple workspaces + run triggers”, “GitHub Actions matrix + multiple states” and “Terragrunt” orchestration approaches, and know their limits (per Stack: max 20 deployments, 100 components, 10,000 resources).
Prerequisites: Lesson 2 module design; Module 3 HCP Terraform. Importance:★★★ (important for teams at scale; OK to skim if you are new)

What: Terraform Stacks

A Stack is a new configuration layer: it declares several Terraform modules as component (components connected through outputs/inputs), then uses deployment to declare “which targets (environments, regions, accounts) this set of components deploys to”. HCP Terraform keeps independent state for each deployment, plans and applies components in dependency order, and shows changes across deployments together and approves them by rule.

Files / blocksPurpose
*.tfcomponent.hcl: componentreferences a module (source), passes inputs, and specifies providers; can be expanded with for_each (e.g., multi-region)
*.tfcomponent.hcl: providerProviders in a Stack are named (provider "azurerm" "this" { config { … } }), and can for_each; configuration usually comes from variables (including OIDC tokens)
*.tfcomponent.hcl: variable / output / required_providersStack-level inputs, outputs and provider dependencies (the lock file is generated by terraform stacks providers-lock )
*.tfdeploy.hcl: deploymenta deployment target and its inputs; each deployment has its own independent state
*.tfdeploy.hcl: identity_tokengenerates an OIDC JWT for the deployment (e.g., audience = ["aws.workload.identity"]), passed via identity_token.x.jwt to the provider
*.tfdeploy.hcl: storereads values from an HCP variable set (e.g., store "varset" "api_keys" { … })
*.tfdeploy.hcl: deployment_groupsets shared orchestration/auto-approval rules for a group of deployments (the official docs note that a higher HCP Terraform tier is required; check the pricing page)
Linked Stacksan upstream Stack publishes outputs and a downstream Stack consumes them (announced as beta in a HashiCorp blog post; check the docs for current status)

Current status and limits (verified 2026-11)

  • GA: HashiConf 2025 (September) announced general availability, and the API carries a backward-compatibility guarantee; the docs require beta users to update configs for GA. Since then, monorepo support, workspace/Stack recovery, Linked Stacks (beta) and more have been added.
  • Where it runs: Stacks are created and deployed in HCP Terraform; Terraform Enterprise uses TF_STACKS_HOSTNAME with the Stacks CLI. There is no“apply a Stack purely locally” workflow.
  • CLI: terraform stacks Command group: init,validate,fmt,providers-lock,create,list,diagnostics,version, and subcommand configuration,deployment-run,deployment-group,migrate (migrate a traditional workspace to Stacks).
  • Limits: each Stack allows at most 20 deployments, 100 components and 10,000 resources, and at most 20 upstream and 25 downstream Stacks.
  • Plan tiers: the legacy HCP Terraform team plan is not available; check the pricing page for current limits per tier.
  • Deferred changes: when a for_each/count depends on values not yet known (for example, create the cluster first, then create K8s resources from its outputs), Stacks can apply what is determinable first and plan the rest in later rounds. In Terraform CLI 1.17, the corresponding -allow-deferral is still available only in alpha experimental builds.

Why: what problem it solves

  • Duplication: the traditional approach is one workspace per environment × region × layer (3 environments × 2 regions × 3 layers = 18 workspaces), each with its own variables, credentials and triggers; Stacks use 3 components + 6 deployments.
  • Orchestration: dependencies between layers (network → cluster → app) were originally chained with run triggers or pipelines, and retries and partial-success handling had to be written by hand; Stacks plan everything from the component dependency graph.
  • “Chicken and egg”: deferred changes reduce the need to split configuration into two parts applied in two separate applies.

How: one Stack change

  1. Push the Stack configuration → HCP creates a new configuration version.
  2. Generate a plan for each deployment (within each deployment, components are ordered by dependency).
  3. Approve by the rules of the deployment / deployment group (for example, dev auto-approves, prod is manual).
  4. Apply; if deferred changes exist, later rounds keep planning until convergence.

When: when to use Stacks and when not to

ApproachGood fitNot a fit
StacksAlready on HCP Terraform; the same components deployed to multiple environments/regions/accounts; tightly coupled layersNot using HCP/TFE; need OpenTofu; a single Stack over 20 deployments (split it)
Multiple workspaces + run triggersTeam already knows workspaces; loosely coupled layersLots of repeated configuration, deep chained dependencies
GitHub Actions matrix + one state per target (an extension of Module 2 in this course)Self-built pipelines; a moderate number of targetsNeeds a dependency graph across states and partial retries
Terragrunt (third-party)DRY backend/provider generation,run --all dependency orchestration; supports OpenTofuWant to use only the HashiCorp official toolchain
Common misconceptions① “Stacks are still beta”: they went GA in 2025-09, but some peripheral features (such as Linked Stacks) went through a beta phase, so distinguish them when citing. ② “Stacks replace modules”: a component's source is a module, so module design (Lesson 2) is still the foundation. ③ “Stacks is just an upgraded CLI workspace”: it is a first-class object in HCP Terraform with its own deployments, state and approval flow; the CLI only handles validation, upload and management. ④ “One Stack holds the whole company”: it is bound by limits such as 20 deployments / 10,000 resources; split by product or domain and connect them with Linked Stacks.

Architecture diagram: component × deployment

components.tfcomponent.hcl component "network"source = ./modules/network component "app"inputs.subnet_id = component.network… provider "azurerm" "this"config { use_oidc, oidc_token = var.jwt } deployments.tfdeploy.hcl identity_token "azure" deployment "dev" deployment "staging" deployment "prod" deployment_group: prod requires manual approval Stack in HCP Terraform dev: network → appindependent state · auto-approve staging: network → appindependent state prod: network → appindependent state · waiting for approval
Figure 7-1: components define “what to deploy”, deployments define “where to deploy it”; each deployment has its own independent state

Flowchart: deferred changes

Round 1 plancluster can be planned namespaces for_eachdepends on unknown values → deferred apply clusteroutputs become known Round 2 plan/applynamespaces converge In a traditional workflow this would fail with “Invalid for_each argument … cannot be determined until apply”; you could only split the configuration or use -target
Figure 7-2: Stacks turn “two applies” into platform-managed multi-round convergence

Interactive animation: how one Stack configuration change advances across three deployments

Playback notes: within each deployment, components are planned in dependency order; dev auto-approves, prod needs manual approval; tick “deferred changes” to see multi-round convergence.

Core commands

CommandPurpose
terraform stacks initInitialize the Stack and prepare the configuration directory (downloads providers, etc.)
terraform stacks providers-lockWrite the dependency lock for the providers configured in the Stack
terraform stacks validateValidate local component and deployment configuration
terraform stacks fmtFormat .tfcomponent.hcl / .tfdeploy.hcl
terraform stacks create / listCreate / list Stacks in HCP Terraform
terraform stacks configuration …Manage (upload/view) configuration versions
terraform stacks deployment-run … / deployment-group …Manage deployment runs and deployment groups (approvals, etc.)
terraform stacks diagnosticsGet alerts and errors for a configuration or deployment step
terraform stacks migrate …Migrate a traditional workspace to Stacks

The command list comes from the developer.hashicorp.com “terraform stacks” page (v1.17.x docs); for each command's arguments, see its subpages or terraform stacks <cmd> -help.

Minimal Stack: deploy myapp to dev and prod (Azure)

required_providers {
  azurerm = {
    source  = "hashicorp/azurerm"
    version = "~> 5.0"
  }
}

variable "location"       { type = string }
variable "env"            { type = string }
variable "client_id"      { type = string }
variable "tenant_id"      { type = string }
variable "subscription_id" { type = string }
variable "identity_token" {
  type      = string
  ephemeral = true
}

provider "azurerm" "this" {
  config {
    features {}
    use_oidc                        = true
    oidc_token                      = var.identity_token
    client_id                       = var.client_id
    tenant_id                       = var.tenant_id
    subscription_id                 = var.subscription_id
    resource_provider_registrations = "none"
  }
}

component "network" {
  source = "./modules/network"
  inputs = {
    location = var.location
    env      = var.env
  }
  providers = {
    azurerm = provider.azurerm.this
  }
}

component "app" {
  source = "./modules/app"
  inputs = {
    location  = var.location
    env       = var.env
    subnet_id = component.network.app_subnet_id
  }
  providers = {
    azurerm = provider.azurerm.this
  }
}

output "app_url" {
  type  = string
  value = component.app.url
}
identity_token "azure" {
  audience = ["api://AzureADTokenExchange"]
}

deployment "dev" {
  inputs = {
    location        = "canadacentral"
    env             = "dev"
    client_id       = "<clientId of id-tfstack-dev>"
    tenant_id       = "<tenant>"
    subscription_id = "<dev subscription>"
    identity_token  = identity_token.azure.jwt
  }
}

deployment "prod" {
  inputs = {
    location        = "canadacentral"
    env             = "prod"
    client_id       = "<clientId of id-tfstack-prod>"
    tenant_id       = "<tenant>"
    subscription_id = "<prod subscription>"
    identity_token  = identity_token.azure.jwt
  }
}

Notes:identity_token block,deployment of inputs, named provider block and config sub-block structure follows the examples in the Stacks official docs (official examples mainly use AWS's assume_role_with_web_identity + aws.workload.identity ). The issuer for Azure-side federated credentials is https://app.terraform.io, and the Stacks token's sub format differs from workspace tokens (it includes the stack and deployment names); configure the federated credential subject following the official “Authenticate a Stack” doc. ephemeral = true variable ensures the token is not written to state. In the example above, the ./modules/network,./modules/app can be split out of the Lesson 3 configuration.

cd stack
terraform stacks init
terraform stacks providers-lock
terraform stacks fmt
terraform stacks validate
Success! Stack configuration is valid and ready for use.

Lab 7: read and rewrite a minimal Stack (about 7 min; deployment is optional)

Split the modules: in stack/modules/network put the VNet/subnet resources from Lesson 3 (output app_subnet_id),stack/modules/app place the Container Apps environment and app (input subnet_id, output url). The resource group can be created by the network component, which outputs its name.
Write the components / deployments files (see the Commands tab), then run terraform stacks init,providers-lock,fmt,validate, then fix all diagnostics.
Thought question (write it in the PR description): if you need to add a canadaeast second region, would you ① add a new deployment, or ② use for_each + provider for_each? What is the effect of each on state isolation, blast radius and the limit (20 deployments)?
(Optional, HCP Terraform) deploy: in an HCP project, create a Stack and connect the repo's stack/ directory; for dev and prod, create a managed identity and a federated credential each (use the Stack subject format); push the configuration and watch the dev and prod deployment plans and approvals. Resources in a Stack count toward the managed resource total.
Cleanup: in HCP, destroy each deployment, then delete the Stack; delete the managed identities created for the Stack. You can keep the local directory for reference.

Case 1: consolidating 18 workspaces into 1 Stack

Problem: 3 environments × 2 regions × 3 layers (network, data, app) = 18 workspaces; the run-trigger chain is fragile, and one network change means manually watching 6 runs. Approach: Migrated to 1 Stack: 3 components and 6 deployments; the dev group auto-approves and the prod group needs manual approval; use terraform stacks migrate to help migrate state. Limitations: The migration needs a change freeze window; existing workspace-level policy sets and notifications must be reconfigured.

Case 2: cluster and in-cluster resources in one go

Problem: The AKS cluster must exist before its outputs can configure the kubernetes/helm providers; the traditional approach requires splitting into two configurations and two applies. Approach: The Stack has cluster and workloads components; deferred changes converge automatically over several rounds. Limitations: The first deployment needs several rounds; later changes complete normally in one pass.

Case 3: what teams without HCP can do

Problem: Compliance requirements force a self-hosted setup. Approach: GitHub Actions matrix (strategy.matrix.env) + an independent state per environment + environment approvals; for dependencies between layers, use terraform_remote_state or data sources (Lesson 6); or use Terragrunt's dependency orchestration. Limitations: You must maintain retries after partial failures and the cross-layer dependency graph yourself.

Common errors and fixes

Error: Invalid for_each argument … The "for_each" map includes keys derived from resource attributes that cannot be determined until apply (traditional workflow)

Cause: Standard Terraform does not support deferred changes (the CLI's -allow-deferral is still alpha experimental).

Fix: Use statically known keys (variables) as for_each keys; or split the configuration; or use deferred changes in Stacks. Do not rely on -target as a regular workflow.

Stacks are not available on your current plan

Cause: The organization is still on the legacy team plan, or the current tier does not include the required feature (such as deployment groups).

Fix: Migrate to a current plan following the official migration guide; check the pricing page to confirm which tier includes the feature.

terraform stacks validate: Unsupported block type "backend" / "terraform"

Cause: You put a normal Terraform root module's terraform { backend … },provider "azurerm" {} (single label) into .tfcomponent.hcl. In a Stack, state is managed by HCP, and the provider uses a double label plus config sub-block.

Fix: Delete the backend; change the provider to provider "azurerm" "this" { config { … } }, and pass it in the component via providers . Do not declare provider configuration inside referenced modules.

AADSTS700213 / AccessDenied (Stack deployment authentication failure)

Cause: The federated credential subject is configured in the workspace format, but the Stack token's sub includes stack/deployment information; or the audience does not match.

Fix: In the HCP deployment run details, inspect the token claims, and update the federated credential using the Stack subject format from the official docs; identity_token audience must match the cloud configuration.

Command-line tasks
1. Write the sequence of commands to validate locally and lock the Stack's providers.
terraform stacks init
terraform stacks providers-lock
terraform stacks fmt
terraform stacks validate
2. Write an identity_token block for use by an AWS deployment.
identity_token "aws" {
  audience = ["aws.workload.identity"]
}
# In deployment inputs: aws_token = identity_token.aws.jwt
Scenario analysis
Your company has 40 regional deployment targets, uses OpenTofu, and has no HCP subscription. The CTO asks, “Should we adopt Stacks?”

Not a fit: Stacks run in HCP Terraform/TFE and do not support OpenTofu; a single Stack allows at most 20 deployments, so 40 targets must be split into at least 2 Stacks. Alternatives: a GitHub Actions matrix + an independent state per target + environment approvals, or orchestration tools from the Terragrunt/OpenTofu ecosystem; you can also evaluate TACOS platforms that support OpenTofu. If you later migrate to HCP Terraform (Terraform, not OpenTofu), split by product domain into multiple Stacks and connect them with Linked Stacks.

Verified teaching videos

▶
Terraform Stacks is here! — HashiCorp, an IBM Company
English · Official introduction to Stacks (for syntax, follow the post-GA docs)
▶
Getting Started with Terraform Stacks — Ned in the Cloud
English · Hands-on introduction (may have been recorded during beta; for file extensions and similar details, follow this lesson)
▶
TERRAFORM STACKS announced at HashiConf 2023!!! — Azure Terraformer
English · Design intent at the first release in 2023 (historical background)

Official docs

Video storyboard (about 80 seconds)

This courseware cannot generate video/MP3 directly; the storyboard and narration script are provided instead.

Shot 1 · 0–20s
Scene: eighteen workspace blocks tangled together by thin lines.
Narration: three environments, two regions, three layers: the traditional approach is eighteen workspaces and a chain of triggers.
Shot 2 · 20–45s
Scene: three component cards on the left, six deployment cards on the right, lines converging into one Stack.
Narration: Stacks use components to describe what to deploy and deployments to describe where to deploy it; each deployment has its own state.
Shot 3 · 45–65s
Scene: dev turns green automatically, prod stops at “waiting for approval”.
Narration: deployment groups can have different approval rules: dev is automatic, production is manual.
Shot 4 · 65–80s
Scene: the calendar flips to September 2025, the HashiConf logo, and the letters GA.
Narration: Stacks shipped officially in September 2025, running in HCP Terraform, with up to twenty deployments per Stack.
or score ≥ 70% on the Quiz

Module 8 · Recap of the first five hours, self-check and cleanup

54:00 – 60:00 · Tie the five lessons into one thread: from a single .tf file to a policy-guarded, auditable production pipeline that checks itself
6 minReview + troubleshooting tree + cleanup★★★★
Learning objectives
  • Use a knowledge map to review the core concepts of Lessons 1–5 and find your weak spots.
  • When a Terraform failure occurs in CI, locate it quickly in the order “authentication → backend/state → provider/lock file → plan → policy → approval/apply” (use the interactive troubleshooting tree on the Troubleshooting tab).
  • Safely clean up the OIDC identities, federated credentials, role assignments, HCP resources and cloud resources created in this lesson, so no permissions or costs are left behind.
Prerequisites: Modules 1–7 of this lesson. Importance:★★★★

What: knowledge map of the first five hours

LessonCore skillsHow it appears in this lesson's pipeline
Lesson 1 core basicsHCL, providers and lock file, resource dependency graph, variables/outputs, state, CLI workflowinit -lockfile=readonly,plan -out,-detailed-exitcode
Lesson 2 production readinessmodules, remote state and locking, for_each, moved/import/removed, validation/check, terraform test, static scanning, version constraintsfmt/validate/tflint/test in the PR; check blocks participate in continuous validation
Lesson 3 Azureazurerm authentication, azurerm backend, VNet, Container Apps, managed identity, AVMpipeline-managed azure/ stack; managed identity + federated credential
Lesson 4 AWSaws provider, S3 backend use_lockfile, VPC, ECS Fargate, IAMIAM OIDC provider,default_tags,tags_all
Lesson 5 automation and operationsGitOps workflow, OIDC, two-stage workflow, HCP Terraform, policy as code, drift, cost and tags, StacksIntegrated lab for this lesson

Why: why do a review

The first four lessons teach you to “write Terraform correctly”; this lesson teaches you to “let people and machines run it safely.” Production incidents rarely come from one concept; they stack up across several layers: a lock file missing platform hashes + overly broad identity permissions + no policy + applying a plan that was never approved. Connecting the knowledge is what lets you pinpoint the failing layer quickly during an incident.

How: the six-layer order for troubleshooting CI failures

  1. Trigger and permissions: is the workflow triggered (paths, branch, fork)? permissions Does it include id-token: write?
  2. Cloud authentication: OIDC sub/aud subject match? Has the role assignment propagated? (AADSTS700213, AccessDenied, AuthorizationFailed)
  3. backend / state: Blob data role, lock held, state modified by someone else (403, state lock, stale plan).
  4. Provider and lock file: platform hashes, version constraints,-lockfile=readonly, Terraform version mismatch.
  5. The plan itself: configuration errors, insufficient permissions to read some resources (listSecrets), resource provider not registered.
  6. Gate and apply: policy failures, approval not completed, apply rejected by a cloud policy (RequestDisallowedByPolicy).

When: cleanup principles

  • Revoke permissions first, then delete resources: first delete federated credentials and role assignments so no identity can still access anything; then destroy the resources.
  • Reverse the creation order: Stack/HCP workspace → workloads → identities → state storage (if Lesson 6 no longer needs it).
  • What to keep: Lesson 6 reuses the myapp-infra repo, state storage account and workflow structure; keep the repo and rg-tfstate, and clean up only the usage-billed workloads.
Common misconceptions① “Deleting the resource group cleans everything up”: managed identities in another resource group (this lesson puts them in rg-tfstate), subscription-level role assignments, Entra app registrations, GitHub environments and variables, and HCP workspaces are not deleted along with it. ② “Deleting the repo means the federated credentials are useless”: a repo recreated under the same name sub can match again; federated credentials must be deleted explicitly.

Architecture diagram: final state of this lesson

GitHub: myapp-infra Branch protection · CODEOWNERS terraform-pr.yml (plan + comment + policy) infracost.yml (cost comment) terraform-deploy.yml (plan → approval → apply) terraform-drift.yml (daily) environments: dev / staging / production policies/tfpolicy · policies/opa Actions pinned by SHA + Dependabot issues: drift label Entra ID id-tf-plan: pull_request / mainReader + Blob Data Contributor id-tf-prod: environment:productionContributor@rg-tf-lab rg-tfstate sttfstate… / tfstatelab3/myapp.tfstate (lease lock)Managed identities are also here rg-tf-lab (canadacentral) Log AnalyticsContainer Apps environmentca-myapp-prodstmyapplogs… (Module 4) Azure Policy: Require tag (backstop) Optional: rg-tf-hcp-demo (Module 3) Optional: HCP workspace / Stack
Figure 8-1: all assets at the end of this lesson; when cleaning up, follow the order “identities → workloads → optional resources”

Flowchart: layered diagnosis of CI failures

① Trigger/permissionspaths · id-token ② Cloud authsub · aud · RBAC ③ backendBlob role · lock ④ providerLock file · versions ⑤ planConfig · read permission ⑥ Gate/applyPolicy · stale
Figure 8-2: find the module for the layer where the error appears (the troubleshooting tree in the Troubleshooting tab follows the same order)

Interactive replay: read the logs, guess the layer

Click “Draw a failure”, read the CI log excerpt, and choose the layer you think failed; after you answer, the root cause and fix are shown. Answering 5 in a row correctly means you have mastered the troubleshooting order.

Score 0 / 0
Click “Draw a failure” to start.

Cleanup commands (run in order)

ObjectCommandNotes
Federated credentialaz identity federated-credential deleteRevoke trust first
Role assignmentaz role assignment delete --assignee OIDDeleting the identity also invalidates the assignments, but leaves “unknown identity” stale entries
Managed identityaz identity deletein rg-tfstate
Workloadsterraform destroy / deploy workflowPreferably through the pipeline (practice approving the delete change)
GitHubgh variable delete,gh api -X DELETE …/environments/Xor delete the entire repo
HCPUI: delete the workspace/Stackdestroy its resources first
AWS (if done)aws iam delete-role,delete-open-id-connect-providerdetach policies first
#!/usr/bin/env bash
set -euo pipefail
: "${STATE_RG:=rg-tfstate}"
SUB_ID=$(az account show --query id -o tsv)

# 1) Revoke trust: delete all federated credentials
for ID in id-tf-plan id-tf-prod; do
  for FC in $(az identity federated-credential list -g "$STATE_RG" --identity-name "$ID" --query "[].name" -o tsv 2>/dev/null); do
    az identity federated-credential delete -g "$STATE_RG" --identity-name "$ID" -n "$FC" --yes
    echo "deleted federated credential $ID/$FC"
  done
done

# 2) Delete role assignments, then delete the identity
for ID in id-tf-plan id-tf-prod; do
  OID=$(az identity show -g "$STATE_RG" -n "$ID" --query principalId -o tsv 2>/dev/null || true)
  if [ -n "$OID" ]; then
    az role assignment delete --assignee "$OID" --yes 2>/dev/null || az role assignment delete --assignee "$OID"
    az identity delete -g "$STATE_RG" -n "$ID"
    echo "deleted identity $ID"
  fi
done

# 3) Optional resources
az group delete -n rg-tf-hcp-demo --yes --no-wait 2>/dev/null || true

# 4) Workloads (if not kept for Lesson 6):
#    cd ~/myapp-infra/azure && terraform destroy     # requires local Contributor permission
#    or: az group delete -n rg-tf-lab --yes --no-wait
echo "done. Remaining identities:"; az identity list -g "$STATE_RG" -o table
deleted federated credential id-tf-plan/gh-pull-request
deleted federated credential id-tf-plan/gh-main
deleted federated credential id-tf-prod/gh-env-production
deleted identity id-tf-plan
deleted identity id-tf-prod
done. Remaining identities:
# GitHub side
for V in AZURE_TENANT_ID AZURE_SUBSCRIPTION_ID AZURE_PLAN_CLIENT_ID; do gh variable delete $V; done
gh variable delete AZURE_CLIENT_ID --env production
gh secret delete INFRACOST_API_KEY
# To delete the repo completely (requires the delete_repo permission: gh auth refresh -s delete_repo)
# gh repo delete "$REPO" --yes

# AWS side (if you did the OIDC part of Lesson 4)
aws iam list-attached-role-policies --role-name gh-tf-prod
# aws iam detach-role-policy --role-name gh-tf-prod --policy-arn <ARN>
aws iam delete-role --role-name gh-tf-prod
aws iam delete-open-id-connect-provider --open-id-connect-provider-arn arn:aws:iam::123456789012:oidc-provider/token.actions.githubusercontent.com

How to verify:az role assignment list --all --query "[?principalType=='ServicePrincipal' && principalName==null]" -o table look for leftover “unknown identity” assignments; az identity list -o table confirm the identity has been deleted. Cost: The workloads in this lesson are billed by usage; with min_replicas=0, Container Apps cost almost nothing; Log Analytics bills by ingestion; LRS storage accounts are very cheap.

Lab 8: self-check + cleanup (about 6 min)

Five-minute self-check: answer without the courseware — ① what are the PR identity's and the prod identity's sub respectively? ② Why should the plan file be treated as a secret? ③ Why shouldn't drift detection share a concurrency group with deployment? ④ Why does the AWS tag policy check tags_all? ⑤ What is the biggest difference between Terraform Policy and OPA? The answers are in this module's “Quiz” and the final quiz.
Review with the troubleshooting tree: open the “Troubleshooting” tab and, for each failure you hit in this lesson's labs, walk through the troubleshooting tree to confirm which layer it belongs to.
Decide what to keep: if you continue to Lesson 6, keep the repo,rg-tfstate and identities; only keep the Container App's min_replicas at 0. If you are finishing the course, run the Commands tab's cleanup-lesson5.sh and the GitHub/AWS cleanup.
Verify cleanup:
az group list --query "[?starts_with(name,'rg-tf')].name" -o tsv
az identity list --query "[].name" -o tsv
gh variable list
rg-tfstate

Case 1: a federated credential left behind by a departed employee

Problem: An engineer once created a federated credential for a personal fork (repo:alice/myapp-infra:…) for debugging; after they left, the fork still existed, and its workflows could still get the Contributor identity. Approach: Each quarter, use Azure Resource Graph to inventory the federated credentials on all managed identities; delete at once any whose subject is not under an allowlisted organization; federated credentials may only be created through the bootstrap stack (code). Limitations: The same inventory is needed for federated credentials on Entra app registrations.

Case 2: layered diagnosis of a CI failure

Problem: On Monday morning, all Terraform runs failed, reporting Error: Failed to query available provider packages. Approach: Troubleshoot layer by layer: authentication OK → backend OK → provider layer: a newly added Linux ARM self-hosted runner whose lock file has no linux_arm64 hash for it. terraform providers lock -platform=linux_arm64 … Service was restored afterward. Limitations: Adding a runner platform must go through the change process for the “lock file platform list”.

Case 3: a cleanup script deleted a shared identity by mistake

Problem: The lab cleanup script deletes identities by name prefix id-tf- , so it deleted a production identity from another team that shares the same prefix. Approach: Cleanup targets only an explicit list or resources with a course=lesson5 tag; print the list before deleting and require confirmation. Limitations: Production subscriptions should not be used for labs.

Interactive troubleshooting tree: common Terraform failures in CI

Start from the symptom you see, answer the questions layer by layer, and get diagnostic commands and fixes.

Extra: the 3 most common errors in this lesson

Error: Failed to install provider … the current package for registry.terraform.io/hashicorp/azurerm 5.14.0 doesn't match any of the checksums previously recorded in the dependency lock file

Cause: The lock file has no hash for the CI platform (linux_amd64),-lockfile=readonly do not hand-write it.

terraform providers lock -platform=linux_amd64 -platform=darwin_arm64 -platform=windows_amd64
git add .terraform.lock.hcl && git commit -m "Lock providers for all platforms"
Error: Process completed with exit code 2. (the plan step “failed” but shows no error message)

Cause: Used -detailed-exitcode, which returns exit code 2 when there are changes, and GitHub Actions treats any non-zero exit as a failure.

Fix: As shown in Module 2, set +e capture the exit code, and fail only when it equals 1 exit 1.

Error: Unable to find an artifact with the provided name: tfplan-…

Cause: The plan job's exit code was 0, so it uploaded no artifact, yet the apply job still ran (missing if); or the SHA in the artifact name is inconsistent (the github.sha value differs between runs); or the retention period has passed.

Fix: On the apply job, add if: needs.plan.outputs.exitcode == '2'; use the same name within one run; if it has expired, re-run the whole workflow.

Command-line tasks
1. List all managed identities in rg-tfstate and their federated credential subjects.
for ID in $(az identity list -g rg-tfstate --query "[].name" -o tsv); do
  echo "== $ID"; az identity federated-credential list -g rg-tfstate --identity-name $ID --query "[].subject" -o tsv
done
2. View all role assignments (including scope) for a given managed identity.
az role assignment list --assignee $(az identity show -g rg-tfstate -n id-tf-prod --query principalId -o tsv) --all --query "[].{role:roleDefinitionName,scope:scope}" -o table
Scenario analysis
A new colleague asks: “Why don't we just run terraform apply on our laptops? That would be much faster.” Give a complete answer using the knowledge from the first five lessons.

Reproducibility: CI pins the Terraform version, the lock file (Lesson 1) and variables; security: no long-lived high-privilege credentials, with OIDC issued per environment (Lesson 5); correctness: PR plan review, policy gates (Lesson 5) and test/static scanning (Lesson 2); consistency: remote state and locking (Lessons 2–4), and apply uses the approved plan itself; auditability: PRs, approvals, run logs; continuous compliance: drift detection, cost and tag governance. A personal sandbox can apply locally; shared environments must go through the pipeline only.

Verified teaching videos (for review)

▶
Terraform in 100 Seconds — Fireship
English · Two-minute review of Terraform core concepts
▶
Introduction to HashiCorp Terraform with Armon Dadgar — HashiCorp, an IBM Company
English · The founder explains Terraform's design philosophy
▶
Complete Terraform Course - From BEGINNER to PRO! (Learn Infrastructure as Code) — DevOps Directive
English · Full course with automation and testing chapters; a supplement to the first five lessons
▶
5 Lessons Learned From Writing Over 300,000 Lines of Infrastructure Code — HashiCorp, an IBM Company
English · Large-scale IaC practice, echoing this lesson's process design

Official docs

Video storyboard (about 90 seconds)

This courseware cannot generate video/MP3 directly; the storyboard and narration script are provided instead.

Shot 1 · 0–25s
Scene: five steps, labeled in order: core basics, production readiness, Azure, AWS, automation and operations.
Narration: the first four lessons teach you to write correct Terraform; the fifth teaches you to let machines run it safely.
Shot 2 · 25–55s
Scene: a six-layer troubleshooting funnel: trigger, authentication, backend, provider, plan, gate. A red error log falls from the top and stops at the second layer.
Narration: when CI fails, troubleshoot in six layers: trigger and permissions, cloud authentication, state backend, provider and lock file, the plan itself, gates and apply.
Shot 3 · 55–90s
Scene: the key icon is retracted first, then the resource blocks disappear one by one.
Narration: when cleaning up, revoke trust and permissions first, then delete resources. Even if the repo is deleted, federated credentials must be deleted explicitly.
or score ≥ 70% on the Quiz

Command cheat sheet

Terraform 1.17 · CI/CD and policy governance · every code block can be copied with one click
After-class reference

Terraform in CI

export TF_IN_AUTOMATION=true TF_INPUT=false
terraform fmt -check -recursive
terraform init -lockfile=readonly
terraform validate
set +e; terraform plan -lock-timeout=5m -out=tfplan -detailed-exitcode; ec=$?; set -e
[ $ec -eq 1 ] && exit 1
terraform show -json tfplan > plan.json
terraform show -no-color tfplan > plan.txt
terraform apply -lock-timeout=5m tfplan
terraform providers lock -platform=linux_amd64 -platform=darwin_arm64 -platform=windows_amd64

Azure OIDC

az identity create -g RG -n id-tf-prod
az identity federated-credential create -g RG --identity-name id-tf-prod -n gh-env-production \
  --issuer https://token.actions.githubusercontent.com \
  --subject "repo:ORG/REPO:environment:production" --audiences api://AzureADTokenExchange
az role assignment create --assignee-object-id OID --assignee-principal-type ServicePrincipal \
  --role Contributor --scope /subscriptions/SUB/resourceGroups/rg-tf-lab
# workflow env:
# ARM_USE_OIDC=true ARM_CLIENT_ID ARM_TENANT_ID ARM_SUBSCRIPTION_ID
# backend "azurerm" { use_azuread_auth = true }

AWS OIDC

resource "aws_iam_openid_connect_provider" "github" {
  url            = "https://token.actions.githubusercontent.com"
  client_id_list = ["sts.amazonaws.com"]
}
# Trust policy conditions:
#  token.actions.githubusercontent.com:aud = sts.amazonaws.com
#  token.actions.githubusercontent.com:sub = repo:ORG/REPO:environment:production
# workflow:
#  uses: aws-actions/configure-aws-credentials@e1253824e5c10ff9df46874f81ed3ec929e19cfd # v6.3.0
#  with: { role-to-assume: ARN, aws-region: ca-central-1 }

Key points of the workflow skeleton

permissions: { contents: read }
concurrency: { group: tf-deploy-azure-prod, cancel-in-progress: false }
jobs:
  plan:
    permissions: { contents: read, id-token: write }
    outputs: { exitcode: "${{ steps.plan.outputs.exitcode }}" }
  apply:
    needs: plan
    if: needs.plan.outputs.exitcode == '2'
    environment: production
# actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1          # v7.0.1
# hashicorp/setup-terraform@dfe3c3f87815947d99a8997f908cb6525fc44e9e # v4.0.1
# actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9   # v7.0.2
# actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
# azure/login@a641126d1b8aa4d1fa005f4f92df94a3a4c4c906               # v3.1.0

HCP Terraform

terraform login
# terraform { cloud { organization = "ORG"  workspaces { project = "P" name = "WS" } } }
terraform init -migrate-state
export TF_TOKEN_app_terraform_io=…          # CI
# Dynamic credentials (workspace environment variables):
#  TFC_AZURE_PROVIDER_AUTH=true  TFC_AZURE_RUN_CLIENT_ID=…  ARM_SUBSCRIPTION_ID  ARM_TENANT_ID
#  TFC_AWS_PROVIDER_AUTH=true    TFC_AWS_RUN_ROLE_ARN=…
# sub: organization:ORG:project:P:workspace:WS:run_phase:plan|apply

Policy as code

terraform plan -policies=../policies/tfpolicy -out=tfplan     # 1.17 GA
tfpolicy validate --policies=policies/tfpolicy
tfpolicy test --policies=policies/tfpolicy --tests=policies/tests
conftest verify -p policies/opa
conftest test plan.json -p policies/opa -o github
jq -r '.resource_changes[] | select(.change.actions|index("delete")) | .address' plan.json
sentinel test

Drift detection

terraform plan -refresh-only -lock=false -out=drift.tfplan
terraform show -json drift.tfplan | jq '[.resource_drift[]?] | length'
terraform apply -refresh-only            # accept into state (after review)
gh workflow run terraform-drift.yml
gh issue list --label drift
# lifecycle { ignore_changes = [tags["CreatedBy"]] }

Cost · tags · Stacks

infracost auth login
infracost breakdown --path . --usage-file infracost-usage.yml
infracost diff --path . --compare-to base.json
infracost comment github --path diff.json --repo R --github-token T --pull-request N --behavior update
# AWS: provider "aws" { default_tags { tags = {...} } } → policy checks tags_all
terraform stacks init && terraform stacks providers-lock
terraform stacks fmt && terraform stacks validate

Quick troubleshooting table

Symptom / errorLayerMost likely causeQuick fix
Unable to get ACTIONS_ID_TOKEN_REQUEST_URLTrigger/permissionsMissing id-token: write or fork PRJob-level permissions; skip forks
AADSTS700213 No matching federated identity recordAuthenticationsub mismatch (environment vs. ref)Add a federated credential for the sub in the error
Not authorized to perform sts:AssumeRoleWithWebIdentityAuthenticationTrust policy sub/aud conditions, OIDC provider missingCheck the conditions and provider ARN
403 AuthorizationPermissionMismatch (state)backendMissing Storage Blob Data ContributorContainer-scoped grant; wait for propagation
state blob is already lockedbackendConcurrent runs / leftover cancelconcurrency; force-unlock after confirming
doesn't match any of the checksums … lock fileproviderLock file missing platform hashesproviders lock -platform=…
plan file was created by Terraform X, but this is YproviderTwo jobs use different versionsUnify TF_VERSION
AuthorizationFailed … listSecrets / register/actionplanInsufficient Reader / RP registrationCustom role; resource_provider_registrations = "none"
Process completed with exit code 2plan-detailed-exitcode uncaughtset +e handling
FAIL - plan.json - main - …GatePolicy violationFix the configuration or go through the exception process
Saved plan is staleapplyState changed during approvalRe-run the workflow
RequestDisallowedByPolicyapplyCloud policy denialMove the same rule forward into the plan policy

Recommended config snippet: Dependabot automatically upgrades SHA-pinned Actions

version: 2
updates:
  - package-ecosystem: "github-actions"
    directory: "/"
    schedule: { interval: "weekly" }
    groups:
      actions: { patterns: ["*"] }
  - package-ecosystem: "terraform"
    directory: "/azure"
    schedule: { interval: "weekly" }

Integrated lab + final quiz

Build a complete CI/CD pipeline for the Azure stack from Lesson 3: keyless OIDC authentication + PR plan comments + dual-engine policy gate + cost comment + apply the same plan after approval + daily drift detection
After class ≈ 45 minutesCovers all modulesAzure cost < $1
Scenario The infrastructure of myapp (Lesson 3: resource group rg-tf-lab, Log Analytics, Container Apps environment and app) is about to be handed over to multiple maintainers. Security and audit requirements: ① no cloud keys stored in GitHub; ② all changes must go through a PR, with the plan, policy results and cost difference visible in it; ③ storage accounts must block public access with a minimum TLS 1.2, and all resources must carry owner/cost-center/env tags; ④ production apply requires approval, and what runs must be the approved plan itself; ⑤ drift is detected automatically every day, and an issue is opened automatically. Please complete it in the repo myapp-infra and prove each gate works with “fault drills”. (If you are using AWS, replace it with the Lesson 4 stack: IAM OIDC provider + default_tags; the remaining steps are the same.)
Pre-checks (Modules 0, 1)
cd ~/myapp-infra
gh repo view --json nameWithOwner,defaultBranchRef -q '.nameWithOwner + " " + .defaultBranchRef.name'
gh api "repos/$REPO/branches/main/protection" --jq '.required_status_checks.contexts'
gh api "repos/$REPO/environments" --jq '[.environments[].name]'
grep -c linux_amd64 azure/.terraform.lock.hcl || echo "Lock file is missing linux_amd64!"
(cd azure && terraform init -input=false >/dev/null && terraform plan -detailed-exitcode -input=false >/dev/null; echo "plan exit=$?")
yourname/myapp-infra main
["terraform-plan"]
["dev","production","staging"]
2
plan exit=0
Identities (Module 2): confirm id-tf-plan (subject: pull_request,ref:refs/heads/main) and id-tf-prod (subject: environment:production) exist, role assignments are correct, and the four variables are set:
for ID in id-tf-plan id-tf-prod; do echo "== $ID"; az identity federated-credential list -g $STATE_RG --identity-name $ID --query "[].subject" -o tsv; \
  az role assignment list --assignee $(az identity show -g $STATE_RG -n $ID --query principalId -o tsv) --all --query "[].roleDefinitionName" -o tsv; done
gh variable list; gh variable list --env production
gh secret list   # should only have INFRACOST_API_KEY, with no cloud keys at all
Policy and cost (Modules 4, 6): the repo should contain policies/tfpolicy/{storage,tags}.policy.hcl,policies/opa/{storage,storage_test,tags}.rego,azure/infracost-usage.yml, and they should all pass locally first:
conftest verify -p policies/opa
cd azure && terraform plan -policies=../policies/tfpolicy -out=tfplan && terraform show -json tfplan > plan.json \
  && conftest test plan.json -p ../policies/opa && infracost breakdown --path . --usage-file infracost-usage.yml | tail -3
Four workflows (Modules 2, 4, 5, 6): terraform-pr.yml (fmt/validate/plan -policies/conftest/comment),infracost.yml,terraform-deploy.yml (plan → artifact → production approval → apply the same plan),terraform-drift.yml (daily refresh-only + issue). All Actions are pinned by SHA and added to .github/dependabot.yml. Merge through one PR:
git switch -c ci/full-pipeline
git add .github policies azure/infracost-usage.yml
git commit -m "Full Terraform CI/CD with OIDC, policy gates, cost and drift"
git push -u origin ci/full-pipeline && gh pr create --fill
gh pr checks --watch && gh pr merge --squash --delete-branch
Fault drill A: policy gate (should be blocked): open a new PR that adds allow_nested_items_to_be_public = true storage account, and delete the cost-center tag. Expected: terraform-plan the check fails; the log shows both Terraform Policy and conftest denial messages, and the PR cannot be merged. After the fix, the check turns green and the Infracost comment shows the monthly cost of the new storage account.
Fault drill B: identity boundary (should be rejected): on a feature branch, temporarily edit the deploy workflow so the apply job runs on push pushes to that branch (without changing the environment). Expected: that branch is not a protected branch, so the production environment's branch policy rejects the deployment (“Branch … is not allowed to deploy to production”); even if the environment is removed,sub changes to ref:refs/heads/<branch>, and Entra returns AADSTS700213. Delete the branch after the drill.
Fault drill C: stale plan and drift: ① merge a normal change, and while apply waits for approval, run locally terraform apply -refresh-only -auto-approve, then approve; expected Saved plan is stale, re-run succeeds; ② az containerapp update … --max-replicas 10, manually trigger the drift workflow, and expect drift issue; after re-running the deployment to roll back, detect again,drift=0, close the issue.
Wrap-up: if you continue to Lesson 6, keep the repo, identities and rg-tfstate; otherwise run the Module 8 cleanup script. In either case, confirm min_replicas = 0, and delete the storage account created in the drill (through a PR) so nothing is left behind.
Acceptance checklist

Open-ended self-test (answer first, then expand the reference answers)

1. Describe the full authentication and execution chain of one apply job, from start to writing state.

The job is bound to the production environment and approved → the runner, using ACTIONS_ID_TOKEN_REQUEST_* requests a JWT from GitHub, with audience api://AzureADTokenExchange (sub=repo:…:environment:production) → azurerm provider/backend exchanges client_assertion with Entra for an access token (the federated credential checks iss/sub/aud) → init: reads the state blob via Entra authentication and installs providers per the lock file → downloads the tfplan artifact → apply: acquires the blob lease lock, checks the lineage/serial of the plan and the state, and core calls the provider's ApplyResourceChange (gRPC) per the plan → ARM PUT → writes new state (serial+1) → releases the lease.

2. Why can't the plan on a PR be used directly as the basis for apply?

A PR plan is based on the PR branch and the state at that time; before or after merging, other PRs may land and someone may change resources by hand, so the plan may be stale. The correct approach is to re-plan on the merged main, save that plan, approve this plan, and apply the same file.

3. Why does the plan identity need write permission on the state container? What risk does this create, and how do you mitigate it?

The plan needs to acquire the state lock (a Blob lease is a write operation). Risk: the plan identity could in theory rewrite state. Mitigation: scope it to the tfstate container; enable Blob versioning / soft delete for recovery; for drift detection, use -lock=false identities with read-only permission where possible; audit Blob write operations.

4. How would you choose between Terraform Policy, Sentinel and OPA?

New project, mainly Terraform: Terraform Policy (HCL, GA in 1.17, works with both CLI and HCP, can check providers/modules before download). Existing Sentinel assets and on HCP: keep using them and migrate gradually. Need unified rules across Terraform/K8s/Dockerfile: OPA. Whichever you pick, pair it with static scanning and a cloud-native policy backstop.

5. After drift detection finds a difference, which situation suits each of the four dispositions?

Roll back (re-run the deployment): unapproved changes and security-related issues; adopt (change the code): a necessary break-glass fix; ignore (ignore_changes at the attribute level): attributes legitimately managed by other systems; accept into state (apply -refresh-only): only the records need updating, for example handling after a resource has been deleted.

6. When should your team migrate from self-hosted GitHub Actions to HCP Terraform or Stacks?

When the number of workspaces/repos grows so that the staff cost of maintaining workflows, identities and backends exceeds the subscription cost; when you need platform capabilities such as health assessments, policy-set coverage for audits and team permissions; when multi-environment, multi-region layered dependency orchestration becomes complex (Stacks). Constraints: billed per managed resource, no OpenTofu support, data in SaaS (or self-hosted TFE).

Final quiz (12 questions, covering all modules)

Sources and version notes

Verification sources for all technical facts in this lesson (verified 2026-11-15)
TopicVerified conclusionSource (accessed 2026-11-15)
Terraform CLILatest v1.17.2 (2026-11-11); 1.17.0 (2026-10-21): Terraform Policy GA,plan/apply/query 's -policies no longer requires an experimental build; -minimal-refresh; provider requirements can use variables/locals; test 's mock_provider supports ephemeral resources; alpha experiment: -allow-deferral. 1.17.1 fixes “always evaluating module policies on destroy plans” and Stacks policy result reportingTerraform v1.17 CHANGELOG
terraform plan option-detailed-exitcode: 0 no differences / 1 error / 2 differences; -minimal-refresh refresh-only plan only updates resource records; -out Saves the plan in an opaque formatterraform plan
Terraform PolicyHCL; file .policy.hcl, test .policytest.hcl; block policy (including required_providers),resource_policy,provider_policy,module_policy,input,locals; enforce { condition, error_message, info_message }; enforcement_level advisory / mandatory_overridable / mandatory (default mandatory); attrs./prior_attrs./meta.; core:: functions; evaluation stages setup / plan / after apply; tfpolicy test --policies=… --tests=…Terraform policy · Write policies · Reference · Tests
Policy framework comparisonSentinel (advisory/soft/hard-mandatory), OPA (in HCP: pass/fail, advisory/mandatory), and Terraform Policy differ in language, enforcement levels, related queries, and evaluation timing; HashiCorp recommends Terraform Policy and has not announced deprecation of Sentinel or OPACompare policy frameworks
GitHub Actions versionsUsing git ls-remote to verify tag → commit: setup-terraform v4.0.1 = dfe3c3f8… (v4.0.0 and later require Node.js 24); checkout v7.0.1 = 3d3c42e5…; upload-artifact v7.0.2 = cf430e03…; download-artifact v8.0.2 = 9000827c…; azure/login v3.1.0 = a641126d… (the commit the annotated tag dereferences to); configure-aws-credentials v6.3.0 = e1253824…; infracost/actions v3 = e9d6e6cd…cross-check against each repository's releases page and git ls-remote
Provider versionslatest azurerm 5.14.0 (2026-11-13), last 4.x is 4.81.0; aws 6.73.0 (2026-11-11); azuread 3.10.0. azurerm_federated_identity_credential Arguments: name, user_assigned_identity_id, audience, issuer, subjectregistry.terraform.io · provider source documentation
HCP Terraform billingThe legacy free plan ended 2026-03-31; enhanced Free: up to 500 managed resources, unlimited users, includes SSO, Sentinel/OPA, run tasks, and agents; Essentials about $0.10, Standard about $0.47, Premium about $0.99 (per resource per month)HashiCorp blog post, 2025-12-17 · Pricing
Health assessmentsAvailable on Standard and Premium; Remote/Agent execution modes; requires at least one successful apply and a recent successful run; drift detection needs 0.15.4+, continuous validation needs 1.3.0+Health assessments
Terraform StacksGA at HashiConf 2025 (September); .tfcomponent.hcl / .tfdeploy.hcl; each Stack supports 20 deployments / 100 components / 10,000 resources, 20 upstream / 25 downstream Stacks; not available on legacy team plans; identity_token,store, deployment group; terraform stacks Command group (TFE requires TF_STACKS_HOSTNAME); Linked Stacks was announced as betaStacks · Deployment config · terraform stacks · HashiConf 2025
InfracostClassic CLI v0.10.49 (2026-11-10), with v2 migration prompts since v0.10.45; Infracost 2.0 CLI (infracost/cli): auth login,setup,scan,inspect, with CI using INFRACOST_CLI_AUTHENTICATION_TOKENinfracost releases · infracost/cli
conftestLatest v0.71.1 (2026-10-06)conftest releases
OIDC mechanicsGitHub issuer, sub format (pull_request / ref / environment), Azure federated credentials, and the AWS IAM OIDC provider and trust conditionsGitHub OIDC · Entra Workload ID · AWS IAM OIDC

Video verification notes

The following videos were verified for title and channel via the YouTube oEmbed endpoint (2026-11-15): Festive Tech Calendar “Day 15 - Terraforming with GitHub Actions with Ned Bellavance” (1G0th5szgg0); Engineering with Morris “Terraform Automation with Atlantis” (xni4cSVDKcY); “GitHub Actions with AWS and OIDC Integration | Wahl Network” (SXGTSHxm9js; the channel display name returned by oEmbed is Uglarvisk); vlogize “Configuring Manual Approval in Terraform Deployments with GitHub Environments” (NRLowqLq-z4); HashiCorp “Getting into Terraform, Part 9: HCP Terraform” (6U0wC-835Nc), “Terraform Cloud Learn Lab: Validate Infrastructure, Detect Drift & Enforce OPA Policies” (AvZjGjPLV8Y), “Terraform Stacks is here!” (2uoY3iQ9Bgg), “Introduction to HashiCorp Terraform with Armon Dadgar” (h970ZBgKINg), “5 Lessons Learned From Writing Over 300,000 Lines of Infrastructure Code” (RTEgE2lcyk4); Tech Tutorials with Piyush “Day 25/28 - HCP Terraform Explained” (LmWq51m9DJQ); Ned in the Cloud “Terraform Cloud - Managing Your Workspaces with Projects” (tDexI54Cjs8), “Open Policy Agent and Terraform - Examining a Terraform Execution Plan with Rego” (YAFICF55aKE), “Using OPA with Terraform - Rego Basics” (DpUDYbFK4IE), “Getting Started with Terraform Stacks” (LMVo_Twzid8); Azure Terraformer “TERRAFORM STACKS announced at HashiConf 2023!!!” (LUIYTTp2Prg); Anton Babenko “Infracost - Cloud cost estimates for Terraform” (_UsK-pKYrPs); Talking tech with Techielass “Estimate Azure Costs from Terraform with Infracost” (XHGSV0Z5iu0); Fireship “Terraform in 100 Seconds” (tomUWcQ0P3k); DevOps Directive “Complete Terraform Course - From BEGINNER to PRO!” (7xngnjfIlK4). oEmbed does not return durations or publish dates, so the cards show no durations. No verified dedicated video was found for Terraform Policy (GA 2026-10). All videos are in English, and most were recorded before this course's version; action versions and product names follow this course.

Voice narration notes

The “Voice” tab uses the browser's Web Speech API (speechSynthesis, en-US) to read the narration aloud in real time; English terms use en-US pronunciation, and the result depends on the voices installed on the system. The environment that generated this course cannot call a TTS service, so no MP3 is embedded; for offline audio, pass the narration script to a TTS service such as Azure AI Speech.

Known limitations

  • The commands and workflows in this lesson have not been run in a real environment; the IDs, URLs, run numbers, times, costs, and Lock IDs in the “expected output” are sample values.
  • The violation output format of Terraform Policy,core::alltrue/core::contains/core::keys availability is inferred from the official note that most built-in functions are available, and the sample output is illustrative; first run tfpolicy validate and terraform plan -help to confirm.
  • The subject format for Azure dynamic credentials in Stacks has not been verified word for word; the course requires configuring it per the official “Authenticate a Stack” documentation; for the tier required by Linked Stacks and deployment groups, follow the current official documentation and pricing page.
  • The number of concurrent runs on the HCP Terraform Free tier comes from third-party sources; check the console. Feature matrices by tier may change.
  • No clear long-term support timeline for Infracost 2.0 CLI CI integration or for the classic CLI (breakdown/diff/comment) was found on the official pages; this lesson demonstrates the classic CLI and notes that 2.0 exists.
  • This lesson's examples use azurerm ~> 5.0 (latest 5.14.0); if your Lesson 3 stack is still on 4.x, first upgrade following the 5.0 upgrade guide. resource_provider_registrations values and defaults depend on the documentation for the version you use.
  • Steps, durations, and prices in the animation are illustrative values that explain the mechanism.