Terraform Hour 5: Automated Operations — CI/CD and Policy Governance
- 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
subclaim: PRs, the main branch and the production environment each get their own identity. - Write production-grade workflows: pin Actions by commit SHA,
permissionsleast privilege,concurrencyserialize runs, upload the plan as an artifact, comment a plan summary on PRs,environmentand 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
-policiesGA),Sentinel,OPA/conftest (checkingterraform show -jsonthe plan JSON), so choose the right one. - Set up drift detection (scheduled job +
plan -detailed-exitcodeor 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
| # | Time | Module | Core content | Animation / interaction | Lab |
|---|---|---|---|---|---|
| 0 | Before class | Setup: GitHub repository and cloud identity | Put the Hour 3 Azure stack into a Git repository; prepare the gh CLI, remote state and subscription permissions | Environment self-check checklist | Repository myapp-infra Push succeeds |
| 1 | 00–07 | GitOps-style Terraform workflow | PR → plan → review → apply, environment promotion, separation of duties, branch protection, CODEOWNERS | Change lifecycle state machine (including the consequences of “bypassing the process”) | Branch protection + CODEOWNERS |
| 2 | 07–17 | GitHub Actions + OIDC plan and apply | OIDC token exchange, Azure federated credentials, AWS OIDC provider, plan artifact, PR comments, environment approval, concurrency, SHA pinning | Core animation: the full pipeline of one PR | Two-stage workflow: PR plan / main plan → approval → apply |
| 3 | 17–25 | HCP Terraform workspaces and runs | Organization/project/workspace, VCS vs CLI vs API driven, remote runs, variable sets, dynamic credentials, run tasks, free/paid tiers | Stage flow of one remote run | cloud block + dynamic credentials |
| 4 | 25–33 | Policy as code | Terraform Policy (.policy.hcl), Sentinel, OPA/conftest, enforcement levels, comparison of the three | The same plan evaluated by three engines | conftest + Terraform Policy gate |
| 5 | 33–40 | Drift detection and continuous compliance | Drift sources -refresh-only and -detailed-exitcode scheduled jobs, HCP health assessments, remediation decisions | Drift simulator (portal manual change → detection → remediation) | Nightly drift-detection workflow + automatic issue creation |
| 6 | 40–47 | Cost estimation and tag governance | Infracost (v0.10 and 2.0 CLI), HCP cost estimation, AWS default_tags, Azure tag inheritance, policy-enforced tags | Tag merge and cost-diff calculator | PR cost comments + tag policy |
| 7 | 47–54 | Stacks and multi-deployment orchestration | Stacks status,.tfcomponent.hcl / .tfdeploy.hcl, deployment, identity_token, limitations; alternatives | Multi-deployment orchestration and deferred changes | Read and rewrite a minimal Stack |
| 8 | 54–60 | Hours 1–5 recap, self-check and cleanup | Knowledge map of the five lessons, common CI failure troubleshooting, cleaning up OIDC identities and resources | CI failure troubleshooting tree | Cleanup script |
| — | After class | Cheat sheet · Capstone lab | Build full CI/CD, policy gates and drift detection for the Hour 3 Azure stack | Final quiz (12 questions) | Capstone lab |
Knowledge Coverage Matrix
| Target skill | M1 | M2 | M3 | M4 | M5 | M6 | M7 | M8 | Key commands / configuration | Lab |
|---|---|---|---|---|---|---|---|---|---|---|
| Design a PR-driven change process and separation of duties | ✓ | ✓ | ✓ | · | · | · | · | ✓ | branch protection, CODEOWNERS, environments | M1, capstone lab |
| Cloud authentication without long-lived keys (OIDC) | · | ✓ | ✓ | · | · | · | ✓ | ✓ | id-token: write,ARM_USE_OIDC,role-to-assume | M2 |
| apply the reviewed plan file | ✓ | ✓ | ✓ | · | · | · | · | ✓ | plan -out,apply tfplan, upload-artifact | M2 |
| Use HCP Terraform remote runs | · | · | ✓ | ✓ | ✓ | ✓ | ✓ | · | cloud block,terraform login, variable sets | M3 |
| Policy-as-code gate | · | ✓ | ✓ | ✓ | ✓ | ✓ | · | ✓ | plan -policies,tfpolicy test,conftest test | M4, M6 |
| Drift detection and remediation | · | · | ✓ | · | ✓ | · | · | ✓ | plan -refresh-only -detailed-exitcode, schedule | M5 |
| Cost visibility and tag governance | · | · | ✓ | ✓ | · | ✓ | · | · | infracost diff,default_tags,tags_all | M6 |
| Multi-deployment orchestration (Stacks / pipelines) | ✓ | · | ✓ | · | · | · | ✓ | · | component,deployment,identity_token | M7 |
| Quick CI failure troubleshooting | · | ✓ | ✓ | ✓ | ✓ | · | · | ✓ | AADSTS700213, AccessDenied, Saved plan is stale | M8 troubleshooting tree |
What this lesson does not cover (and where to learn it)
| Topic | Why not in this lesson | Where to learn |
|---|---|---|
| Repo and environment directory layout, state splitting, cross-stack references | Belongs 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 parameters | Secrets governance topic | Lesson 6, Module 5 |
tflint, Trivy/Checkov static scanning and terraform test | Covered in Lesson 2; this lesson reuses it directly in the workflow | Lesson 2 Modules 6, 7 |
| Third-party TACOS platforms such as Atlantis, Spacelift, env0, Scalr | Same approach as this lesson (PR-driven + policy + approval); product details change quickly | See each vendor's official docs; m3 of this lesson gives the selection criteria |
| Terraform Enterprise self-hosted installation and operations | Platform team responsibilities | Terraform Enterprise documentation |
Large-scale performance tuning (parallelism,-minimal-refresh, splitting) | Belongs to optimization topics | Lesson 7 |
How to use these course materials
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.
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).
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.
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)
- CompletedHour 3 (Azure): resource group
rg-tf-lab(regioncanadacentral) running myapp (Container Apps), with state in an azurerm backend (this lesson assumes resource grouprg-tfstate, storage accountsttfstate<suffix>, containertfstate, keylab3/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
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.
Module 1 · GitOps-style Terraform workflow
- Draw the PR →
fmt/validate/lint→plan→ review → merge →applythe 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.
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 apply | How the GitOps workflow solves it |
|---|---|
| Everyone's Terraform/provider versions, variables and credentials differ, so results are not reproducible | CI uses a pinned version + lock file + the same variables, running on a clean runner |
| Long-lived high-privilege credentials are scattered across personal computers | Only 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 why | PR 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)
- Create a branch, open a PR: change
azure/*.tf. - 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). - Code review: approval from the platform team named in CODEOWNERS; branch protection requires all checks to pass.
- 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. - 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. - 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”. - Promotion: after dev succeeds, run the same steps on staging and prod (same commit SHA).
Comparison of the three apply timings
| Pattern | Approach | Pros | Risks | Example |
|---|---|---|---|---|
| Apply directly after merge | Automatically after merging to main apply -auto-approve | Simple; main always reflects the deployed state | The 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 code | Small teams, non-production |
| Apply before merge | Comment on the PR atlantis apply, then merge after it succeeds | main only contains code that has been applied successfully | Parallel PRs need locking (Atlantis locks per directory); unmerged code has already reached production | Atlantis default flow |
| After merge: plan → approval → apply the same plan | Re-plan on main and save it; after approval, apply that file | The executed change = the approved change; state changes automatically invalidate it | One extra wait; the plan file is a sensitive artifact | This 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 Actions | HCP Terraform (VCS-driven) | Atlantis | Argo CD / Flux | |
|---|---|---|---|---|
| Trigger | Workflow events | VCS webhook | PR webhook + comment commands | Controller polls Git |
| State and lock | Self-managed backend | Platform-managed | Self-managed backend + Atlantis directory locks | Not applicable (K8s objects) |
| Approval | environment required reviewers | Confirm & Apply / policy override | PR approval + apply requirement | Sync policy / PR |
| Policy | conftest / -policies Self-integrated | Sentinel, OPA, native Terraform Policy | conftest integration | Gatekeeper/Kyverno |
| Cost | Actions minutes | Billed per managed resource (see Module 3) | Self-hosted | Self-hosted |
-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
Flow chart: environment promotion and identity separation
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 / configuration | Purpose | Key parameters / notes |
|---|---|---|
terraform fmt -check -recursive | Format check (does not modify files in CI, only returns non-zero) | -diff Show diff |
terraform validate | Syntax and type validation (requires init -backend=false first) | -json Machine-readable |
terraform plan -out=tfplan -input=false | Generate and save the plan | -lock-timeout=5m,-var-file |
terraform apply -input=false tfplan | Apply the saved plan (no more prompts) | Reports stale when state changes |
gh api … /branches/main/protection | Configure branch protection | Required checks, required reviews, CODEOWNERS |
.github/CODEOWNERS | Required reviewers for specified paths | Requires pairing with “Require review from Code Owners” |
gh api … /environments/production | Create environments, reviewers, branch restrictions | reviewers,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)
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
gh api scripts from the “Commands” page.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.
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.
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]'
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
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.
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.
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.
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.
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.
Module 2 · GitHub Actions + OIDC plan and apply
- 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 readssubclaims, 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 →environmentapproval → download andapplythe same plan; useconcurrency, leastpermissions, pin Actions by SHA.
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
| Claim | Example | Purpose |
|---|---|---|
iss | https://token.actions.githubusercontent.com | The cloud uses it to find the OIDC discovery document and signing public keys (JWKS) |
aud | Azure: api://AzureADTokenExchange; AWS: sts.amazonaws.com | Prevents a token issued for A from being used for B |
sub | repo:yourname/myapp-infra:pull_requestrepo:yourname/myapp-infra:ref:refs/heads/mainrepo: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 target | on a user-assigned managed identity (or app registration) federated identity credential: issuer + subject + audience | Account-level IAM OIDC identity provider + role trust policy (sts:AssumeRoleWithWebIdentity) |
| subject matching | Default 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 exchange | POST login.microsoftonline.com/{tenant}/oauth2/v2.0/token,client_assertion=<GitHub JWT> | STS AssumeRoleWithWebIdentity, returns temporary AK/SK/SessionToken |
| On the Terraform side | ARM_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 token | aws-actions/configure-aws-credentials ; it writes temporary credentials into environment variables, and the provider and S3 backend use these directly |
| for authorization | RBAC 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-artifactto uploadtfplan(setretention-daysto 1–5 days); the apply job runs on a brand-new runner andinitruns init (same Terraform version, same lock file), then downloads andapply 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, norenvironment:productionan 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
v4to a malicious commit (this is what happened in the March 2025 tj-actions/changed-files incident). Write it asuses: 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 itid-token: write,pull-requests: write. - setup-terraform's wrapper: the default
terraform_wrapper: truewraps the terraform binary to expose stdout/stderr/exitcode as step outputs. When you need to redirectterraform show -jsonto a file or handle the exit code yourself, set it tofalseis 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_requestevent cannot getid-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 usepull_request_targetto check out and run a fork's code: this hands your permissions to a stranger's Terraform configuration (externaldata sources and malicious providers can both run arbitrary commands). - A PR plan is also code execution: plan runs providers and
external/httpdata 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 federation | Service principal keys / access keys stored in Secrets | Self-hosted runner + managed identity | |
|---|---|---|---|
| Leak risk | Very low (short-lived tokens, bound to aud/sub) | High (long-lived) | Medium (compromising the runner grants the identity) |
| Granularity | By branch / environment / PR | One key for all jobs | By runner pool |
| Operations | No rotation | Regular rotation | Maintain runners |
| Suitable for | GitHub-hosted runners accessing public clouds (preferred) | Legacy systems that do not support OIDC | Needs access to a private network (e.g., state behind a private endpoint) |
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)
Flow chart: two-stage workflow (plan on PR / plan after merge → approval → apply)
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.
Core commands and configuration
| Command / configuration | Purpose | Key parameters |
|---|---|---|
az identity create | Create user-assigned managed identity | -g -n -l; output clientId,principalId |
az identity federated-credential create | Add federated identity credential | --issuer --subject --audiences |
az role assignment create | RBAC authorization | --assignee-object-id --assignee-principal-type ServicePrincipal --role --scope |
aws iam create-open-id-connect-provider | Register GitHub OIDC provider (once per account) | --url --client-id-list |
aws iam create-role | Create a role that web identities can assume | --assume-role-policy-document |
gh variable set | Set repository/environment variables (client ID is not a secret) | --env production |
gh run watch / gh run view --log-failed | Track 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.
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)
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).
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
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)
}
}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.
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.
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.
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://AzureADTokenExchange2. 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
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
Official docs
- GitHub: About security hardening with OpenID Connect
- Microsoft Entra Workload ID federation
- azurerm: Authenticating using OIDC
- AWS: Create an OIDC identity provider
- hashicorp/setup-terraform
- GitHub: Control the concurrency of workflows and jobs
Video storyboard script (about 120 seconds)
This courseware cannot generate video or MP3 directly, so a storyboard and narration script are provided instead.
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.
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.
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.
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.
Module 3 · HCP Terraform workspaces and runs
- 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 (
cloudblock), 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.
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
| Concept | Description |
|---|---|
| Organization | Boundaries of billing, SSO, teams, policy sets, and VCS connections |
| Project | A grouping of workspaces, used for authorization (team permissions on projects) and for variable set scope |
| Workspace | One state + variables + run history + settings (Terraform version, working directory, execution mode, auto-apply, trigger paths). Not the same as the CLI terraform workspace . |
| Variable set | A 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). |
| Run | One plan (optionally followed by apply). A speculative plan only plans and cannot apply (used on PRs). |
| Run task | Calls 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 set | A 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
tfeprovider 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
| Workflow | Trigger | PR experience | Best for |
|---|---|---|---|
| VCS-driven | The 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 link | Simplest and most “GitOps”; the first choice for most teams |
| CLI-driven | Write the cloud block, runs locally or in CI terraform plan/apply, the configuration is uploaded and runs on a remote runner, with logs streamed back | Decided by your CI | You want to keep your existing CI but still use remote state, policies, and credentials; local development and debugging |
| API-driven | CI uploads a configuration version through the API and creates a run | Implemented 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 mode | Where plan/apply runs | state | Description |
|---|---|---|---|
| Remote (default) | HashiCorp-managed runner | Platform | Needs access to public APIs; dynamic credentials can be used |
| Agent | HCP Terraform Agent in your network (pulls tasks) | Platform | Accesses private networks and local resources; no inbound ports to open |
| Local | Your machine or CI | Platform (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)
| Tier | Price | Key points |
|---|---|---|
| Free (Enhanced) | Free | Up 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. |
| Essentials | About $0.10 / resource / month | Remote state, VCS, projects, remote runs, private registry, team management |
| Standard | About $0.47 / resource / month | Builds on Essentials, adding no-code modules, team notifications, and more; Health assessments (drift detection + continuous validation) are available from Standard |
| Premium | About $0.99 / resource / month | Full 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
| Capability | DIY GitHub Actions (Module 2) | HCP Terraform |
|---|---|---|
| state + locking | azurerm/S3 backend | Built in, with version history and rollback (state versions) |
| Credentials | GitHub OIDC | Dynamic credentials (plan/apply separated) |
| Approval | environment reviewers | Confirm & Apply, controlled by team permissions |
| Policy | Integrate conftest yourself / -policies | Policy sets, enforcement levels, and override auditing |
| Drift | Scheduled workflow (Module 5) | Health assessments (from Standard) |
| Multi-environment orchestration | Chained workflows | Run triggers, Stacks (Module 7) |
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
Flowchart: VCS-driven vs CLI-driven
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 / configuration | Purpose | Notes |
|---|---|---|
terraform login | Get an API token and write it to ~/.terraform.d/credentials.tfrc.json | In CI, use the environment variable TF_TOKEN_app_terraform_io |
cloud { … } | CLI-driven workspace | organization,workspaces { name | tags, project } |
terraform init -migrate-state | Migrate state from an existing backend to HCP | Back up the state before migrating |
terraform plan / apply | Run remotely | Ctrl+C only disconnects the streamed output; the remote run may keep going |
.terraformignore | Controls which files are uploaded | Syntax is similar to .gitignore |
tfe provider | Manage organizations/projects/workspaces/variable sets/teams as code | tfe_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)
yourorg) and a project myapp. New organizations use Enhanced Free (free up to 500 managed resources).TFC_AZURE_RUN_CLIENT_ID.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.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.
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.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.
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 changes2. 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-terraformA 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
Official docs
- Workspaces
- Remote operations
- Dynamic provider credentials
- Run tasks
- Continuing HCP Terraform's enhanced free tier experience (2025-12-17)
Video storyboard script (about 90 seconds)
This courseware cannot generate video or MP3 directly, so a storyboard and narration script are provided instead.
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.
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.
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.
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.
Module 4 · Policy as code: Terraform Policy / Sentinel / OPA
- 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 checksterraform show -jsonoutput). - 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.
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 Policy | Sentinel | OPA (Rego) | |
|---|---|---|---|
| Language | HCL (policy,resource_policy,provider_policy,module_policy,input,locals) | Sentinel DSL | Rego (general-purpose policy language) |
| Status | Terraform 1.17.0 (2026-10-21) GA; CLI plan/apply/query -policies; HCP Terraform policy sets | Built into HCP Terraform / Enterprise; Sentinel CLI for local testing | CNCF graduated project; native HCP support; for local/CI, use conftest or opa eval |
| input | Reference attributes directly by resource type: attrs.,prior_attrs.,meta. | tfplan/v2,tfconfig/v2,tfstate/v2,tfrun import | plan JSON (resource_changes[]); in HCP it is input.plan |
| Enforcement level | advisory / mandatory_overridable / mandatory (default: mandatory) | advisory / soft-mandatory / hard-mandatory | HCP: advisory / mandatory; conftest: deny / warn |
| Cross-resource lookups | built in core::getresources,core::getdatasource | manual traversal and matching | write comprehensions over the plan JSON |
| Evaluation timing | Can check provider/module sources and versions at the init stage (before download); after plan; values known only after apply are reported after apply | After plan (policy check stage) | After plan |
| Testing | tfpolicy test (.policytest.hcl) | sentinel test | opa 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_eachand 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
- In PR and deploy workflows:
terraform plan -policies=../policies/tfpolicy -out=tfplan(Terraform Policy, no experimental build required since 1.17). - Same plan:
terraform show -json tfplan > plan.json→conftest test plan.json -p ../policies/opa(OPA). - If any check fails, the job fails: the PR cannot merge, and the apply job does not start.
- 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.
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
Flowchart: how enforcement levels determine the outcome
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).
Core commands
| Command | Purpose | Notes |
|---|---|---|
terraform plan -policies=DIR | Evaluate Terraform Policy at plan time | 1.17 GA; apply,query also supported; check the argument form in terraform plan -help the official reference. |
tfpolicy validate --policies=DIR | Validate policy syntax | Install the tfpolicy CLI from the official Install page |
tfpolicy test --policies=DIR --tests=DIR | Run .policytest.hcl Test | Input variables are available TFPOLICY_INPUT_<name> |
terraform show -json tfplan | Generate plan JSON | Contains plaintext sensitive values; protect it |
conftest test plan.json -p DIR | Check the plan with Rego | default namespace main; --all-namespaces,-o github |
conftest verify -p DIR | Run Rego unit tests | test_ Prefix rules |
sentinel apply / sentinel test | Run and test Sentinel locally | Needs 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)
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
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.
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.
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).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).
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
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
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
- Terraform policy
- Compare policy frameworks
- Policy reference
- Sentinel for Terraform
- conftest
- JSON output format
Video storyboard script (about 100 seconds)
This courseware cannot generate video or MP3 directly, so a storyboard and narration script are provided instead.
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.
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.
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.
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.
Module 5 · Drift detection and continuous compliance
- Distinguish “drift” (real resources diverging from state) from “unapplied changes” (code diverging from state), and know
planandplan -refresh-onlywhat each one can see. - Use a scheduled task +
-detailed-exitcode/ the plan JSON'sresource_driftto build drift detection and automatically open issues. - Understand HCP Terraform health assessments (drift detection + continuous validation:
checkblocks and pre/post conditions), along with their prerequisites, and the four ways to handle drift: roll back, adopt, ignore, or import.
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.
| Command | What is compared | Typical use |
|---|---|---|
terraform plan | Code vs (refreshed) real state: both drift and unapplied code changes appear | Pre-deployment review |
terraform plan -refresh-only | State vs real resources: only checks drift, ignoring code | Drift detection; after confirmation, use apply -refresh-only to accept into state |
terraform plan -refresh=false | Code vs state, no cloud API access | Fast 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/deployIfNotExistseffect (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
- GitHub Actions
schedule(cron, UTC) runs once a day with a read-only plan identity. terraform plan -refresh-only -out=drift.tfplan, then usesterraform show -json drift.tfplan | jq '.resource_drift | length'to count the drifted resources, which is clearer than relying on the exit code alone.- It also runs a regular
plan -detailed-exitcode: exit code 2 means “code and reality differ” (either drift, or changes merged but not applied). - When differences exist, automatically open (or update) an issue labeled
driftissue and mention the on-call engineer or CODEOWNERS.
B. HCP Terraform health assessments
- Includes drift detection and continuous validation (re-evaluates
checkblocks, 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
| Option | Action | When 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 changes | A break-glass fix was truly necessary |
| Ignore | lifecycle { ignore_changes = [tags["CreatedBy"], template[0].max_replicas] } | Attribute is legitimately managed by another system (autoscaling, tags added by Azure Policy) |
| Accept into state | terraform apply -refresh-only | Only 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-refreshfor 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.
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
Flowchart: automated drift detection and handling
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.
Core commands
| Command | Purpose | Notes |
|---|---|---|
terraform plan -refresh-only | Show drift only | Can add -out Save |
terraform apply -refresh-only | Write the detected real values into state | Does not modify any cloud resources; review before running |
terraform plan -detailed-exitcode | 0 no differences / 1 error / 2 differences | In scripts, you must set +e capture |
terraform show -json PLAN | jq '.resource_drift' | Get the drift list in structured form | Each item contains address and before/after |
-lock=false | Do not acquire the state lock during read-only detection | Avoids blocking deployments; do not use for apply |
gh issue create / comment | Report 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)
terraform-drift.yml from the Commands page and merge it to main via a PR.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
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
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 …".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).
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
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
Official docs
- Health assessments
- terraform plan (-refresh-only, -detailed-exitcode)
- Manage resource drift (tutorial)
- Checks
Video storyboard (about 80 seconds)
This courseware cannot generate video/MP3 directly, so the storyboard and narration script are provided instead.
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.
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.
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.
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.
Module 6 · Cost estimation and tag governance
- 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_tagsandtags_allAzure locals merging, tag inheritance, enforcing required tags via policy, and a cloud-native policy backstop.
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)
| Tool | Status | Usage |
|---|---|---|
| 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 v2 | infracost 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 similar | For CI authentication, use INFRACOST_CLI_AUTHENTICATION_TOKEN; for command details, see its README |
| HCP Terraform cost estimation | Enabled in workspace settings; supports some resource types on AWS/Azure/GCP | a “Cost estimation” stage in the run; Sentinel can read it tfrun.cost_estimate |
| Cloud vendor calculators / budget alerts | Azure Pricing Calculator, AWS Pricing Calculator; Azure Cost Management budgets, AWS Budgets | Beyond estimation,after-the-fact control; must be configured together |
Why: why look at cost at the PR stage
- Changing the size from
Standard_D2s_v5toStandard_E16s_v5In 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:
- Default injection: the AWS provider's
default_tagsblock merges tags automatically into all resources that support tags; the result goes in the read-only attributetags_all(resource-leveltagstags with the same key override defaults). The azurerm provider has no equivalent provider-level default tags, so the usual approach is localslocals { tags = {...} }+merge(local.tags, {...}), or enforce it in an internal module through atagsvariable. - Policy enforcement: Terraform Policy / OPA checks required keys at the plan stage (AWS checks
tags_all, since default tags appear only there). - 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).
| AWS | Azure | |
|---|---|---|
| Provider default tags | default_tags → tags_all | None; locals + merge / module convention |
| Key case | Case-sensitive | Keys are case-insensitive (values are case-sensitive) |
| Cloud enforcement | Tag Policies (canonical values) + SCP (deny creation of untagged resources, per service support) | Azure Policy deny / modify / append |
| Cost allocation | Requires activating cost allocation tags in Billing | Cost 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.
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
Flowchart: AWS default_tags merge rules
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).
Core commands
| Command | Purpose | Notes |
|---|---|---|
infracost auth login | Get a free API key (v0.10) | Used in CI INFRACOST_API_KEY |
infracost breakdown --path DIR|plan.json | Full cost breakdown | --format json --out-file,--usage-file |
infracost diff --path DIR --compare-to base.json | difference from the baseline | Most used in PRs |
infracost comment github | Comment the result on the PR | --behavior update Keep only one comment |
infracost generate config | Generate for a monorepo infracost.yml | multi-project |
infracost scan / inspect | Scan and view with the Infracost 2.0 CLI | See 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)
infracost auth login infracost configure get api_key | gh secret set INFRACOST_API_KEY
infracost.yml,infracost-usage.yml and policies/opa/tags.rego (the conftest step in Module 4 runs it automatically).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"}
…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).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.
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
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
Official docs
- Infracost docs
- infracost/cli (2.0)
- AWS provider: Resource tagging (default_tags)
- HCP Terraform cost estimation
- Azure: Assign policy definitions for tag compliance
Video storyboard (about 80 seconds)
This courseware cannot generate video/MP3 directly; the storyboard and narration script are provided instead.
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.
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.
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.
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.
Module 7 · Stacks and multi-deployment orchestration
- 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_HOSTNAMEsetting 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).
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 / blocks | Purpose |
|---|---|
*.tfcomponent.hcl: component | references a module (source), passes inputs, and specifies providers; can be expanded with for_each (e.g., multi-region) |
*.tfcomponent.hcl: provider | Providers 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_providers | Stack-level inputs, outputs and provider dependencies (the lock file is generated by terraform stacks providers-lock ) |
*.tfdeploy.hcl: deployment | a deployment target and its inputs; each deployment has its own independent state |
*.tfdeploy.hcl: identity_token | generates an OIDC JWT for the deployment (e.g., audience = ["aws.workload.identity"]), passed via identity_token.x.jwt to the provider |
*.tfdeploy.hcl: store | reads values from an HCP variable set (e.g., store "varset" "api_keys" { … }) |
*.tfdeploy.hcl: deployment_group | sets 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 Stacks | an 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_HOSTNAMEwith the Stacks CLI. There is no“apply a Stack purely locally” workflow. - CLI:
terraform stacksCommand group:init,validate,fmt,providers-lock,create,list,diagnostics,version, and subcommandconfiguration,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/countdepends 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-deferralis 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
- Push the Stack configuration → HCP creates a new configuration version.
- Generate a plan for each deployment (within each deployment, components are ordered by dependency).
- Approve by the rules of the deployment / deployment group (for example, dev auto-approves, prod is manual).
- Apply; if deferred changes exist, later rounds keep planning until convergence.
When: when to use Stacks and when not to
| Approach | Good fit | Not a fit |
|---|---|---|
| Stacks | Already on HCP Terraform; the same components deployed to multiple environments/regions/accounts; tightly coupled layers | Not using HCP/TFE; need OpenTofu; a single Stack over 20 deployments (split it) |
| Multiple workspaces + run triggers | Team already knows workspaces; loosely coupled layers | Lots 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 targets | Needs a dependency graph across states and partial retries |
| Terragrunt (third-party) | DRY backend/provider generation,run --all dependency orchestration; supports OpenTofu | Want to use only the HashiCorp official toolchain |
Architecture diagram: component × deployment
Flowchart: deferred changes
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
| Command | Purpose |
|---|---|
terraform stacks init | Initialize the Stack and prepare the configuration directory (downloads providers, etc.) |
terraform stacks providers-lock | Write the dependency lock for the providers configured in the Stack |
terraform stacks validate | Validate local component and deployment configuration |
terraform stacks fmt | Format .tfcomponent.hcl / .tfdeploy.hcl |
terraform stacks create / list | Create / 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 diagnostics | Get 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)
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.terraform stacks init,providers-lock,fmt,validate, then fix all diagnostics.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)?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.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.
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.jwtYour 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
Official docs
- Terraform Stacks
- Define deployment configuration
- terraform stacks command
- HashiConf 2025 release post (Stacks GA)
Video storyboard (about 80 seconds)
This courseware cannot generate video/MP3 directly; the storyboard and narration script are provided instead.
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.
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.
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.
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.
Module 8 · Recap of the first five hours, self-check and cleanup
- 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.
What: knowledge map of the first five hours
| Lesson | Core skills | How it appears in this lesson's pipeline |
|---|---|---|
| Lesson 1 core basics | HCL, providers and lock file, resource dependency graph, variables/outputs, state, CLI workflow | init -lockfile=readonly,plan -out,-detailed-exitcode |
| Lesson 2 production readiness | modules, remote state and locking, for_each, moved/import/removed, validation/check, terraform test, static scanning, version constraints | fmt/validate/tflint/test in the PR; check blocks participate in continuous validation |
| Lesson 3 Azure | azurerm authentication, azurerm backend, VNet, Container Apps, managed identity, AVM | pipeline-managed azure/ stack; managed identity + federated credential |
| Lesson 4 AWS | aws provider, S3 backend use_lockfile, VPC, ECS Fargate, IAM | IAM OIDC provider,default_tags,tags_all |
| Lesson 5 automation and operations | GitOps workflow, OIDC, two-stage workflow, HCP Terraform, policy as code, drift, cost and tags, Stacks | Integrated 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
- Trigger and permissions: is the workflow triggered (paths, branch, fork)?
permissionsDoes it includeid-token: write? - Cloud authentication: OIDC
sub/audsubject match? Has the role assignment propagated? (AADSTS700213, AccessDenied, AuthorizationFailed) - backend / state: Blob data role, lock held, state modified by someone else (403, state lock, stale plan).
- Provider and lock file: platform hashes, version constraints,
-lockfile=readonly, Terraform version mismatch. - The plan itself: configuration errors, insufficient permissions to read some resources (listSecrets), resource provider not registered.
- 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-infrarepo, state storage account and workflow structure; keep the repo andrg-tfstate, and clean up only the usage-billed workloads.
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
Flowchart: layered diagnosis of CI failures
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.
Cleanup commands (run in order)
| Object | Command | Notes |
|---|---|---|
| Federated credential | az identity federated-credential delete | Revoke trust first |
| Role assignment | az role assignment delete --assignee OID | Deleting the identity also invalidates the assignments, but leaves “unknown identity” stale entries |
| Managed identity | az identity delete | in rg-tfstate |
| Workloads | terraform destroy / deploy workflow | Preferably through the pipeline (practice approving the delete change) |
| GitHub | gh variable delete,gh api -X DELETE …/environments/X | or delete the entire repo |
| HCP | UI: delete the workspace/Stack | destroy its resources first |
| AWS (if done) | aws iam delete-role,delete-open-id-connect-provider | detach 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)
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.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.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.
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 tableA 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)
Official docs
- Automate Terraform with GitHub Actions (tutorial)
- Dependency lock file
- az identity federated-credential
Video storyboard (about 90 seconds)
This courseware cannot generate video/MP3 directly; the storyboard and narration script are provided instead.
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.
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.
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.
Command cheat sheet
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.0HCP 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|applyPolicy 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 testDrift 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 validateQuick troubleshooting table
| Symptom / error | Layer | Most likely cause | Quick fix |
|---|---|---|---|
| Unable to get ACTIONS_ID_TOKEN_REQUEST_URL | Trigger/permissions | Missing id-token: write or fork PR | Job-level permissions; skip forks |
| AADSTS700213 No matching federated identity record | Authentication | sub mismatch (environment vs. ref) | Add a federated credential for the sub in the error |
| Not authorized to perform sts:AssumeRoleWithWebIdentity | Authentication | Trust policy sub/aud conditions, OIDC provider missing | Check the conditions and provider ARN |
| 403 AuthorizationPermissionMismatch (state) | backend | Missing Storage Blob Data Contributor | Container-scoped grant; wait for propagation |
| state blob is already locked | backend | Concurrent runs / leftover cancel | concurrency; force-unlock after confirming |
| doesn't match any of the checksums … lock file | provider | Lock file missing platform hashes | providers lock -platform=… |
| plan file was created by Terraform X, but this is Y | provider | Two jobs use different versions | Unify TF_VERSION |
| AuthorizationFailed … listSecrets / register/action | plan | Insufficient Reader / RP registration | Custom role; resource_provider_registrations = "none" |
| Process completed with exit code 2 | plan | -detailed-exitcode uncaught | set +e handling |
| FAIL - plan.json - main - … | Gate | Policy violation | Fix the configuration or go through the exception process |
| Saved plan is stale | apply | State changed during approval | Re-run the workflow |
| RequestDisallowedByPolicy | apply | Cloud policy denial | Move 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
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.)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
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
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
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
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.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.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.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.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
| Topic | Verified conclusion | Source (accessed 2026-11-15) |
|---|---|---|
| Terraform CLI | Latest 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 reporting | Terraform 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 format | terraform plan |
| Terraform Policy | HCL; 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 comparison | Sentinel (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 OPA | Compare policy frameworks |
| GitHub Actions versions | Using 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 versions | latest 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, subject | registry.terraform.io · provider source documentation |
| HCP Terraform billing | The 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 assessments | Available 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 Stacks | GA 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 beta | Stacks · Deployment config · terraform stacks · HashiConf 2025 |
| Infracost | Classic 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_TOKEN | infracost releases · infracost/cli |
| conftest | Latest v0.71.1 (2026-10-06) | conftest releases |
| OIDC mechanics | GitHub issuer, sub format (pull_request / ref / environment), Azure federated credentials, and the AWS IAM OIDC provider and trust conditions | GitHub 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::keysavailability is inferred from the official note that most built-in functions are available, and the sample output is illustrative; first runtfpolicy validateandterraform plan -helpto 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_registrationsvalues 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.