Terraform Hour 8 (Optional): 50 Production Issues + 50 Interview Questions
- Given the raw text of an error, you can tell which layer it comes from: State/Backend, Plan/Apply and the dependency graph, Provider/authentication/cloud API, Modules/versions/CI/CD and name the first diagnostic command.
- Understand the underlying mechanisms: state locks and snapshot serial numbers, the dependency graph and unknown values, a provider's PlanResourceChange and RequiresReplace, the credential chain, dependency lock file checksums, and OIDC trust conditions, not just memorize fix commands.
- Be able to reproduce, diagnose, fix, and clean up locally (docker / random / local provider + MinIO) reproduce, diagnose, fix, and clean up 14 typical failures, without needing a cloud account.
- Answer the 50 most common Terraform interview questions using the structure "30-second answer → principle → code → production experience", and handle common follow-ups.
- Use mock interviews (timed + self-assessed) to measure your mastery rate and find weak modules.
1-hour time allocation
| # | Time | Module | Core content | Animation · interactive | Lab |
|---|---|---|---|---|---|
| 0 | Before class | Instructions & troubleshooting lab environment | Ubuntu 24.04 + Terraform 1.17 + Docker 29 + MinIO; safety rules | Environment self-check | Set up the lab8 directory |
| 1 | 00–08 | A · State & Backend | Issues 1–12: lock not released, checksum mismatch, backend change/migration, secrets in state, stale plan, wrong workspace, version too new, backend permissions, deprecated DynamoDB lock, missing remote_state outputs | State troubleshooting decision tree | Lock conflicts · state rollback · migration · secret scanning |
| 2 | 08–16 | A · Plan/Apply & Dependencies | Issues 13–25: cycles, unknown for_each/count, unexpected replacement, count address drift, prevent_destroy, partial failure, timeouts, inconsistent final plan, perpetual diffs, hidden dependencies, -target misuse | "Plan looks wrong" troubleshooting tree | Cycle · unknown for_each · count drift · moved |
| 3 | 16–24 | A · Providers, Authentication & Cloud APIs | Issues 26–38: credential chain, azurerm subscription_id (required since 4.0), 403, resource already exists and needs import, throttling, eventual consistency, version constraint conflicts, missing lock file platforms, wrong provider source address, deleted provider configuration, unregistered RP, quotas, Docker daemon | "init / authentication failure" troubleshooting tree | Multi-platform lock file · wrong source · import block |
| 4 | 24–30 | A · Modules, Versions, CI/CD & Drift | Issues 39–50: module version drift, Module not installed, Registry unreachable, GitHub→AWS/Azure OIDC failure, PR plan and apply mismatch, lock file inconsistency, drift, policy denial, Core version mismatch, moved conflicts, secrets leaked in CI logs | CI pipeline failure simulator | Drift detection · network mirror · moved conflicts |
| 5 | 30–37 | B · Core Concepts & Architecture | Questions 1–13 | Mock interview | 2 scenario questions |
| 6 | 37–44 | B · State, Modules & HCL | Questions 14–25 | Mock interview | 2 scenario questions |
| 7 | 44–52 | B · Multi-Environment, CI/CD & Governance | Questions 26–38 | Mock interview | 3 scenario questions |
| 8 | 52–60 | B · Security, Cloud Practices & Scenario Design | Questions 39–50 | Mock interview | 3 scenario questions |
| — | After class | Cheat sheet · Comprehensive drills | 50 "error → first command → fix" entries; 50 flashcards; 8 mixed failures; full mock interviews | Full mock interview | Final quiz, 12 questions |
Knowledge coverage matrix
| Topic | m1 | m2 | m3 | m4 | m5 | m6 | m7 | m8 |
|---|---|---|---|---|---|---|---|---|
| State / Backend / Locks | ● | — | — | — | ● | ● | — | ● |
| Dependency graph / plan semantics / lifecycle | — | ● | — | — | ● | — | — | ● |
| Provider / authentication / cloud API | — | — | ● | ● | ● | — | ● | ● |
| Modules / versions / lock file | — | — | ● | ● | — | ● | ● | — |
| HCL expressions / validation / testing | — | ● | — | — | — | ● | — | — |
| CI/CD / OIDC / policy / drift | — | — | — | ● | — | — | ● | ● |
| Security / secrets / least privilege | ● | — | ● | ● | — | ● | ● | ● |
| Azure / AWS practices | ● | ● | ● | ● | — | — | — | ● |
Not covered in this lesson (where to learn it)
- HCL syntax and provider/resource basics from scratch → Lesson 1 Core Fundamentals.
- Full Azure / AWS deployment steps → Lesson 3 / Lesson 4.
- Full GitHub Actions pipeline and OIDC configuration → Lesson 5.
- Writing custom providers (Plugin Framework) and operating Terraform Enterprise installations → refer to HashiCorp's official documentation; not covered in this course.
- Managing resources inside a Kubernetes cluster → same repository Kubernetes course.
How to use this lesson
- Open the matching module's quick reference, paste the most distinctive word from the error (such as
state lock,Cycle,checksums,AADSTS) into the filter box. - Click a table row to jump to the detailed explanation, then follow the "diagnose → compare output → fix" steps.
- Not sure which layer it is? Use the animation tab's decision tree/simulator.
- First, check the quick reference, and pick out the questions you're unsure of by difficulty.
- Mock interview: random questions, a 2-minute countdown, answer first then check, self-rate as "answered / partial / didn't know"; scores are saved in this browser.
- Answer structure: One-sentence conclusion → principle → code/command → pitfalls you've hit.
- Cheat sheet Good to print and pin at your desk.
- Comprehensive drills: 8 mixed failures + full mock interview (10 of 50) + final quiz.
- Each question links back to the matching section in Lessons 1–7, so you can revisit it.
Entry structure for Parts A and B
Symptom → root cause (mechanism level) → diagnostic command → sample expected output → fix → prevention & best practices → see Lesson N. Titles use the actual error text printed by Terraform / the provider where possible; provider errors are determined by both the cloud API and the provider version, so wording may change between versions, which is noted in each entry.
Question → 30-second answer → in-depth answer (principles, code) → common follow-ups → bonus points → common wrong answers. Difficulty:BeginnerIntermediateAdvanced.
Relation to the first seven lessons
| Lesson | Most-referenced content in this lesson |
|---|---|
| Lesson 1 Core Fundamentals | Workflow, provider, state, dependency graph, variables/outputs, count/for_each |
| Lesson 2 Production Readiness | Remote backend and locking, modules, version constraints and lock file, workspaces, moved/import/removed, lifecycle |
| Lesson 3 Azure · Lesson 4 AWS | azurerm/aws authentication, resource provider registration, IAM, eventual consistency, quotas |
| Lesson 5 Automation & Operations | GitHub Actions, OIDC, PR plan / merge apply, drift detection, policy |
| Lesson 6 Architecture in Practice | Layered state, remote_state / data source decoupling, multi-environment composition |
| Lesson 7 Deep Troubleshooting & Optimization | TF_LOG, state surgery, large-plan performance, terraform test |
-policies) is generally available, and adds -minimal-refresh; 1.14 introduced terraform query (list resources, written in *.tfquery.hcl) and action blocks; 1.10 introduced ephemeral resources, 1.11 introduced write-only arguments; the S3 backend's use_lockfile native locking replaces the deprecated DynamoDB lock. All "expected output" shown is illustrative, as IDs, timestamps, and ARNs will differ in your environment.Module 0 · Instructions & Troubleshooting Lab Environment (Before Class)
- Completed Lessons 1 and 2 (Lessons 3–7 are optional; cloud-related entries provide links and read-only diagnostic commands).
- Ubuntu 24.04 LTS (local machine or Azure VM), with Docker Engine 29 installed (from the Docker course).
- For cloud-related issues (some entries in Modules 3 and 4), only diagnostic methods are given; reproducing them requires a disposable subscription/account: Azure resource group
rg-tf-lab(canadacentral), AWS regionca-central-1.
Environment: Terraform 1.17 + tools
# HashiCorp official apt repository (same as Lesson 1, Module 0)
wget -O- https://apt.releases.hashicorp.com/gpg | sudo gpg --dearmor -o /usr/share/keyrings/hashicorp-archive-keyring.gpg
echo "deb [signed-by=/usr/share/keyrings/hashicorp-archive-keyring.gpg] https://apt.releases.hashicorp.com $(lsb_release -cs) main" | sudo tee /etc/apt/sources.list.d/hashicorp.list
sudo apt-get update && sudo apt-get install -y terraform jq
terraform version
docker version --format 'Docker {{.Server.Version}}'
Terraform v1.17.2 on linux_amd64 Docker 29.x.x
MinIO: local S3 backend (used in the labs for Modules 1 and 4)
docker run -d --name lab8-minio -p 9000:9000 -p 9001:9001 \ -e MINIO_ROOT_USER=lab8admin -e MINIO_ROOT_PASSWORD=lab8-secret-pass \ pgsty/minio:RELEASE.2026-08-04T00-00-00Z server /data --console-address :9001 # Create the bucket and enable versioning (needed for state rollback) docker run --rm --network host --entrypoint sh minio/mc -c \ "mc alias set l http://127.0.0.1:9000 lab8admin lab8-secret-pass && mc mb -p l/tfstate && mc version enable l/tfstate"
Generic backend snippet (copy into the lab directory's backend.tf):
terraform {
backend "s3" {
bucket = "tfstate"
key = "lab8/terraform.tfstate"
region = "us-east-1" # MinIO does not validate the region, but the argument is required
endpoints = { s3 = "http://127.0.0.1:9000" }
use_path_style = true
skip_credentials_validation = true
skip_requesting_account_id = true
skip_metadata_api_check = true
skip_region_validation = true
use_lockfile = true # S3 native lock (conditional write of a .tflock object)
}
}
export AWS_ACCESS_KEY_ID=lab8admin AWS_SECRET_ACCESS_KEY=lab8-secret-pass
Parameter names for S3-compatible endpoints (endpoints,use_path_style,skip_*) should be confirmed per the S3 backend documentation ; use_lockfile Relies on S3 conditional writes (If-None-Match); older MinIO versions may not support this, in which case run the lock experiment with the local backend instead.
Environment self-check checklist
Connection to the previous lesson
Used in Lesson 7: TF_LOG,terraform state subcommands,terraform test appear heavily in this lesson. The myapp from Lesson 1 (kreuzwerker/docker provider runs nginx/redis containers) serves as the "managed resource" for the failure labs.
Safety rules (must read)
state rm/mv/push,force-unlock operation on real state, terraform state pull > backup-$(date +%s).tfstate first back up the state and confirm that the backend has versioning enabled.- Labs use only fake credentials and fake passwords (such as
FAKE-PASS-123). - Before reproducing anything in the cloud, confirm budget alerts are set; each lab ends with a cleanup step (
terraform destroy,az group delete -n rg-tf-lab).
Five-step general troubleshooting method (used throughout Part A)
| Step | Command | Question answered |
|---|---|---|
| 1 Read the full error | Look at the Error: title + the with …/on main.tf line N location line | Which resource, which line, which stage (init / plan / apply)? |
| 2 Check versions and environment | terraform version · terraform providers · terraform workspace show | Are Core, the provider, and the workspace as expected? |
| 3 Check state | terraform state list · terraform state show ADDR · terraform state pull | jq .serial | What does Terraform think the world looks like? |
| 4 Check the real world | terraform plan -refresh-only · az …show / aws … describe | What do the real resources look like? Where are the differences? |
| 5 Turn on logs | TF_LOG=DEBUG TF_LOG_PATH=tf.log terraform plan; for the provider only: TF_LOG_PROVIDER=DEBUG | What API request did the provider send, and what did it return? (Logs may contain secrets; delete them when done.) |
Module 1 · Part A: State & Backend (Issues 1–12)
- Explain the read/write order of state during one plan/apply: initialize backend → acquire lock → read snapshot (serial + lineage) → write new snapshot → release lock.
- Safely handle leftover locks, corrupted snapshots, and backend migration, and know when to use
force-unlock,state pull/push, and version rollback. - Understand why plaintext secrets end up in state, and how ephemeral resources / write-only arguments prevent this at the source.
Type a keyword from the error (such as lock,checksum,migrate,403) to filter; click a row to jump to the matching entry in "Detailed explanations".
#1 Error: Error acquiring the state lock (lock not released)
Error: Error acquiring the state lock Error message: operation error DynamoDB: PutItem, https response error StatusCode: 400, ... ConditionalCheckFailedException: The conditional request failed Lock Info: ID: 6f1c2a8e-3b4d-1e5f-9a7b-2c8d4e6f0a1b Path: tfstate/prod/network.tfstate Operation: OperationTypeApply Who: runner@ci-7f9c Version: 1.17.2 Created: 2026-11-14 23:51:07.123 +0000 UTC Info: Terraform acquires a state lock to protect the state from being written by multiple users at the same time. Please resolve the issue above and try again. For most commands, you can disable locking with the "-lock=false" flag, but this is not recommended.
Symptom: plan/apply fails right away. When using use_lockfile , the "Error message" line shows an S3 conditional write failure (HTTP 412 PreconditionFailed); the azurerm backend instead reports that the blob is leased (state blob is already locked). The exact wording varies by backend and version.
Root cause: Before writing state, the backend creates a lock (S3: <key>.tflock object; DynamoDB: a record written with a conditional write; azurerm: a blob lease). Normally the lock is released when the command ends; if the process is kill -9 killed, the CI runner is cancelled or times out, or the network drops, the lock is left behind. It can also happen when another person or pipeline really is running—in that case, force-unlocking lets two processes write state at the same time.
Diagnostic commands
# 1) First confirm whether someone is actually running: check Who / Created in Lock Info, and check CI for running jobs on the same state
# 2) Inspect the lock object itself
aws s3api head-object --bucket my-tfstate --key prod/network.tfstate.tflock # use_lockfile
aws dynamodb get-item --table-name tf-locks --key '{"LockID":{"S":"my-tfstate/prod/network.tfstate"}}' # legacy lock
az storage blob show --account-name sttfstate -c tfstate -n prod.terraform.tfstate --auth-mode login --query properties.lease
{
"duration": "infinite",
"state": "leased",
"status": "locked"
}
Fix
# Once you have confirmed no process is using this state: terraform force-unlock 6f1c2a8e-3b4d-1e5f-9a7b-2c8d4e6f0a1b # In extreme azurerm cases (where force-unlock also fails), you can break the lease directly az storage blob lease break --account-name sttfstate -c tfstate -b prod.terraform.tfstate --auth-mode login
Prevention & best practices
- Set a concurrency group for the same state in CI (GitHub Actions
concurrency: tf-prod,cancel-in-progress: false), and do not cancel a job that is running apply. - For brief contention, use
-lock-timeout=5mwaiting instead of failing immediately. - Never add by default in pipelines
-lock=false. - Write force-unlock into the runbook: first confirm Who,
state pullback up, then unlock.
See Lesson 2 Remote backends & locking,Lesson 5 CI concurrency control.
#2 Error refreshing state: state data in S3 does not have the expected content (checksum mismatch / corrupted state)
Error: error loading state: state data in S3 does not have the expected content. The checksum calculated for the state stored in S3 does not match the checksum stored in DynamoDB. Bucket: my-tfstate Key: prod/app.tfstate Calculated checksum: 3c1d...e9 Stored checksum: a77b...04 This may be caused by unusually long delays in S3 processing a previous state update. Please wait for a minute or two and try again. If this problem persists, and neither S3 nor DynamoDB are being written to, then this may indicate a corruption of state data...
Symptom: init/plan fails to read state; or Error: Failed to load state: ... unexpected end of JSON input (the state file is truncated, for example after someone hand-edited it and the save failed).
Root cause: Besides lock records, the legacy DynamoDB lock table also stores an <key>-md5 digest. Someone bypassed Terraform and directly overwrote or rolled back the S3 object (console upload,aws s3 cp), so the digest no longer matches; a mistake while hand-editing JSON directly causes a parse failure.
Diagnostic commands
aws s3api list-object-versions --bucket my-tfstate --prefix prod/app.tfstate \
--query 'Versions[0:5].[VersionId,LastModified,Size]' --output table
aws s3 cp s3://my-tfstate/prod/app.tfstate - | jq '{version,terraform_version,serial,lineage}'
aws dynamodb get-item --table-name tf-locks --key '{"LockID":{"S":"my-tfstate/prod/app.tfstate-md5"}}'
| 3Lg8...Qz | 2026-11-15T02:11:40Z | 412 | ← only 412 bytes: truncated/overwritten
| 9aF2...Kp | 2026-11-14T18:03:12Z | 58211|
{ "version": 4, "terraform_version": "1.17.2", "serial": 318, "lineage": "6b1e0f..." }
Fix
- Freeze all pipelines for this state.
- Restore the most recent correct version:
aws s3api copy-object --copy-source "my-tfstate/prod/app.tfstate?versionId=9aF2...Kp" --bucket my-tfstate --key prod/app.tfstate. - If still using a DynamoDB lock: update the
-md5record to the new object's MD5, or delete the record so Terraform rewrites it. terraform planCheck: resources created after the restored old snapshot will show as "to be created" and need to be re-adopted withimportblocks, rather than applying directly.
Prevention & best practices
- State bucket/container must have versioning and soft delete enabled; only the Terraform identity may write to it.
- When you need to repair state, use
terraform state pull→ edit →terraform state push(push validates lineage and serial, preventing overwriting a newer snapshot). - After migrating to
use_lockfilethere are no more md5 digest records, so this class of "checksum mismatch" disappears, but manual overwrites must still be prevented.
#3 Error: Backend configuration changed
Error: Backend configuration changed A change in the backend configuration has been detected, which may require migrating existing state. If you wish to attempt automatic migration of the state, use "terraform init -migrate-state". If you wish to store the current configuration with no changes to the state, use "terraform init -reconfigure".
Symptom: You changed the backend block (changed the bucket, changed the key, switched from local to S3/azurerm, added use_lockfile) and plan/init now fails.
Root cause:terraform init Terraform records the previous backend configuration (and its hash) in .terraform/terraform.tfstate. When the configuration does not match, Terraform cannot tell whether you want to "move state to a new location" or "point to a new location for an existing state", so it requires an explicit choice. The consequence of choosing wrongly: -reconfigure pointing at an empty location → plan shows every resource as to be created (and may create duplicate resources).
Diagnostic commands
jq '.backend' .terraform/terraform.tfstate # backend configuration used by the last init git diff -- backend.tf terraform state list | head # record the resource list before migrating
{ "type": "s3", "config": { "bucket": "tfstate", "key": "lab8/terraform.tfstate", ... }, "hash": 2793151102 }
Fix
terraform state pull > pre-migrate.tfstate # back up terraform init -migrate-state # copy the existing state to the new backend (prompts for confirmation) terraform state list | wc -l # should match the count before migration terraform plan # should show No changes
In CI, where each run passes -backend-config the value but the local cache holds the old one, use -reconfigure.
Prevention & best practices
- Treat backend migration as a "change": go through a PR, pick a maintenance window, and after migrating verify
state listthe count andplanthat there are no changes. - In CI, do not cache
.terraform/directory (only cache the provider plugin cache directory).
#4 Error: Backend initialization required, please run "terraform init"
Error: Backend initialization required, please run "terraform init" Reason: Initial configuration of the requested backend "s3" The "backend" is the interface that Terraform uses to store state, perform operations, etc. If this message is showing up, it means that the Terraform configuration you're using is using a custom configuration for the Terraform backend.
Symptom: Running plan in a freshly cloned repository or a new CI working directory fails right away; similar errors include Error: Required plugins are not installed,Error: Module not installed (#40).
Root cause:init is responsible for three things: initializing the backend, downloading providers (per the lock file), and installing modules. .terraform/ is not committed to Git, so every new working directory must run init first. When separate CI jobs (plan job / apply job) run on different runners, each must also run init.
Diagnostic commands
ls -la .terraform/ 2>/dev/null || echo "not initialized" cat .terraform/terraform.tfstate 2>/dev/null | jq .backend.type
Fix
terraform init -input=false -lockfile=readonly # recommended for CI: non-interactive, lock file read-only terraform plan -input=false -out=tfplan
Prevention & best practices
- Put
initinto the Makefile / pipeline template as a fixed first step. - When an apply job uses the plan file from the plan job, also run init with the same configuration and lock file (the plan file does not contain provider binaries).
#5 Plaintext database password appears in terraform.tfstate (secrets in state)
Symptom: A security scan finds "password": "P@ssw0rd!", private keys, and connection strings in state; even though variables and outputs are marked sensitive = true, and the plan shows (sensitive value).
Root cause:sensitive It only affects display (CLI output and logs hide the value), not the storage: all attributes returned by the provider are written to state. random_password.result,tls_private_key.private_key_pem, the database's password arguments and Key Vault-reading data sources all go into state.
Diagnostic commands
terraform state pull | jq -r '.resources[] | select(.instances[].sensitive_attributes|length>0) | "\(.type).\(.name)"' terraform state pull | grep -nE '"(password|secret|private_key[a-z_]*|connection_string)"' | head
azurerm_postgresql_flexible_server.db random_password.db 212: "administrator_password": "P@ssw0rd!",
Fix
# Terraform 1.11+: write-only argument — the value is passed to the provider but not written to the plan or state
ephemeral "random_password" "db" { # 1.10+: ephemeral resource, not stored in state
length = 24
}
resource "azurerm_postgresql_flexible_server" "db" {
# ...
administrator_password_wo = ephemeral.random_password.db.result
administrator_password_wo_version = 1 # increment this when you want to rotate
}
Whether a given resource offers the *_wo argument depends on that provider's documentation (AWS aws_db_instance.password_wo, azurerm supports it for several resources already). Better still, let the cloud platform manage passwords (RDS manage_master_user_password, Azure managed identities need no password). If a password has leaked: rotate it immediately, and clear access to the state's version history.
Prevention & best practices
- Treat state as a secret: encrypt the backend (SSE-KMS / storage account encryption), apply least privilege, and enable access logging.
- OpenTofu 1.7+ provides client-side state encryption; Terraform relies on backend-side encryption (HCP Terraform manages encrypted state storage).
- Do not upload the state file as a CI artifact, and do not paste
state show.
#6 Error: Saved plan is stale (concurrent writes / expired plan)
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.
Symptom: A plan file generated in a PR tfplan fails to apply after merging; or worse—if the team uses local state or a backend without locking, two people apply at once, the later write overwrites the earlier one, and resources "disappear" from state (they still exist in the cloud, but Terraform doesn't know about them).
Root cause: The plan file records the lineage and serial. If the current state's serial has changed when applying (someone else has applied), Terraform refuses to run; this is a safeguard. Without a lock there is no protection at all: two processes read the same serial N, each writes N+1, and the later write overwrites the earlier one.
Diagnostic commands
terraform show -json tfplan | jq '.prior_state.serial? // "n/a"' # whether this field exists varies by version terraform state pull | jq .serial aws s3api list-object-versions --bucket my-tfstate --prefix prod/app.tfstate --query 'Versions[0:3].LastModified'
Fix
- Stale plan: re-run
plan -out, review it, and apply immediately. - For resources lost to an overwrite: find the missing resource addresses and IDs in the backend's version history, and re-adopt them using
importblocks.
Prevention & best practices
- All shared state uses a remote backend with locking.
- Pipelines: serialize work on the same state (concurrency group); after merging, re-plan on main before applying, or use a "merge queue + re-plan and compare before apply" pattern.
#7 plan shows all 80 resources to be created / prod resources to be destroyed (wrong workspace)
Symptom: You thought you were in dev, but plan wants to change prod; or Plan: 80 to add, 0 to change, 0 to destroy, it looks like state is empty.
Root cause: CLI workspaces share one configuration and backend, differing only in their state key (S3: env:/<workspace>/<key>). The current workspace is stored locally in .terraform/environment a file that is invisible and easy to forget; TF_WORKSPACE an environment variable can also override it. When you create or misspell a workspace, its state is empty, so plan wants to create every resource.
Diagnostic commands
terraform workspace show
echo "TF_WORKSPACE=${TF_WORKSPACE:-<unset>}"
terraform workspace list
cat .terraform/environment 2>/dev/null
prod TF_WORKSPACE=<unset> default dev * prod
Fix
terraform workspace select dev then re-run plan. If resources were created in the wrong workspace, in that workspace terraform destroy (after confirming it contains only the mistakenly created resources), or use removed blocks / import , to move them to the correct state.
Prevention & best practices
- For production, use separate directories + separate backend keys (or even separate accounts/subscriptions), not workspaces; workspaces suit short-lived identical copies (such as PR preview environments).
- Add a safeguard in the configuration:
checka check block orlifecycle.preconditionan assertionterraform.workspaceto confirm the workspace and variablevar.envmatch. - Show the current workspace in your shell prompt.
See Lesson 2 workspaces,Lesson 6 multi-environment structure.
#8 Error: state snapshot was created by Terraform v1.17.2, which is newer than current v1.16.7
Error: Failed to load state: state snapshot was created by Terraform v1.17.2, which is newer than current v1.16.7; upgrade to Terraform v1.17.2 or greater to work with this state
Symptom: A colleague upgraded their local Terraform and ran apply; afterwards, all CI runs (still on the old version) fail.
Root cause: The state records the terraform_version field. Terraform refuses to read state that was written by a newer version, to avoid an older CLI misreading the new format or losing new fields. Any operation that writes state (apply, state mv, import, even refresh-only apply) updates the version number to the current CLI version.
Diagnostic commands
terraform state pull | jq -r .terraform_version # pulling requires a new enough CLI; or read the backend object directly aws s3 cp s3://my-tfstate/prod/app.tfstate - | jq -r .terraform_version grep -rn required_version *.tf
Fix
Upgrade CI and everyone's CLI to ≥ the version in state (recommended); if you truly must roll back, restore the snapshot from before the write from the backend's version history (later changes will be lost, so use with caution).
Prevention & best practices
- Use
required_version = "~> 1.17.0"to pin the minor version, and use.terraform-version(tfenv) ormise/asdfto standardize the team's version. - In CI, when using
hashicorp/setup-terraformexplicitly writeterraform_version. - Treat upgrading Core as a planned change: validate it on the dev state first.
#9 Error: Failed to get existing workspaces: … S3: ListObjectsV2 … StatusCode: 403 … AccessDenied
Error: Failed to get existing workspaces: Unable to list objects in S3 bucket "my-tfstate" with prefix "env:/": operation error S3: ListObjectsV2, https response error StatusCode: 403, RequestID: 8Q3..., HostID: ..., api error AccessDenied: User: arn:aws:sts::111122223333:assumed-role/gh-tf-plan/GitHubActions is not authorized to perform: s3:ListBucket on resource: "arn:aws:s3:::my-tfstate"
Symptom: Init fails outright, or init succeeds but plan fails with a GetObject 403 error, and apply fails with a PutObject 403 error, and locking fails with a 412/403.
Root cause: The backend's authentication and the provider's authentication are two separate configurations (the backend block cannot use variables). The backend identity needs: s3:ListBucket (the bucket, used to list workspaces), access to the state key's s3:GetObject/PutObject, and access to *.tflock 's PutObject/DeleteObject; when using SSE-KMS, you also need kms:Decrypt/GenerateDataKey. Note that the workspace prefix env:/ must also be allowed in the policy.
Diagnostic commands
aws sts get-caller-identity # the identity the backend actually uses aws s3api list-objects-v2 --bucket my-tfstate --prefix prod/ --max-items 1 aws s3api get-bucket-encryption --bucket my-tfstate --query 'ServerSideEncryptionConfiguration.Rules[0].ApplyServerSideEncryptionByDefault'
Fix
{
"Statement": [
{"Effect":"Allow","Action":"s3:ListBucket","Resource":"arn:aws:s3:::my-tfstate"},
{"Effect":"Allow","Action":["s3:GetObject","s3:PutObject"],"Resource":"arn:aws:s3:::my-tfstate/prod/*"},
{"Effect":"Allow","Action":["s3:DeleteObject"],"Resource":"arn:aws:s3:::my-tfstate/prod/*.tflock"}
]
}
Follow the policy syntax in the S3 backend documentation Permissions Required ; a read-only plan identity also needs lock file write permission (plan locks by default), or use -lock=false (only for read-only plans, and understand the risks).
Prevention & best practices
- Separate permissions by state key prefix: each team/environment can only access its own prefix.
- In the
assume_role { role_arn = … }block, explicitly specify a role, rather than relying on credentials that happen to be in environment variables.
#10 azurerm backend: 403 AuthorizationPermissionMismatch / This request is not authorized to perform this operation
Error: Failed to get existing workspaces: listing blobs: executing request: unexpected status 403 (403 This request is not authorized to perform this operation using this permission.) with AuthorizationPermissionMismatch
Symptom: In the portal you are a subscription Owner, but you cannot read state; or CI suddenly fails after shared key access is disabled on the storage account.
Root cause: Using Entra ID authentication (use_azuread_auth = true, recommended) to access blobs requires the data plane role Storage Blob Data Contributor (scoped to the storage account or container). Owner/Contributor are control plane roles; they cannot read or write blob data themselves—they can only "list access keys" and then use the keys. Once the storage account disables shared key access, this route breaks. Newly assigned roles may take a few minutes to take effect.
Diagnostic commands
az account show --query '{sub:id, user:user.name}' -o table
az role assignment list --assignee "$(az ad signed-in-user show --query id -o tsv)" \
--scope "$(az storage account show -n sttfstate -g rg-tf-state --query id -o tsv)" -o table
az storage account show -n sttfstate -g rg-tf-state --query allowSharedKeyAccess
Fix
az role assignment create --role "Storage Blob Data Contributor" \ --assignee-object-id <principal-object-id> --assignee-principal-type ServicePrincipal \ --scope "$(az storage account show -n sttfstate -g rg-tf-state --query id -o tsv)/blobServices/default/containers/tfstate"
terraform {
backend "azurerm" {
resource_group_name = "rg-tf-state"
storage_account_name = "sttfstate"
container_name = "tfstate"
key = "prod.terraform.tfstate"
use_azuread_auth = true
use_oidc = true # in GitHub Actions
}
}
Prevention & best practices
- State storage account: disable shared keys, enable blob versioning and soft delete, add a delete lock (
CanNotDelete), and restrict network access. - Assign roles at the narrowest container scope.
#11 Warning: Deprecated Parameter — "dynamodb_table" is deprecated. Use parameter "use_lockfile" instead.
Warning: Deprecated Parameter on backend.tf line 7, in terraform: 7: dynamodb_table = "tf-locks" The parameter "dynamodb_table" is deprecated. Use parameter "use_lockfile" instead.
Symptom: Every init/plan shows a deprecation warning; the team worries that when switching locking mechanisms, the two locks might disagree and allow concurrent writes.
Root cause: Since S3 added support for conditional writes in 2024, the Terraform S3 backend has added use_lockfile (writing a .tflock object next to the state), and the DynamoDB lock is consequently marked deprecated and will be removed in a future version.
Diagnostic commands
grep -nE 'dynamodb_table|use_lockfile' backend.tf aws s3api list-objects-v2 --bucket my-tfstate --prefix prod/ --query 'Contents[].Key'
Fix: migrate in two smooth steps
# Step 1: enable both locks at once (both must be acquired for locking to succeed)
backend "s3" {
bucket = "my-tfstate"
key = "prod/app.tfstate"
region = "ca-central-1"
use_lockfile = true
dynamodb_table = "tf-locks"
}
# Step 2: after all pipelines and members have upgraded and run init -reconfigure, delete the dynamodb_table
After changing backend parameters you need to terraform init -reconfigure (the state location has not changed, so no migration is needed). The identity needs *.tflock PutObject/DeleteObject permissions on it (#9).
Prevention & best practices
- Watch the backend deprecation items in the Terraform CHANGELOG and handle them during minor-version upgrades.
- Before deleting the DynamoDB table after migration, confirm that no old repository still references it.
#12 Error: Unsupported attribute — This object does not have an attribute named "vpc_id" (terraform_remote_state)
Error: Unsupported attribute
on main.tf line 14, in resource "aws_ecs_service" "api":
14: subnets = data.terraform_remote_state.network.outputs.private_subnet_ids
├────────────────
│ data.terraform_remote_state.network.outputs is object with 2 attributes
This object does not have an attribute named "private_subnet_ids".
Symptom: The application layer fails to read the networking layer's state outputs; or after the networking layer refactors/renames outputs, all downstream projects break together.
Root cause:terraform_remote_state It can only read root module outputs (outputs inside a module must be re-exported at the root module), and it reads the most recent apply-written snapshot: a newly added output does not exist if the other side has not applied it yet. It also requires the downstream identity to have permission to read the entire upstream state, which means it can see all secrets in the upstream state.
Diagnostic commands
cd ../network && terraform output -json | jq 'keys' terraform console <<< 'keys(data.terraform_remote_state.network.outputs)'
["private_subnets","vpc_id"]
Fix
Correct the name, or add output "private_subnet_ids" and apply the upstream. A better approach: downstream looks up via a data source by tag (data "aws_subnets" + filter { name = "tag:Tier" values = ["private"] }), or publishes "contract values" through SSM Parameter Store / Azure App Configuration.
Prevention & best practices
- Treat cross-state outputs as an API: only add, never change; to rename, add the new name first, migrate downstream, then remove the old name.
- Prefer decoupling via data sources or parameter stores, to reduce read access to the upstream state.
State / Backend troubleshooting decision tree
Pick the symptom you see and step through to get diagnostic commands and conclusions. Each conclusion links to the matching detailed explanation.
AWS_ACCESS_KEY_ID/SECRET is exported; work in ~/lab8/m1 . Use only hashicorp/random,hashicorp/local and kreuzwerker/docker, with no cloud cost.Lab 1-A: create and clear a leftover lock (#1)
mkdir -p ~/lab8/m1 && cd ~/lab8/m1
cat > main.tf <<'EOF'
terraform {
required_providers { time = { source = "hashicorp/time", version = "~> 0.13" } }
}
resource "time_sleep" "slow" { create_duration = "120s" }
EOF
terraform init -input=falseterraform apply -auto-approve & sleep 8; kill -9 $! terraform plan
Error: Error acquiring the state lock Error message: ... StatusCode: 412 ... PreconditionFailed ... Lock Info: ID: 0b9d6c1e-... Operation: OperationTypeApply
If your MinIO does not support conditional writes, delete backend.tf and use local state instead; the process will still .terraform.tfstate.lock.info leave a lock behind.
pgrep -fa 'terraform apply' || echo "no terraform running" terraform force-unlock -force 0b9d6c1e-... # use the ID from your output terraform plan -lock-timeout=30s
terraform destroy -auto-approve (time_sleep destroys quickly).Lab 1-B: roll back to a version after accidentally overwriting state (#2, #6)
cat > main.tf <<'EOF'
resource "random_pet" "a" { count = 3 }
EOF
terraform init -input=false -upgrade && terraform apply -auto-approve
terraform state pull | jq '{serial, n: (.resources|length)}'echo '{"version":4,"terraform_version":"1.17.2","serial":1,"lineage":"bogus","outputs":{},"resources":[]}' > empty.json
docker run --rm --network host -v $PWD:/w --entrypoint sh minio/mc -c \
"mc alias set l http://127.0.0.1:9000 lab8admin lab8-secret-pass >/dev/null && mc cp /w/empty.json l/tfstate/lab8/terraform.tfstate"
terraform plan | tail -2Plan: 3 to add, 0 to change, 0 to destroy.
docker run --rm --network host --entrypoint sh minio/mc -c \ "mc alias set l http://127.0.0.1:9000 lab8admin lab8-secret-pass >/dev/null && mc ls --versions l/tfstate/lab8/" # Choose the second-to-last version ID: docker run --rm --network host --entrypoint sh minio/mc -c \ "mc alias set l http://127.0.0.1:9000 lab8admin lab8-secret-pass >/dev/null && mc cp --version-id <VID> l/tfstate/lab8/terraform.tfstate l/tfstate/lab8/terraform.tfstate" terraform plan | tail -1
No changes. Your infrastructure matches the configuration.
terraform destroy -auto-approve; rm empty.jsonLab 1-C: local → S3 migration (#3)
mkdir -p ~/lab8/m1c && cd ~/lab8/m1c
echo 'resource "random_id" "x" { byte_length = 4 }' > main.tf
terraform init -input=false && terraform apply -auto-approve # local state
cp ../m1/backend.tf . && sed -i 's#lab8/terraform.tfstate#lab8/m1c.tfstate#' backend.tf
terraform planError: Backend initialization required, please run "terraform init" Reason: Initial configuration of the requested backend "s3"
terraform init -migrate-state # answer yes terraform state list && terraform plan | tail -1 && ls terraform.tfstate*
random_id.x No changes. Your infrastructure matches the configuration. terraform.tfstate terraform.tfstate.backup ← the old local files are now empty and can be deleted
terraform destroy -auto-approve; cd ..; rm -rf m1cLab 1-D: sensitive does not mean not stored (#5)
mkdir -p ~/lab8/m1d && cd ~/lab8/m1d
cat > main.tf <<'EOF'
resource "random_password" "db" { length = 16 }
output "pw" {
value = random_password.db.result
sensitive = true
}
EOF
terraform init -input=false && terraform apply -auto-approve | tail -2
grep -c '"result"' terraform.tfstate; jq -r '.resources[0].instances[0].attributes.result' terraform.tfstatepw = <sensitive> 1 q7#Lk2!vR0pZ9x&b ← plaintext in state
cat > main.tf <<'EOF'
ephemeral "random_password" "db" { length = 16 }
EOF
terraform apply -auto-approve >/dev/null; grep -c '"result"' terraform.tfstate0
ephemeral values can only be used in provider configuration, write-only arguments, other ephemeral contexts, and ephemeral outputs; they cannot be used as ordinary resource arguments (this causes an error). See the official documentation for details.
cd ..; rm -rf m1dTeaching video (title and channel verified via YouTube oEmbed)
No verified video specifically on state lock/corruption troubleshooting was found. Below is a 3-minute storyboard you can record yourself:
pgrep after confirming no one is running it force-unlock.grep Plaintext random_password in state; after switching to ephemeral, grep returns 0. Summary: locks, version control, and secrets.Official documentation
Module 2 · Part A: Plan/Apply & Dependencies (Issues 13–25)
- Use the dependency graph (DAG) and "known/unknown values" to explain errors such as cycles, for_each/count that cannot be determined, and hidden dependencies.
- Read the
-/+,# forces replacement,must be replaced, use lifecycle,movedand for_each to avoid unexpected destruction. - The standard process for handling partial apply failures, timeouts, and provider inconsistencies: stay calm, don't hand-edit state, and plan before deciding.
Type a keyword (such as Cycle,for_each,replace,timeout) to filter; click a row to jump to the detailed explanation.
#13 Error: Cycle: aws_security_group.app, aws_security_group.db
Error: Cycle: aws_security_group.db, aws_security_group.app
Symptom: validate or plan fails outright, listing only the nodes that form the cycle. Common causes: two security groups referencing each other in inline ingress blocks; module A's output feeds module B, and B's output feeds back into A; create_before_destroy or a dependency direction conflict (the error will show (destroy) nodes).
Root cause: Terraform builds each resource (and its destroy action) into a node of a directed acyclic graph, connects edges by reference, and then performs a topological sort; with a cycle, it cannot determine which to create first.
Diagnostic commands
terraform graph -type=plan | grep -E 'aws_security_group\.(app|db)' | head terraform graph -type=plan | dot -Tsvg > graph.svg # requires graphviz; visualize to find the cycle
Fix
# Split the mutually referencing rules into separate resources: the two SGs no longer depend on each other
resource "aws_security_group" "app" {
name = "app"
vpc_id = var.vpc_id
}
resource "aws_security_group" "db" {
name = "db"
vpc_id = var.vpc_id
}
resource "aws_vpc_security_group_ingress_rule" "db_from_app" {
security_group_id = aws_security_group.db.id
referenced_security_group_id = aws_security_group.app.id
from_port = 5432
to_port = 5432
ip_protocol = "tcp"
}
Cycles between modules: move the shared part into a third module, or pass in a "known name" via a variable instead of passing an attribute of the other module's resource.
Prevention & best practices
- Prefer "standalone rule resources" over inline blocks (AWS SG rules, Azure NSG rules).
- Module outputs should flow only downstream; avoid bidirectional data flow.
#14 Error: Invalid for_each argument — keys derived from resource attributes that cannot be determined until apply
Error: Invalid for_each argument
on main.tf line 22, in resource "azurerm_role_assignment" "ra":
22: for_each = toset(azurerm_user_assigned_identity.ids[*].principal_id)
├────────────────
│ azurerm_user_assigned_identity.ids is tuple with 2 elements
The "for_each" set includes values derived from resource attributes that
cannot be determined until apply, and so Terraform cannot determine the full
set of keys that will identify the instances of this resource.
When working with unknown values in for_each, it's better to use a map value
where the keys are defined statically in your configuration and where only
the values contain apply-time results.
Alternatively, you could use the -target planning option to first apply only
the resources that the for_each value depends on, and then apply a second
time to fully converge.
Root cause: The for_each key is the instance address (ra["…"]), which must be known at plan time. principal_id,id Such attributes are only known after the resource is created (unknown), so Terraform cannot determine which instances to create. Values may be unknown; keys may not.
Diagnostic commands
terraform console > azurerm_user_assigned_identity.ids[*].principal_id # new resources show (known after apply)
Fix
locals { identities = toset(["api", "worker"]) } # static keys
resource "azurerm_user_assigned_identity" "id" {
for_each = local.identities
name = "id-${each.key}"
# ...
}
resource "azurerm_role_assignment" "ra" {
for_each = azurerm_user_assigned_identity.id # keys = api/worker (static); values may contain unknown attributes, which is fine
principal_id = each.value.principal_id
# ...
}
Terraform is experimenting with "deferred actions" (plan -allow-deferral, alpha builds only) to allow unknown for_each; stable releases still require designing as above.
Prevention & best practices
- for_each keys come from names in variables/locals, not from resource attributes.
- Do not use
-targeta two-stage apply as a routine solution (#25).
#15 Error: Invalid count argument — The "count" value depends on resource attributes that cannot be determined until apply
Error: Invalid count argument on main.tf line 9, in resource "aws_eip" "nat": 9: count = length(aws_subnet.public) > 0 ? length(data.aws_availability_zones.az.names) : 0 The "count" value depends on resource attributes that cannot be determined until apply, so Terraform cannot predict how many instances will be created. To work around this, use the -target argument to first apply only the resources that the count depends on.
Root cause: Same as #14: count determines the number of instances and must be known at plan time. Common pitfalls: count = var.create ? 1 : 0 is fine, but count = module.x.enabled ? 1 : 0 when enabled the value comes from a resource attribute, it is unknown; if a data source depends on a resource to be created, its result also becomes unknown during plan (the data source is read at apply time).
Diagnostic commands
terraform plan 2>&1 | grep -B2 -A6 'Invalid count' grep -n 'depends_on' *.tf # depends_on on a data source defers it to be read at apply
Fix
- Drive count with input variables (boolean switches, quantities), not resource attributes.
- Remove unnecessary
depends_on(it makes the data source's result unknown at plan time). - When the quantity comes from an enumerable set, use for_each with static keys instead.
Prevention & best practices
In module interface design, "whether to create / how many to create" should always be input variables; document in the module README which inputs must be values known at plan time.
#16 # azurerm_linux_virtual_machine.vm must be replaced (-/+ … # forces replacement, unexpected destroy and recreate)
# azurerm_linux_virtual_machine.vm must be replaced
-/+ resource "azurerm_linux_virtual_machine" "vm" {
~ id = "/subscriptions/.../virtualMachines/vm-web" -> (known after apply)
~ name = "vm-web" -> "vm-web-01" # forces replacement
~ custom_data = (sensitive value) # forces replacement
# (20 unchanged attributes hidden)
}
Plan: 1 to add, 0 to change, 1 to destroy.
Symptom: You only changed the name / tag format / cloud-init, but plan wants to delete and recreate the VM or database; or the AMI data source returned most_recent = true, so every new AMI release replaces the instance.
Root cause: The provider's schema marks certain attributes as ForceNew / RequiresReplace (the cloud API does not support in-place modification). When PlanResourceChange returns RequiresReplace a path, Terraform Core changes the action to "replace"; the default order is destroy first, then create.
Diagnostic commands
terraform plan -out=tfplan
terraform show -json tfplan | jq -r '.resource_changes[] | select(.change.actions|index("delete")) | "\(.address) \(.change.actions|join(",")) replace_paths=\(.change.replace_paths)"'
azurerm_linux_virtual_machine.vm delete,create replace_paths=[["name"],["custom_data"]]
Fix
resource "azurerm_linux_virtual_machine" "vm" {
# ...
lifecycle {
ignore_changes = [custom_data] # cloud-init only takes effect on first boot; later changes should not trigger a rebuild
create_before_destroy = true # when a rebuild is required, create the new one before destroying the old one (names must be able to coexist)
prevent_destroy = true # add a safeguard for stateful resources (#18)
}
}
AMI drift: publish the AMI ID explicitly as a variable, or ignore_changes = [ami] update it through a rolling replacement process (ASG instance refresh).
Prevention & best practices
- In CI, gate the plan JSON: when a
deleteaction appears, require extra approval (OPA/conftest or Terraform Policy). - When reviewing a plan, first look at
Plan: X to add, Y to change, Z to destroythe Z in it.
#17 After deleting an item in the middle of a list, all following instances must be modified/replaced (count address drift)
# docker_container.app[1] must be replaced
-/+ resource "docker_container" "app" {
~ name = "lab8-b" -> "lab8-c" # forces replacement
# docker_container.app[2] will be destroyed
Plan: 1 to add, 0 to change, 2 to destroy.
Symptom:var.names = ["a","b","c"] Changed to ["a","c"], expecting only b to be deleted; instead c is replaced and index 2 is deleted.
Root cause: The address of a count instance is a positional index ([0] [1] [2]). After deleting a middle element,"c" moves from index 2 to 1, and Terraform thinks [1] 's argument changed from b to c (ForceNew → replace),[2] no longer exists → destroy.
Diagnostic commands
terraform state list | grep docker_container.app terraform plan | grep -E '^\s+# docker_container'
Fix: switch to for_each, and use moved blocks to migrate addresses without loss
resource "docker_container" "app" {
for_each = toset(var.names)
name = "lab8-${each.key}"
image = docker_image.nginx.image_id
}
moved {
from = docker_container.app[0]
to = docker_container.app["a"]
}
moved {
from = docker_container.app[1]
to = docker_container.app["b"]
}
moved { from = docker_container.app[2] to = docker_container.app["c"] }
The plan should show has moved to and 0 to destroy. Then, when b is later removed from the list, only app["b"] is destroyed.
Prevention & best practices
- Use count only for fully identical, interchangeable instances (such as N identical workers); for objects with identity, always use for_each.
- Keep moved blocks for at least one release cycle, and remove them only after all environments have applied.
#18 Error: Instance cannot be destroyed — Resource … has lifecycle.prevent_destroy set
Error: Instance cannot be destroyed
on db.tf line 1:
1: resource "aws_db_instance" "main" {
Resource aws_db_instance.main has lifecycle.prevent_destroy set, but the plan
calls for this resource to be destroyed. To avoid this error and continue with
the plan, either disable lifecycle.prevent_destroy or reduce the scope of the
plan using the -target option.
Symptom: The plan fails. This is actually the protection taking effect: a change would cause the database to be replaced (#16), or someone deleted the resource block.
Root cause:prevent_destroy Makes Terraform error when the plan includes a destroy (including a destroy as part of a replacement). Note: if you delete the entire resource block, the lifecycle goes with it, and the protection is lost.
Diagnostic commands
git diff HEAD~1 -- db.tf # which line change triggered the replacement # Temporarily comment out prevent_destroy only to see the cause (do not apply): terraform plan -out=tfplan && terraform show -json tfplan | jq '.resource_changes[]|select(.address=="aws_db_instance.main")|.change.replace_paths'
Fix
- If the change was a mistake: revert the change that triggers ForceNew (for example
identifier,engine, storage encryption). - If you really want to remove it from Terraform but keep the instance, use a
removedblock (from = aws_db_instance.main, containinglifecycle { destroy = false }) (1.7+). - If you really need to rebuild: go through the change process, take a snapshot/backup first, then temporarily remove prevent_destroy.
Prevention & best practices
- Use cloud-side protection for stateful resources as well: RDS
deletion_protection = true, Azure resource locks (CanNotDelete), S3 versioning. - The azurerm provider's
features { resource_group { prevent_deletion_if_contains_resources = true } }(enabled by default in 4.x).
#19 apply fails midway: "Apply complete" does not appear and some resources were created (partial failure / tainted)
azurerm_resource_group.rg: Creation complete after 2s azurerm_virtual_network.vnet: Creation complete after 6s azurerm_container_app_environment.env: Still creating... [10m0s elapsed] ╷ │ Error: creating Managed Environment ...: polling after CreateOrUpdate: ... │ Code="ManagedEnvironmentProvisioningError" ... ╵
Symptom: apply exits with an error; when you plan again, the failed resource shows is tainted, so must be replaced.
Root cause: Terraform is not transactional: each resource is written to state as soon as it completes (successful resources are kept); a resource that failed during creation but already produced an object in the cloud is marked as tainted, and the next plan will plan to replace it. There is no rollback.
Diagnostic commands
terraform state list terraform plan | grep -E 'tainted|must be replaced' terraform state show azurerm_container_app_environment.env | head -20
Fix
- Read the cloud error (quotas, subnet delegation, name conflicts) and fix the root cause.
- Run
planagain: confirm that it will only replace tainted resources and create the remaining resources, then apply. - If you confirm the tainted resource is actually fine:
terraform untaint ADDR(use with caution). - To force-replace a healthy resource, use
terraform apply -replace=ADDR(which replaces the oldtaint).
Prevention & best practices
- Design apply to be re-runnable: after a failure, fix the issue and run again to converge.
- Break large changes into smaller ones and layer state to reduce the blast radius of failures.
#20 Error: waiting for … : timeout while waiting for state to become 'available' (last state: 'creating', timeout: 40m0s)
Error: waiting for RDS DB Instance (lab8-db) create: timeout while waiting for state to become 'available' (last state: 'creating', timeout: 40m0s)
Symptom: Large resources (RDS, AKS/EKS, Container Apps environments, Azure Firewall) time out and fail, but in the console they later become "available".
Root cause: After calling the create API, the provider polls the resource status; each resource type has a default timeout (found in the Timeouts section of the resource documentation). A timeout only means the provider stopped waiting,not that the cloud operation failed; the resource is marked tainted (#19), and the next plan may plan to replace a resource that is actually healthy.
Diagnostic commands
aws rds describe-db-instances --db-instance-identifier lab8-db --query 'DBInstances[0].DBInstanceStatus' terraform plan | grep -A2 tainted
Fix
resource "aws_db_instance" "main" {
# ...
timeouts {
create = "90m"
update = "90m"
delete = "60m"
}
}
If the resource is already available in the cloud: terraform untaint aws_db_instance.main, then run plan to confirm No changes (or only minor attribute refreshes).
Prevention & best practices
- The CI job's own timeout should be greater than the sum of Terraform resource timeouts; otherwise the runner is killed and leaves a lock behind (#1).
- Set timeouts blocks in advance for resources known to be slow.
See Lesson 4 AWS.
#21 Error: Provider produced inconsistent final plan / inconsistent result after apply
Error: Provider produced inconsistent final plan When expanding the plan for aws_s3_bucket.logs to include new values learned so far during apply, provider "registry.terraform.io/hashicorp/aws" produced an invalid new value for .tags_all: new element "Owner" has appeared. This is a bug in the provider, which should be reported in the provider's own issue tracker.
Symptom: apply fails midway with a message saying "this is a provider bug"; similar ones include Provider produced inconsistent result after apply (the value returned after apply differs from the plan).
Root cause: Core requires the provider to honor the contract: values known in the plan must not change during apply, and the result returned by apply must match the plan. Causes include a provider implementation defect, the cloud API normalizing values (casing, default tags, JSON ordering), or default_tags combining default_tags with resource-level tags that contain apply-time values; any of these triggers this check.
Diagnostic commands
terraform version # record the provider version TF_LOG_PROVIDER=DEBUG TF_LOG_PATH=provider.log terraform apply grep -n 'inconsistent' provider.log | head
Fix
- Usually, running plan + apply once more converges (the resource has been created, and the second run has no unknown values).
- Search the provider's GitHub issues for the exact error text to see whether it is fixed in a newer version, then upgrade the provider (validate in dev first).
- Avoid using
default_tagsintimestamp()values that are only determined at apply time.
Prevention & best practices
Pin the provider version (~> + lock file); upgrade providers through a PR; when you hit a provider bug, file an issue with a minimal reproduction configuration and logs (with secrets removed).
#22 every plan shows ~ update in-place, and there are still differences after apply (perpetual diff)
# aws_iam_policy.app will be updated in-place
~ resource "aws_iam_policy" "app" {
~ policy = jsonencode(
~ {
~ Statement = [
~ {
~ Action = [
- "s3:PutObject",
"s3:GetObject",
+ "s3:PutObject",
]
Symptom: With no code changes, plan never shows No changes; drift detection (#46) therefore raises false alarms every day.
Root cause: Values in the configuration and values returned by the API are "semantically the same, textually different": JSON key or array ordering, casing (the casing of resourceGroups in an Azure resource ID), CIDR notation, defaults auto-filled by the API, or two resources managing the same attribute at once (for example, using inline rules and standalone rule resources at the same time,aws_s3_bucket and aws_s3_bucket_policy coexisting).
Diagnostic commands
terraform plan -out=p && terraform show -json p | jq '.resource_changes[]|select(.change.actions==["update"])|{address, before: .change.before.policy, after: .change.after.policy}'
grep -rn 'aws_security_group_rule\|ingress {' *.tf # check whether two places manage the same set of rules
Fix
- Use
data "aws_iam_policy_document"orjsonencode()to generate normalized JSON, with action lists sorted alphabetically. - Manage each attribute with only one resource (choose one: inline or standalone resource).
- For attributes the API modifies automatically that you don't need to manage, use
lifecycle { ignore_changes = [...] }. - When it is confirmed to be a provider bug, upgrade the provider.
Prevention & best practices
In CI, after apply, run terraform plan -detailed-exitcode: exit code 2 (changes present) means a perpetual diff exists and must be fixed.
#23 Error: Reference to undeclared resource / Reference to undeclared input variable
Error: Reference to undeclared resource on main.tf line 12, in resource "docker_container" "web": 12: image = docker_image.ngnix.image_id A managed resource "docker_image" "ngnix" has not been declared in the root module.
Symptom: validate/plan fails; similar errors include Reference to undeclared input variable,Reference to undeclared module,Unsupported attribute (accessing an output the module does not export).
Root cause: a typo; the resource is in a child module, but the root module references it directly (it must be accessed through the module's output: module.web.image_id) ; or the files were placed in a different directory (Terraform only loads the current directory's *.tf, non-recursively).
Diagnostic commands
terraform validate grep -rn 'resource "docker_image"' --include=*.tf . ls *.tf
Fix
Correct the name; access across modules through outputs; confirm the files are in the root module directory.
Prevention & best practices
Run in pre-commit terraform fmt -check + terraform validate + tflint; install the Terraform language server (terraform-ls) in your IDE for instant hints.
See Lesson 1 HCL basics.
#24 InvalidParameterValueException: The role defined for the function cannot be assumed by Lambda (hidden dependency, missing depends_on)
Error: creating Lambda Function (lab8-fn): operation error Lambda: CreateFunction, https response error StatusCode: 400, ... InvalidParameterValueException: The role defined for the function cannot be assumed by Lambda.
Symptom: The first apply fails and the second succeeds; or creating an ECS service reports "unable to assume role"; in Azure, a web app starts pulling its image before the role assignment completes, and the pull fails.
Root cause: Terraform only builds dependencies from expression references. The Lambda references aws_iam_role.fn.arn, so it waits for the role to be created—but does not wait for aws_iam_role_policy_attachment, because nothing references it. So the function can be created before the policy is attached; combined with IAM eventual consistency (#31), this causes intermittent failures.
Diagnostic commands
terraform graph | grep -E 'aws_lambda_function.fn.*->'
Fix
resource "aws_lambda_function" "fn" {
role = aws_iam_role.fn.arn
# ...
depends_on = [aws_iam_role_policy_attachment.fn_logs] # explicitly declare the hidden dependency
}
Prevention & best practices
depends_onUse only for dependencies that truly exist but cannot be expressed with an expression, and add a comment explaining why.- Do not casually add
depends_on: it defers all data sources inside the module to be read at apply time, causing many(known after apply)(#15).
See Lesson 1 implicit and explicit dependencies,Lesson 4 IAM.
#25 Warning: Resource targeting is in effect / Applied changes may be incomplete (misuse of -target)
Warning: Resource targeting is in effect You are creating a plan with the -target option, which means that the result of this plan may not represent all of the changes requested by the current configuration. The -target option is not for routine use, and is provided only for exceptional situations such as recovering from errors or mistakes, or when Terraform specifically suggests to use it as part of an error message.
Symptom: The team routinely runs -target only to deploy "their own resources"; a few weeks later the full plan shows many unexpected changes, and nobody dares to apply.
Root cause:-target It processes only the target and its dependencies; changes to other resources are skipped but remain in the configuration, so the configuration gradually drifts from the real state. It is suitable as a one-off emergency tool (for example, the two-stage convergence in #14/#15).
Diagnostic commands
terraform plan -detailed-exitcode; echo "exit=$?" # full plan; 2 means accumulated differences exist grep -rn -- '-target' .github/ Makefile scripts/ 2>/dev/null
Fix
Stop using -target in pipelines; run one full plan, review the accumulated changes item by item, and apply; needing to "deploy only my part" means the state is too coarse-grained and should be split (by team / layer / lifecycle).
Prevention & best practices
Forbid -target in CI (script check); when needed, have a person run it from the runbook and record it.
"Plan looks wrong" troubleshooting decision tree
Start from the symptom and narrow down step by step to the specific problem.
kreuzwerker/docker / hashicorp/random, local state is sufficient, and work in ~/lab8/m2 the lab directory.Lab 2-A: create and remove a cycle (#13)
mkdir -p ~/lab8/m2a && cd ~/lab8/m2a
cat > main.tf <<'EOF'
resource "terraform_data" "a" { input = terraform_data.b.id }
resource "terraform_data" "b" { input = terraform_data.a.id }
EOF
terraform init -input=false >/dev/null; terraform validateError: Cycle: terraform_data.b, terraform_data.a
sed -i 's/input = terraform_data.a.id/input = "static"/' main.tf
sed -i 's/input = terraform_data.b.id/input = "static"/;' main.tf
cat >> main.tf <<'EOF'
resource "terraform_data" "c" { input = terraform_data.a.id }
EOF
terraform validate && terraform graph | grep -- '->'cd ..; rm -rf m2aLab 2-B: unknown values driving for_each (#14)
mkdir -p ~/lab8/m2b && cd ~/lab8/m2b
cat > main.tf <<'EOF'
resource "random_pet" "p" { count = 2 }
resource "terraform_data" "t" {
for_each = toset(random_pet.p[*].id)
input = each.key
}
EOF
terraform init -input=false >/dev/null; terraform plan 2>&1 | grep -A1 'Invalid for_each'Error: Invalid for_each argument
cat > main.tf <<'EOF'
resource "random_pet" "p" { for_each = toset(["api","worker"]) }
resource "terraform_data" "t" {
for_each = random_pet.p # keys api/worker are static
input = each.value.id # values are known only at apply time; that's fine
}
EOF
terraform apply -auto-approve | tail -1Apply complete! Resources: 4 added, 0 changed, 0 destroyed.
terraform destroy -auto-approve; cd ..; rm -rf m2bLab 2-C: count address drift and moved (#17)
mkdir -p ~/lab8/m2c && cd ~/lab8/m2c
cat > main.tf <<'EOF'
terraform {
required_providers { docker = { source = "kreuzwerker/docker", version = "~> 3.0" } }
}
variable "names" { default = ["a","b","c"] }
resource "docker_image" "nginx" { name = "nginx:alpine" }
resource "docker_container" "app" {
count = length(var.names)
name = "lab8-${var.names[count.index]}"
image = docker_image.nginx.image_id
}
EOF
terraform init -input=false >/dev/null && terraform apply -auto-approve | tail -1
terraform plan -var 'names=["a","c"]' | tail -1Plan: 1 to add, 0 to change, 2 to destroy. ← you only wanted to delete b, but c was affected
cat > main.tf <<'EOF'
terraform {
required_providers { docker = { source = "kreuzwerker/docker", version = "~> 3.0" } }
}
variable "names" { default = ["a","b","c"] }
resource "docker_image" "nginx" { name = "nginx:alpine" }
resource "docker_container" "app" {
for_each = toset(var.names)
name = "lab8-${each.key}"
image = docker_image.nginx.image_id
}
moved {
from = docker_container.app[0]
to = docker_container.app["a"]
}
moved {
from = docker_container.app[1]
to = docker_container.app["b"]
}
moved {
from = docker_container.app[2]
to = docker_container.app["c"]
}
EOF
terraform apply -auto-approve | grep -E 'moved|Apply'
terraform plan -var 'names=["a","c"]' | tail -1# docker_container.app[0] has moved to docker_container.app["a"] Apply complete! Resources: 0 added, 0 changed, 0 destroyed. Plan: 0 to add, 0 to change, 1 to destroy.
terraform destroy -auto-approve; cd ..; rm -rf m2cLab 2-D: prevent_destroy blocks replacement (#16, #18)
mkdir -p ~/lab8/m2d && cd ~/lab8/m2d
cat > main.tf <<'EOF'
variable "len" { default = 2 }
resource "random_pet" "db" {
length = var.len # changing length forces replacement
lifecycle { prevent_destroy = true }
}
EOF
terraform init -input=false >/dev/null && terraform apply -auto-approve >/dev/null
terraform plan -var len=3 2>&1 | grep -E 'Error|prevent_destroy' | head -3Error: Instance cannot be destroyed Resource random_pet.db has lifecycle.prevent_destroy set, but the plan calls for this resource to be destroyed. ...
prevent_destroy to false, then terraform destroy -auto-approve; cd ..; rm -rf m2dTeaching video (title and channel verified via YouTube oEmbed)
No verified video specifically on cycle / unknown for_each troubleshooting was found. Storyboard:
terraform graph | dot Draw the dependency graph and mark the cycle.(known after apply), then change to static keys.Official documentation
Module 3 · Part A: Providers, Authentication & Cloud APIs (Issues 26–38)
- Explain the credential source order for providers (AWS SDK credential chain; azurerm's CLI / managed identity / OIDC / client secret), and quickly confirm "whose identity Terraform is actually calling the API with".
- Distinguish five kinds of cloud API errors — "authentication failure", "authorization failure (403)", "resource already exists", "throttling", and "eventual consistency" — and give the standard fix for each.
- Understand the provider installation chain: version constraints → lock file → checksums (multi-platform) → download/mirror.
Type a keyword (such as credential,403,already exists,checksum) to filter; click a row to jump to the detailed explanation.
#26 Error: No valid credential sources found (AWS credential chain)
Error: No valid credential sources found
with provider["registry.terraform.io/hashicorp/aws"],
on providers.tf line 1, in provider "aws":
1: provider "aws" {
Please see https://registry.terraform.io/providers/hashicorp/aws
for more information about providing credentials.
Error: failed to refresh cached credentials, no EC2 IMDS role found,
operation error ec2imds: GetMetadata, request canceled, context deadline exceeded
Symptom: Works locally but not in CI/containers; or AWS_PROFILE the SSO session it points to has expired (reports token has expired / SSO session ... expired).
Root cause: The aws provider uses the AWS SDK credential chain: provider block arguments → environment variables (AWS_ACCESS_KEY_ID…) → shared config/credentials files (profile, SSO,credential_process) → Web Identity (AWS_WEB_IDENTITY_TOKEN_FILE, used for OIDC/EKS) → container credentials (ECS) → EC2 IMDS. If nothing is found, the last step (IMDS) times out, and you see "no EC2 IMDS role found".
Diagnostic commands
env | grep -E '^AWS_' | sed 's/=.*/=***/' aws configure list aws sts get-caller-identity aws sso login --profile lab8 # when the SSO session has expired
Name Value Type Location
profile lab8 manual --profile
access_key ****************ABCD sso
region ca-central-1 config-file ~/.aws/config
Fix
Provide one explicit credential source: locally, use aws sso login + AWS_PROFILE; in CI, use OIDC (aws-actions/configure-aws-credentials, see #42); do not put long-lived access keys in the provider block or tfvars.
Prevention & best practices
- In the provider block, use
assume_role { role_arn = var.deploy_role_arn }to specify the target role explicitly; the base credentials only need to be able to "assume" it. - In CI, print as the first step
aws sts get-caller-identity, so failures surface early.
#27 Error: `subscription_id` is a required provider property when performing a plan/apply operation (azurerm 4.0+)
Error: `subscription_id` is a required provider property when performing a plan/apply operation
with provider["registry.terraform.io/hashicorp/azurerm"],
on providers.tf line 1, in provider "azurerm":
1: provider "azurerm" {
Symptom: Fails immediately after upgrading from azurerm 3.x to 4.x/5.x; or Azure CLI login works, but in CI building account: could not acquire access token.
Root cause: From azurerm 4.0 onward,must explicitly specify the subscription (in the provider block subscription_id or as the environment variable ARM_SUBSCRIPTION_ID). It no longer implicitly uses the default subscription from Azure CLI, which prevents accidental operations on the wrong subscription. Authentication methods are tried in order: client certificate/secret, OIDC (ARM_USE_OIDC), managed identity (ARM_USE_MSI), Azure CLI.
Diagnostic commands
az account show --query '{name:name, id:id, tenant:tenantId}' -o table
env | grep -E '^ARM_' | sed 's/=.*/=***/'
grep -n 'azurerm' .terraform.lock.hcl -A1 | head -3
Fix
provider "azurerm" {
features {}
subscription_id = var.subscription_id # or export ARM_SUBSCRIPTION_ID=...
}
Prevention & best practices
- Read the provider's Upgrade Guide before a major version upgrade (the azurerm 4.0 Upgrade Guide lists all breaking changes).
- Put each environment's subscription ID in that environment's tfvars, so it is visible at a glance during review.
#28 403: AuthorizationFailed / UnauthorizedOperation / AccessDenied (authentication succeeded but authorization is insufficient)
Error: creating Virtual Network (Subscription: "..." Resource Group Name: "rg-tf-lab" Virtual Network Name: "vnet-lab8"): unexpected status 403 (403 Forbidden) with error: AuthorizationFailed: The client 'a1b2...' with object id 'a1b2...' does not have authorization to perform action 'Microsoft.Network/virtualNetworks/write' over scope '/subscriptions/.../resourceGroups/rg-tf-lab/providers/Microsoft.Network/virtualNetworks/vnet-lab8' or the scope is invalid. If access was recently granted, please refresh your credentials.
Error: creating EC2 Instance: operation error EC2: RunInstances, https response error StatusCode: 403, ... api error UnauthorizedOperation: You are not authorized to perform this operation. User: arn:aws:sts::111122223333:assumed-role/gh-tf-apply/GitHubActions is not authorized to perform: ec2:RunInstances on resource: arn:aws:ec2:ca-central-1:... with an explicit deny in a service control policy. Encoded authorization failure message: ...
Root cause: The identity is established, but the RBAC/IAM policy does not allow the operation; or it is overridden by a higher-level denial (AWS SCP, permission boundary, explicit Deny; Azure Policy's deny effect reports RequestDisallowedByPolicy, which differs from 403).
Diagnostic commands
# AWS: decode the authorization failure message to see which policy denied it aws sts decode-authorization-message --encoded-message '...' --query DecodedMessage --output text | jq . aws iam simulate-principal-policy --policy-source-arn arn:aws:iam::111122223333:role/gh-tf-apply --action-names ec2:RunInstances # Azure: list the identity's roles at the scope az role assignment list --assignee a1b2... --all -o table
Fix
Grant the Terraform identity the minimum permissions needed for the operation (Azure: Contributor at resource group level; when role assignments must be created, you also need User Access Administrator or a constrained assignment of RBAC Administrator; AWS: a per-service deployment role). If an SCP/Policy denies it, the organization forbids it; change the configuration rather than bypassing it.
Prevention & best practices
- The plan identity is read-only and the apply identity is writable (#39 interview question).
- When adding a new resource type, update the IAM policy at the same time and validate in dev first.
#29 Error: A resource with the ID "…" already exists - to be managed via Terraform this resource needs to be imported into the State
Error: A resource with the ID "/subscriptions/0000.../resourceGroups/rg-tf-lab" already exists - to be managed via Terraform this resource needs to be imported into the State. Please see the resource documentation for "azurerm_resource_group" for more information.
Symptom: azurerm checks for a resource with the same name before creating and shows the message above; AWS instead returns a conflict from the API, for example EntityAlreadyExists: Role with name lab8-role already exists.,BucketAlreadyOwnedByYou,InvalidGroup.Duplicate.
Root cause: The resource was created manually in the portal or by a script, or earlier state was lost or overwritten (#2, #6), or after an apply timeout the cloud resource was actually created but never recorded in state. Terraform does not "automatically adopt" existing resources.
Diagnostic commands
az group show -n rg-tf-lab --query '{id:id, tags:tags}'
terraform state list | grep azurerm_resource_group || echo "not in state"
Fix: import block (1.5+; reviewable, can run in CI)
import {
to = azurerm_resource_group.rg
id = "/subscriptions/0000.../resourceGroups/rg-tf-lab"
}
terraform plan -generate-config-out=generated.tf # if the resource block hasn't been written yet, this generates a draft configuration terraform plan # expected: 1 to import, 0 to add, 0 to change
Prevention & best practices
- In production, prohibit manual portal creation (Azure Policy / SCP + read-only roles for people); all resources go through Terraform.
- To bring existing resources under management in bulk, you can use the 1.14+
terraform query(list resources, written in*.tfquery.hcl) to discover resources and then generate import configuration (check the documentation for provider support).
#30 ThrottlingException: Rate exceeded / 429 TooManyRequests (API throttling)
Error: reading IAM Role (lab8-role-17): operation error IAM: GetRole, exceeded maximum number of attempts, 25, https response error StatusCode: 400, ... api error Throttling: Rate exceeded Error: retrieving ... : unexpected status 429 (429 Too Many Requests) with error: TooManyRequests: ... Please try again after '17' seconds.
Symptom: plan on a large state (thousands of resources) fails randomly during the refresh phase; multiple pipelines run at the same time in the same account/subscription.
Root cause: Cloud APIs rate-limit per account/subscription/region. Refresh sends a read request for each resource, with a default parallelism of 10; the SDK automatically backs off and retries, but when retries are exhausted it errors. Azure Resource Manager counts read/write request quotas per subscription, tenant, and principal.
Diagnostic commands
terraform state list | wc -l TF_LOG=DEBUG TF_LOG_PATH=tf.log terraform plan; grep -ciE 'throttl|429|rate exceeded' tf.log
Fix
- Short term:
terraform plan -parallelism=4; aws providermax_retries = 25(orAWS_MAX_ATTEMPTS,retry_mode = "adaptive"). - Medium term: split the state to reduce the number of resources refreshed per run; in 1.17, the
-minimal-refreshoption refreshes only resources with configuration changes (trade-off: drift may be missed, so hand drift detection to a scheduled refresh-only job). - Stagger pipeline schedules, or serialize per account.
Prevention & best practices
Keep a single state within a few hundred resources; pay special attention to global low-quota APIs such as IAM and Route 53.
#31 PrincipalNotFound: Principal … does not exist in the directory (eventual consistency)
Error: authorization.RoleAssignmentsClient#Create: Failure responding to request: StatusCode=400 -- Original Error: autorest/azure: Service returned an error. Status=400 Code="PrincipalNotFound" Message="Principal 9f8e... does not exist in the directory 0000.... Check that you have the correct principal ID. If you are creating this principal and then immediately assigning a role, this error might be related to a replication delay. In this case, set the role assignment principalType property to a value, such as ServicePrincipal, User, or Group. See https://aka.ms/docs-principaltype"
Symptom: A role assignment immediately after creating a managed identity / service principal fails, but succeeds on rerun; in AWS, an IAM role just created fails immediately when used by EC2/Lambda (#24), and a newly created instance InvalidInstanceID.NotFound. The outer error wrapper varies with the provider version.
Root cause: Entra ID, AWS IAM, and similar are globally replicated control planes; after a write, it takes seconds to tens of seconds to become visible everywhere (eventual consistency). Providers have built-in retries for common cases, but they cannot cover every combination.
Diagnostic commands
az ad sp show --id 9f8e... --query '{appId:appId, type:servicePrincipalType}' # check again later whether it is visible yet
Fix
resource "azurerm_role_assignment" "acr_pull" {
scope = azurerm_container_registry.acr.id
role_definition_name = "AcrPull"
principal_id = azurerm_user_assigned_identity.app.principal_id
principal_type = "ServicePrincipal" # tells ARM not to look it up in the directory immediately
}
When really necessary, use hashicorp/time 's time_sleep to insert a wait in the dependency chain (last resort; add a comment).
Prevention & best practices
Upgrade to a provider version that fixes this class of retry issue; design apply to be re-runnable (#19).
#32 locked provider … does not match configured version constraint; must use terraform init -upgrade
Error: Failed to query available provider packages Could not retrieve the list of available versions for provider hashicorp/aws: locked provider registry.terraform.io/hashicorp/aws 5.100.0 does not match configured version constraint ~> 6.0; must use terraform init -upgrade to allow selection of new versions
Symptom: After changing the required_providers version constraint, init fails; another case is no available releases match the given constraints >= 6.0.0, < 6.0.0— the root module and child modules have contradictory constraints.
Root cause:.terraform.lock.hcl Records the exact versions selected last time; by default, init respects the lock file; only -upgrade will reselect within the constraints. Terraform merges the constraints of the root module and all child modules; if the intersection is empty, there is no solution.
Diagnostic commands
terraform providers # shows the constraint tree for each module's provider requirements grep -A2 'hashicorp/aws' .terraform.lock.hcl
Providers required by configuration:
.
├── provider[registry.terraform.io/hashicorp/aws] ~> 6.0
└── module.vpc
└── provider[registry.terraform.io/hashicorp/aws] >= 5.0, < 6.0
Fix
First resolve the constraint conflict (upgrade module.vpc to a version that supports aws 6), then terraform init -upgrade, commit the updated lock file; read the provider's major-version Upgrade Guide and validate with plan in dev.
Prevention & best practices
- Reusable modules use loose lower bounds (
>= 5.0), and the root module uses~>to pin the major version. - Commit the lock file to Git; use Renovate/Dependabot to open provider upgrade PRs.
#33 the local package for … doesn't match any of the checksums previously recorded in the dependency lock file (missing lock file platform)
Error: Failed to install provider Error while installing hashicorp/azurerm v4.x.x: the local package for registry.terraform.io/hashicorp/azurerm 4.x.x doesn't match any of the checksums previously recorded in the dependency lock file (this might be because the available checksums are for packages targeting different platforms); for more information: https://developer.hashicorp.com/terraform/language/files/dependency-lock#checksum-verification
Symptom: A lock file generated on a Mac (darwin_arm64) fails checksum verification in Linux CI when using a plugin cache or network mirror; a Windows colleague's init fails.
Root cause: In the lock file, the h1: (package content hash) only includes the platform where init was run; zh: (zip release hash) comes from the registry's officially signed manifest and covers all platforms. When downloading directly from the registry, the zh: hashes can be used for verification, but when installing from a local cache or filesystem mirror, only the h1: can be compared, so a missing platform causes failure.
Diagnostic commands
grep -A12 'hashicorp/azurerm' .terraform.lock.hcl | grep -c 'h1:' terraform version | head -2 # on linux_amd64 / darwin_arm64
Fix
terraform providers lock \ -platform=linux_amd64 -platform=linux_arm64 \ -platform=darwin_arm64 -platform=windows_amd64 git add .terraform.lock.hcl && git commit -m "lock providers for all platforms"
Prevention & best practices
Agree on the team's platform list in the repository template, and have provider upgrade PRs automatically run the commands above; in CI, terraform init -lockfile=readonly, make it fail outright when the lock file is inconsistent rather than silently rewriting it.
#34 provider registry registry.terraform.io does not have a provider named registry.terraform.io/hashicorp/docker
Error: Failed to query available provider packages
Could not retrieve the list of available versions for provider hashicorp/docker:
provider registry registry.terraform.io does not have a provider named
registry.terraform.io/hashicorp/docker
Did you intend to use kreuzwerker/docker? If so, you must specify that source
address in each module which requires that provider. To see which modules are
currently depending on hashicorp/docker, run the following command:
terraform providers
Root cause: When you don't write required_providers in source , Terraform by default looks up hashicorp/<local name> . Third-party/partner providers (kreuzwerker/docker,integrations/github,cloudflare/cloudflare) must explicitly declare source, and every child module that uses it must also declare it; otherwise the child module implicitly requires hashicorp/docker.
Diagnostic commands
terraform providers | grep -i docker grep -rn 'required_providers' -A4 --include=*.tf . | grep -i docker
Fix
terraform {
required_providers {
docker = {
source = "kreuzwerker/docker"
version = "~> 3.0"
}
}
} # both the root module and every child module that uses docker resources need this
Prevention & best practices
Every module has versions.tf a versions.tf that explicitly lists source and minimum version; tflint's terraform_required_providers rule can check it automatically.
#35 Error: Provider configuration not present
Error: Provider configuration not present To work with module.dr.aws_s3_bucket.replica (orphan) its original provider configuration at module.dr.provider["registry.terraform.io/hashicorp/aws"].west is required, but it has been removed. This occurs when a provider configuration is removed while objects created by that provider still exist in the state. Re-add the provider configuration to destroy module.dr.aws_s3_bucket.replica (orphan), after which you can remove the provider configuration again.
Symptom: After deleting a module call or a provider block with an alias, plan fails.
Root cause: Each resource in state records "which provider configuration manages it." When deleting a resource, Terraform needs that provider configuration to call Delete; if you delete both the resource and its provider configuration (for example, a whole module together with its internal provider block), those orphaned resources cannot be destroyed. Defining provider blocks inside a child module is a common source of this problem.
Diagnostic commands
terraform state list | grep module.dr terraform state show module.dr.aws_s3_bucket.replica | head -3 terraform state pull | jq -r '.resources[] | select(.module=="module.dr") | .provider'
Fix
- Temporarily restore the provider configuration (and the module call), apply to destroy the resources, then delete the configuration; or
- if you do not want to destroy them, use a
removedblock (lifecycle { destroy = false }) to remove these resources from state.
Prevention & best practices
Reusable modules must not contain provider blocks; the root module passes them in through providers = { aws = aws.west } , and inside the module, use configuration_aliases to declare the aliases it needs.
See Lesson 2 modules and provider passing,Lesson 4 multi-region.
#36 MissingSubscriptionRegistration: The subscription is not registered to use namespace 'Microsoft.App'
Error: creating Managed Environment ...: unexpected status 409 (409 Conflict) with error: MissingSubscriptionRegistration: The subscription is not registered to use namespace 'Microsoft.App'. See https://aka.ms/rps-not-found for how to register subscriptions.
Symptom: In a new subscription, creating Container Apps or certain new services for the first time fails; or azurerm 4.x/5.x init errors because it has no permission to register resource providers.
Root cause: An Azure subscription must register resource providers (RPs) before using the corresponding services. From azurerm 4.0, use resource_provider_registrations (core/extended/all/none, default core) to control which RPs are auto-registered (replacing the 3.x skip_provider_registration); services not in that list must be registered manually or appended to resource_providers_to_register . Registration requires subscription-level permissions (*/register/action).
Diagnostic commands
az provider show -n Microsoft.App --query registrationState -o tsv az provider list --query "[?registrationState=='Registered'].namespace" -o tsv | wc -l
Fix
az provider register -n Microsoft.App --wait
provider "azurerm" {
features {}
subscription_id = var.subscription_id
resource_provider_registrations = "none" # for identities with limited permissions: the platform team registers in advance
# resource_providers_to_register = ["Microsoft.App"] # or add the RPs you need
}
Confirm parameter names and default sets against the azurerm provider documentation .
Prevention & best practices
Pre-register the required RPs in the subscription provisioning (landing zone) process; the Terraform apply identity does not need subscription-level registration permissions.
#37 Insufficient quota: QuotaExceeded / OperationNotAllowed … exceeding approved quota / VcpuLimitExceeded
Azure: Code="OperationNotAllowed" Message="Operation could not be completed as it results in exceeding approved Total Regional Cores quota. Location: canadacentral, Current Limit: 10, Current Usage: 8, Additional Required: 4 ..." AWS: api error VcpuLimitExceeded: You have requested more vCPU capacity than your current vCPU limit of 16 allows for the instance bucket that the specified instance type belongs to.
Root cause: Cloud accounts have quotas for each region and each SKU family; new subscriptions / free accounts have very low quotas. It can also be that the region temporarily has no capacity for that SKU (Azure SkuNotAvailable, AWS InsufficientInstanceCapacity).
Diagnostic commands
az vm list-usage -l canadacentral -o table | grep -iE 'Total Regional|Standard B' aws service-quotas get-service-quota --service-code ec2 --quota-code L-1216C47A --query 'Quota.Value' az vm list-skus -l canadacentral --size Standard_B2s --query '[].restrictions' -o json
Fix
Request a quota increase (the portal "Quotas" / Service Quotas); change SKU or region; for capacity issues, use multiple availability zones / instance types (ASG mixed instances policy).
Prevention & best practices
In capacity planning, include quotas in your checks (you can use check a check block + data sources for soft assertions); include quota requests in the environment provisioning runbook.
#38 Error pinging Docker server … Cannot connect to the Docker daemon (kreuzwerker/docker provider)
Error: Error pinging Docker server, please make sure that unix:///var/run/docker.sock is reachable and has a '_ping' endpoint and Docker daemon is running: Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?
Symptom: The Lesson 1 local lab fails at plan on a new machine, WSL, rootless Docker, or Docker Desktop; or permission denied while trying to connect to the Docker daemon socket.
Root cause: The provider connects by default to unix:///var/run/docker.sock (or DOCKER_HOST). The rootless Docker socket is at $XDG_RUNTIME_DIR/docker.sock; Docker Desktop / contexts use a different endpoint; if the current user is not in the docker group, it has no socket permission.
Diagnostic commands
docker context ls
echo "DOCKER_HOST=${DOCKER_HOST:-<unset>}"
ls -l /var/run/docker.sock; id -nG | grep -w docker || echo "not in docker group"
Fix
provider "docker" {
host = "unix:///run/user/1000/docker.sock" # rootless; or get it from docker context inspect
}
or sudo systemctl start docker, or add the user to the docker group and log in again (note the docker group is effectively root-equivalent).
Prevention & best practices
Make host a variable that reads by default DOCKER_HOST; list the socket paths for different environments in the lab README.
See Lesson 1 Module 0 environment, Docker course Lesson 8, issues 45–46.
"init / authentication / API failure" troubleshooting decision tree
Lab 3-A: missing source address (#34)
mkdir -p ~/lab8/m3a && cd ~/lab8/m3a
echo 'resource "docker_network" "n" { name = "lab8-net" }' > main.tf
terraform init -input=false 2>&1 | grep -E 'does not have|Did you intend'provider registry registry.terraform.io does not have a provider named registry.terraform.io/hashicorp/docker Did you intend to use kreuzwerker/docker? ...
cat > versions.tf <<'EOF'
terraform {
required_providers { docker = { source = "kreuzwerker/docker", version = "~> 3.0" } }
}
EOF
terraform init -input=false | tail -1 && terraform apply -auto-approve | tail -1terraform destroy -auto-approve (keep the directory for use in 3-B)Lab 3-B: multi-platform lock file (#33)
cd ~/lab8/m3a grep -A8 'kreuzwerker/docker' .terraform.lock.hcl | grep -c 'h1:' # only the current platform terraform providers lock -platform=linux_amd64 -platform=darwin_arm64 -platform=windows_amd64 grep -A12 'kreuzwerker/docker' .terraform.lock.hcl | grep -c 'h1:'
1 3
sed -i 's/~> 3.0/~> 2.0/' versions.tf terraform init -input=false 2>&1 | grep -E 'does not match|init -upgrade' sed -i 's/~> 2.0/~> 3.0/' versions.tf
cd ..; rm -rf m3aLab 3-C: Docker daemon unreachable (#38)
mkdir -p ~/lab8/m3c && cd ~/lab8/m3c
cat > main.tf <<'EOF'
terraform {
required_providers { docker = { source = "kreuzwerker/docker", version = "~> 3.0" } }
}
provider "docker" { host = "unix:///tmp/nope.sock" }
resource "docker_network" "n" { name = "lab8-net" }
EOF
terraform init -input=false >/dev/null; terraform plan 2>&1 | grep -i 'ping'Error: Error pinging Docker server, please make sure that unix:///tmp/nope.sock is reachable ...
docker context inspect -f '{{.Endpoints.docker.Host}}' output), then plan succeeds. Cleanup: cd ..; rm -rf m3cLab 3-D (Azure, optional): already exists → import block (#29)
az group create -n rg-tf-lab -l canadacentral -o none # simulate "manual creation"
mkdir -p ~/lab8/m3d && cd ~/lab8/m3d
cat > main.tf <<EOF
terraform {
required_providers { azurerm = { source = "hashicorp/azurerm", version = "~> 5.0" } }
}
provider "azurerm" {
features {}
subscription_id = "$(az account show --query id -o tsv)"
}
resource "azurerm_resource_group" "rg" {
name = "rg-tf-lab"
location = "canadacentral"
}
EOF
terraform init -input=false >/dev/null; terraform apply -auto-approve 2>&1 | grep -m1 'already exists'cat >> main.tf <<EOF
import {
to = azurerm_resource_group.rg
id = "$(az group show -n rg-tf-lab --query id -o tsv)"
}
EOF
terraform plan | tail -1 && terraform apply -auto-approve | tail -1Plan: 1 to import, 0 to add, 0 to change, 0 to destroy. Apply complete! Resources: 1 imported, 0 added, 0 changed, 0 destroyed.
terraform destroy -auto-approve; cd ..; rm -rf m3d (or az group delete -n rg-tf-lab --yes)Teaching video (title and channel verified via YouTube oEmbed)
No verified video specifically on provider lock file / 403 troubleshooting was found. Storyboard:
Official documentation
Module 4 · Part A: Modules, Versions, CI/CD & Drift (Issues 39–50)
- Locate pipeline failures to a stage: setup → cloud login (OIDC) → init (module/provider download) → static checks → plan → policy → apply.
- Understand the trust conditions of GitHub OIDC (
sub,aud), and fix AWS/Azure federated login failures. - Establish the guarantee that "the plan reviewed in the PR = the change applied on main", and detect drift with scheduled refresh-only / plan runs.
Type a keyword (such as module,OIDC,AADSTS,drift) to filter; click a row to jump to the detailed explanation.
#39 Error: Unsupported argument — An argument named "enable_classiclink" is not expected here (module version drift)
Error: Unsupported argument on network.tf line 9, in module "vpc": 9: enable_classiclink = false An argument named "enable_classiclink" is not expected here.
Symptom: Without changing any code, CI suddenly fails one day; or the plan shows many unexpected replacements.
Root cause: The module call does not specify version a version (for Registry modules), or the Git source is not pinned to ?ref= a ref init ; when init runs, it fetches the latest major version; the new version removed or renamed input variables, or changed internal resource addresses. In the example above, the community VPC module removed ClassicLink-related inputs in the new major version.
Diagnostic commands
cat .terraform/modules/modules.json | jq -r '.Modules[] | "\(.Key) \(.Source) \(.Version // "-")"' grep -n -A3 'module "vpc"' network.tf
vpc registry.terraform.io/terraform-aws-modules/vpc/aws 6.x.x ← expected 3.x
Fix
module "vpc" {
source = "terraform-aws-modules/vpc/aws"
version = "~> 5.21" # pin the major version; upgrade major versions via a separate PR and read the UPGRADE docs
# ...
}
module "naming" {
source = "git::https://github.com/org/tf-modules.git//naming?ref=v1.4.2" # pin the Git source to a tag or commit
}
Prevention & best practices
- Note: Module versions are not recorded in
.terraform.lock.hcl(the lock file only locks providers), so they must be pinned in source/version. - Renovate can recognize Terraform modules and open upgrade PRs.
#40 Error: Module not installed / Module source has changed
Error: Module not installed
on main.tf line 3:
3: module "web" {
This module is not yet installed. Run "terraform init" to install all modules
required by this configuration.
Symptom: After adding or changing a module call (source/version) and running plan directly; similar errors include Module source has changed,Module version requirements have changed.
Root cause: Modules are downloaded during init to .terraform/modules/, and recorded in modules.json; plan does not download automatically. Local path modules (./modules/web) are not copied, but still need to be registered by init.
Diagnostic commands
ls .terraform/modules/ ; jq '.Modules[].Key' .terraform/modules/modules.json
Fix
terraform init (when you changed the version constraint, terraform init -upgrade, it also upgrades providers, so watch for lock file changes); if you only want to update modules, use terraform get -update.
Prevention & best practices
Run init on every CI run; do not cache .terraform/modules, to avoid using outdated module code.
See Lesson 2 modules.
#41 could not connect to registry.terraform.io: failed to request discovery document (Registry unreachable)
Error: Failed to query available provider packages Could not retrieve the list of available versions for provider hashicorp/azurerm: could not connect to registry.terraform.io: failed to request discovery document: Get "https://registry.terraform.io/.well-known/terraform.json": dial tcp: lookup registry.terraform.io on 10.0.0.2:53: read udp ...: i/o timeout
Symptom: init fails on internal/offline runners and on enterprise networks controlled by a proxy; or occasional Registry/GitHub download timeouts make CI unstable.
Root cause: init needs to access the Registry's service discovery document, then download provider packages from releases.hashicorp.com or GitHub. The enterprise network does not allow these domains, requires a proxy (HTTPS_PROXY), or TLS interception (requires trusting the enterprise root CA).
Diagnostic commands
curl -sSI https://registry.terraform.io/.well-known/terraform.json | head -1 curl -sSI https://releases.hashicorp.com | head -1 env | grep -i _proxy
Fix
# ~/.terraformrc (Windows: %APPDATA%\terraform.rc)
plugin_cache_dir = "$HOME/.terraform.d/plugin-cache"
provider_installation {
network_mirror {
url = "https://tf-mirror.internal.example.com/providers/"
include = ["registry.terraform.io/*/*"]
}
}
or use filesystem_mirror: on a machine with internet access, run terraform providers mirror /opt/tf-mirror, then distribute the directory to the offline runner. Put private modules in a private Registry (HCP Terraform / Artifactory / GitLab).
Prevention & best practices
Use a plugin cache directory + network mirror in CI to eliminate runtime dependence on the public internet; the lock file should include h1 hashes for all platforms (#33) so that mirror installs can pass verification.
#42 Could not assume role with OIDC: Not authorized to perform sts:AssumeRoleWithWebIdentity (GitHub Actions → AWS)
Error: Could not assume role with OIDC: Not authorized to perform sts:AssumeRoleWithWebIdentity
Error: Credentials could not be loaded, please check your action inputs: Could not load credentials from any providers (core cause: Unable to get ACTIONS_ID_TOKEN_REQUEST_URL env variable)
Root cause: GitHub issues an OIDC token for the workflow, and AWS IAM uses the role's trust policy to verify: aud must be sts.amazonaws.com; sub must match, for example repo:org/infra:ref:refs/heads/main,repo:org/infra:pull_request,repo:org/infra:environment:prod. A job that uses an environment has a sub in environment format rather than branch format— this is the most common mismatch. Without permissions: id-token: write it, no token can be obtained at all.
Diagnostic commands
aws iam get-role --role-name gh-tf-plan --query 'Role.AssumeRolePolicyDocument' | jq .
aws iam list-open-id-connect-providers
# Temporarily print the token claims in the workflow (do not print the token itself):
# curl -sH "Authorization: bearer $ACTIONS_ID_TOKEN_REQUEST_TOKEN" "$ACTIONS_ID_TOKEN_REQUEST_URL&audience=sts.amazonaws.com" | jq -r .value | cut -d. -f2 | base64 -d 2>/dev/null | jq '{sub,aud,environment,ref}'
Fix
permissions:
id-token: write
contents: read
jobs:
plan:
runs-on: ubuntu-latest
steps:
- uses: aws-actions/configure-aws-credentials@v4
with:
role-to-assume: arn:aws:iam::111122223333:role/gh-tf-plan
aws-region: ca-central-1
"Condition": {
"StringEquals": { "token.actions.githubusercontent.com:aud": "sts.amazonaws.com" },
"StringLike": { "token.actions.githubusercontent.com:sub": ["repo:org/infra:pull_request", "repo:org/infra:ref:refs/heads/main"] }
}
Prevention & best practices
- Separate the plan role (read-only + state read/write lock) from the apply role (write); the apply role should trust only
environment:prod. - Do not use
repo:org/*such overly broad sub wildcards.
#43 AADSTS700213: No matching federated identity record found for presented assertion subject (GitHub → Azure)
Error: building account: ... AADSTS700213: No matching federated identity record found for presented assertion subject 'repo:org/infra:environment:prod'. Check your federated identity credential Subject, Audience and Issuer against the presented assertion.
Root cause: The Entra ID application's / user-assigned managed identity's federated credential requires issuer, subject, and audience to match exactly (subject does not support wildcards; for the newer "flexible federated identity credentials" feature, refer to the official documentation). When the job uses an environment, the subject becomes repo:org/infra:environment:prod, but the federated credential is configured for ref:refs/heads/main. Other related errors: AADSTS70021: No matching federated identity record found for presented assertion, or audience is not api://AzureADTokenExchange.
Diagnostic commands
az ad app federated-credential list --id <APP_ID> --query '[].{name:name, subject:subject, aud:audiences[0]}' -o table
Name Subject Aud ----- -------------------------------------- ------------------------- main repo:org/infra:ref:refs/heads/main api://AzureADTokenExchange
Fix
az ad app federated-credential create --id <APP_ID> --parameters '{
"name": "env-prod",
"issuer": "https://token.actions.githubusercontent.com",
"subject": "repo:org/infra:environment:prod",
"audiences": ["api://AzureADTokenExchange"]
}'
On the Terraform side: ARM_USE_OIDC=true,ARM_CLIENT_ID,ARM_TENANT_ID, and ARM_SUBSCRIPTION_ID; the backend also needs use_oidc = true (#10).
Prevention & best practices
Create separate federated credentials for the PR (pull_request), main, and each environment, each mapped to an identity with different permissions.
#44 The plan reviewed in the PR was "2 to change", but after merge, apply actually executed 5 changes (plan and apply inconsistent)
Symptom: The changes approved by reviewers differ from the changes actually executed; sometimes apply even destroys resources that did not appear in the PR.
Root cause: At apply time, Terraform recalculates the plan (terraform apply -auto-approve ) instead of the saved plan file. Between PR review and merge, other PRs may have changed the state, the cloud may have drifted, module/provider versions may float (#39), and variable sources may differ (the PR job and the main job use different tfvars/environment variables).
Diagnostic commands
grep -n 'terraform apply' .github/workflows/*.yml # compare the Plan: line in the PR's plan with the one in the apply log gh run view <RUN_ID> --log | grep -E 'Plan:|Apply complete'
Fix
- Option A (simple): after merging, on main, run
plan -out=tfplan, manual approval (environment protection rules), thenapply tfplan— what is approved is what gets executed. - Option B: the plan generated in the PR is stored as an artifact; after merging, apply that file directly; when state has changed, Terraform refuses (
Saved plan is stale, #6), in which case re-plan and re-approve. - Run the same state serially (concurrency); a merge queue guarantees ordering.
Prevention & best practices
Plan files contain sensitive values; set a short retention period on artifacts and restrict access; in CI, output a plan summary (counts of add/change/destroy) as the basis for approval.
#45 Error: Inconsistent dependency lock file
Error: Inconsistent dependency lock file The following dependency selections recorded in the lock file are inconsistent with the current configuration: - provider registry.terraform.io/hashicorp/random: required by this configuration but no version is selected To update the locked dependency selections to match a changed configuration, run: terraform init -upgrade
Symptom: A developer added a provider (or a new module introduced a new provider) and forgot to update the lock file when committing; CI uses -lockfile=readonly , and init fails.
Root cause: The lock file must cover all providers required by the configuration. -lockfile=readonly Init must not modify the lock file—this is exactly what we want: the lock file may only change through reviewed commits.
Diagnostic commands
terraform providers | grep -o 'provider\[[^]]*\]' | sort -u grep '^provider' .terraform.lock.hcl
Fix
Locally, run terraform init -upgrade (or only terraform init to add the new provider), then terraform providers lock -platform=… to fill in the platforms, and commit the lock file.
Prevention & best practices
A pre-commit hook checks that the lock file matches the configuration; the PR template reminds people that "adding a provider requires committing the lock file".
#46 Note: Objects have changed outside of Terraform (drift)
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_network_security_group.web has changed
~ resource "azurerm_network_security_group" "web" {
~ security_rule = [
+ {
+ destination_port_range = "22"
+ name = "allow-ssh-debug"
+ source_address_prefix = "*"
...
Symptom: Someone "temporarily" opened port 22 in the portal; the next plan wants to delete it (overwriting the manual change), or a manually changed attribute is ignore_changes masked, with no one knowing about it.
Root cause: Terraform only compares state with the real world during plan/refresh; manual changes between two runs are drift. Drift by itself is not an error, but it makes the next apply produce surprises (reverting hotfixes or deleting other people's resources).
Diagnostic commands
terraform plan -refresh-only -detailed-exitcode; echo "exit=$?" # 0 no changes / 1 error / 2 drift detected
az monitor activity-log list -g rg-tf-lab --offset 24h --query "[?operationName.value=='Microsoft.Network/networkSecurityGroups/write'].{who:caller,when:eventTimestamp}" -o table
Fix
- If the manual change should not exist: apply directly to restore the code state (and open a security incident at the same time).
- If the manual change is a correct hotfix: write it into the code (or
terraform apply -refresh-onlyaccept the state update first, then add the code), and then go through a PR.
Prevention & best practices
- Run a scheduled job (daily)
plan -detailed-exitcode, and create an issue / send an alert when the exit code is 2. - Give people read-only access; emergency changes go through break-glass and are written back to code within 24 hours. HCP Terraform provides managed drift detection (health assessments).
#47 Policy denial: FAIL - tfplan.json - main - Storage account must disable public blob access (Policy as Code)
FAIL - tfplan.json - main - azurerm_storage_account.logs: allow_nested_items_to_be_public must be false 2 tests, 1 passed, 0 warnings, 1 failure, 0 exceptions
Symptom: The PR's plan succeeds, but the policy check step fails and the PR cannot be merged; in HCP Terraform, the policy set check shows as failed (Sentinel's hard-mandatory cannot be overridden; soft-mandatory can be overridden by someone with permission). Starting with Terraform 1.17, native Terraform Policy is generally available (plan/apply -policies=<directory>); for its output format, refer to the official documentation.
Root cause: The policy engine checks plan JSON (terraform show -json tfplan) in resource_changes[].change.after. Note that attributes whose value is (known after apply) appear in the JSON under after_unknown, and the policy must handle them separately; otherwise it misjudges.
Diagnostic commands
terraform plan -out=tfplan && terraform show -json tfplan > tfplan.json jq '.resource_changes[] | select(.type=="azurerm_storage_account") | .change.after.allow_nested_items_to_be_public' tfplan.json conftest test tfplan.json -p policy/
Fix
Change the configuration to match the policy (allow_nested_items_to_be_public = false); if the policy is a false positive, change the policy (open a PR to the policy repository), or request an exception through the process (with an expiry date). Do not skip the policy step in pipelines.
Prevention & best practices
- Grade policies: advisory (warn) → soft → hard; run new policies in warning mode for two weeks first.
- Make secure defaults the defaults in modules (secure by default), to reduce policy denials.
- Static scanning (Checkov, Trivy config) complements plan-based policies.
#48 Error: Unsupported Terraform Core version
Error: Unsupported Terraform Core version on versions.tf line 2, in terraform: 2: required_version = "~> 1.17.0" This configuration does not support Terraform version 1.16.7. To proceed, either choose another supported Terraform version or update this version constraint. Version constraints are normally set for good reason, so updating the constraint may lead to other errors or unexpected behavior.
Symptom: The Terraform version bundled in the CI runner image does not match the repository constraint; a child module's required_version constraint is stricter than the root module's.
Root cause: Terraform checks the required_version constraints of the root module and all child modules; if any one is not satisfied, it fails. This protects against #8 (state written by a newer version) and against new syntax being misparsed by older versions.
Diagnostic commands
terraform version grep -rn 'required_version' --include=*.tf . .terraform/modules 2>/dev/null
Fix
- uses: hashicorp/setup-terraform@v3
with:
terraform_version: 1.17.2
terraform_wrapper: false
Prevention & best practices
The root module uses ~> 1.17.0 (pinning the minor version); reusable modules only declare a lower bound (>= 1.11, i.e., the version required by the newest feature used); the team uses .terraform-version file to standardize local versions.
#49 Error: Moved object still exists / after refactoring a module, plan wants to destroy and recreate all resources
Error: Moved object still exists
on moved.tf line 1:
1: moved {
This statement declares a move from aws_s3_bucket.logs, but that resource is
still declared at main.tf:12.
Change your configuration so that this resource will be declared as
aws_s3_bucket.this instead.
Symptom: After moving resources from the root module into a child module (aws_s3_bucket.logs → module.logs.aws_s3_bucket.this), plan shows "1 to add, 1 to destroy"; after adding a moved block, the error above appears.
Root cause: Terraform identifies resources by address, so when the address changes it is treated as "delete one old, create one new." The moved block tells Terraform to change only the address in state; but from the old address must already be removed from the configuration, otherwise the two conflict. There are also related errors such as Ambiguous move statements (two moved blocks pointing at the same target), among other related errors.
Diagnostic commands
grep -rn 'resource "aws_s3_bucket" "logs"' --include=*.tf . terraform plan | grep -E 'has moved to|will be destroyed|will be created'
Fix
# After deleting the old resource block in the root module:
moved {
from = aws_s3_bucket.logs
to = module.logs.aws_s3_bucket.this
}
Expected plan: # aws_s3_bucket.logs has moved to module.logs.aws_s3_bucket.this,0 to add, 0 to destroy. Authors of reusable modules should keep moved blocks inside the module so all callers migrate automatically when they upgrade.
Prevention & best practices
Acceptance criteria for refactoring PRs: the plan contains only moves, with no add/destroy; for moves across states, use removed (destroy = false) + the import block in the target state.
#50 Passwords and tokens appear in CI logs / PR comments (TF_LOG, plan output leaks secrets)
Symptom: To troubleshoot, set TF_LOG=DEBUG, and the logs show the Authorization: Bearer … value in the HTTP request header and connection strings in response bodies; or the plan posted by the PR comment bot contains values of variables not marked sensitive.
Root cause: DEBUG/TRACE logs record the provider's raw API requests and responses; Terraform neither does nor can fully redact them; sensitive (marking as sensitive) only applies to the plan output that Terraform itself renders; it has no effect on unmarked variables, on logs, or on terraform show -json 's raw values (sensitive values still exist in the JSON; they are only sensitive_values flagged by path) do not help.
Diagnostic commands
grep -rnE 'TF_LOG|show -json|tfplan' .github/workflows/ gh run view <RUN_ID> --log | grep -ciE 'authorization: bearer|password|AccountKey='
Fix
- Rotate leaked credentials immediately; delete the related run logs (in GitHub, you can delete workflow run logs) and the PR comments.
- Remove
TF_LOGfrom the pipeline; when debugging is needed, enable it locally or in an isolated environment, writing logs to a file (TF_LOG_PATH), and delete it when done. - Mark all secret variables with
sensitive = true; where possible, use ephemeral / write-only instead (#5).
Prevention & best practices
- PR comments should only post
terraform show -no-color tfplanhuman-readable output (sensitive values masked), not JSON. - Enable secret scanning (push protection) in the repository, and set a short retention period for CI logs.
CI pipeline failure simulator
Choose a failure scenario and run it: the pipeline executes stage by stage, stops at the stage where it would really fail, and shows the logs and the corresponding issue. Use it to practice "reading logs to locate the stage".
Lab 4-A: drift detection (#46)
mkdir -p ~/lab8/m4a && cd ~/lab8/m4a
cat > main.tf <<'EOF'
terraform {
required_providers { docker = { source = "kreuzwerker/docker", version = "~> 3.0" } }
}
resource "docker_image" "nginx" { name = "nginx:alpine" }
resource "docker_container" "web" {
name = "lab8-web"
image = docker_image.nginx.image_id
ports {
internal = 80
external = 8088
}
}
EOF
terraform init -input=false >/dev/null && terraform apply -auto-approve | tail -1docker rm -f lab8-web terraform plan -refresh-only -detailed-exitcode >/dev/null; echo "exit=$?" terraform plan | grep -E 'Objects have changed|has been deleted|will be created'
exit=2 Note: Objects have changed outside of Terraform # docker_container.web has been deleted # docker_container.web will be created
terraform apply -auto-approve; then run again, plan -detailed-exitcode the exit code should be 0.terraform destroy -auto-approve; cd ..; rm -rf m4aLab 4-B: offline init and filesystem mirror (#41)
mkdir -p ~/lab8/m4b && cd ~/lab8/m4b
printf 'terraform {\n required_providers { random = { source = "hashicorp/random" } }\n}\nresource "random_id" "x" { byte_length = 4 }\n' > main.tf
terraform providers mirror ~/lab8/mirror && find ~/lab8/mirror -name '*.zip'echo '127.0.0.1 registry.terraform.io releases.hashicorp.com' | sudo tee -a /etc/hosts
rm -rf .terraform .terraform.lock.hcl
TF_PLUGIN_CACHE_DIR= terraform init -input=false 2>&1 | grep -m1 -iE 'could not connect|failed'
cat > lab8.tfrc <<EOF
provider_installation {
filesystem_mirror { path = "$HOME/lab8/mirror" }
}
EOF
TF_CLI_CONFIG_FILE=$PWD/lab8.tfrc TF_PLUGIN_CACHE_DIR= terraform init -input=false | tail -1... could not connect to registry.terraform.io ... Terraform has been successfully initialized!
sudo sed -i '/registry.terraform.io releases.hashicorp.com/d' /etc/hosts; cd ..; rm -rf m4b mirrorLab 4-C: refactor into a child module and moved (#49)
mkdir -p ~/lab8/m4c/modules/pet && cd ~/lab8/m4c
echo 'resource "random_pet" "logs" { length = 2 }' > main.tf
terraform init -input=false >/dev/null && terraform apply -auto-approve | tail -1
echo 'resource "random_pet" "this" { length = 2 }' > modules/pet/main.tf
cat > main.tf <<'EOF'
module "logs" { source = "./modules/pet" }
moved {
from = random_pet.logs
to = module.logs.random_pet.this
}
EOF
terraform init -input=false >/dev/null && terraform plan | grep -E 'moved|Plan:'# random_pet.logs has moved to module.logs.random_pet.this Plan: 0 to add, 0 to change, 0 to destroy.
resource "random_pet" "logs" { length = 2 }, and plan reports Moved object still exists; delete it afterward to restore the original state.terraform apply -auto-approve && terraform destroy -auto-approve; cd ..; rm -rf m4cTeaching video (title and channel verified via YouTube oEmbed)
No verified video specifically on Terraform OIDC troubleshooting was found. Storyboard:
Official documentation
Module 5 · Part B: Core Concepts & Architecture (Questions 1–13)
- Use the four keywords "declarative + state + dependency graph + provider plugin" to explain what Terraform is and how it works.
- Explain what each step of init/plan/apply does, and the differences between resource and data, count and for_each, and the lifecycle arguments.
- Be able to go deep into PlanResourceChange / ApplyResourceChange and unknown values, and answer the advanced follow-up "how does plan decide to replace?"
Browse the questions and their focus points first, mark the ones you're unsure about; click a row to jump to the detailed explanation.
Q1. What is Infrastructure as Code (IaC)? What does Terraform's declarative model mean?Beginner
30-second answer
IaC describes infrastructure with version-controlled code, and creates, changes, and destroys it through review and automation. Terraform is declarative: you describe the "desired end state"; Terraform compares state with the real world to compute the differences (plan), then calls the provider to execute the minimum set of API operations to reach the goal; it does not write "do A, then B" like a script.
In-depth answer
- Benefits: repeatable (the same code builds the same environment), reviewable (PR + plan), auditable (Git history), rollback-able (revert the code and apply again), and self-documenting.
- Declarative vs imperative: declarative is naturally idempotent—the second apply is No changes; imperative scripts must handle "already exists" themselves.
- Terraform's "state convergence" only covers the attributes it manages; unmanaged attributes and manually created resources are not controlled (drift).
resource "azurerm_resource_group" "rg" {
name = "rg-tf-lab"
location = "canadacentral" # describes only "what", not "how to call the API"
}
Common follow-up questions
- Doesn't declarative mean you don't need to care about order? Order is derived automatically from the dependency graph, but hidden dependencies need depends_on (#24).
- Can IaC prevent manual changes? No; it requires permission controls plus drift detection.
Bonus points
Mention the ideas of "immutable infrastructure" and "GitOps"; point out that Terraform's HCL also has for expressions, functions, and other "limited imperative capabilities", but without side effects.
Common wrong answers
"Terraform is just a script tool that calls cloud APIs"—this ignores the core of state and difference computation.
See Lesson 1 Module 1.
Q2. How does Terraform differ from Ansible, CloudFormation/Bicep, and Pulumi? How do you choose?Beginner
30-second answer
Terraform: declarative resource orchestration across multiple clouds and services; it has state and the largest ecosystem. Ansible: configuration management driven mainly by procedural tasks, suited to configuring machines internally (no state; relies on module idempotency). CloudFormation/Bicep: single-cloud native; state is managed by the cloud; fastest support for new services. Pulumi: writes IaC in general-purpose programming languages; its model is similar to Terraform.
In-depth answer
| Terraform | Ansible | Bicep/CFN | Pulumi | |
|---|---|---|---|---|
| Style | declarative HCL | procedural YAML | declarative | general-purpose language |
| state | self-managed / HCP | None | cloud-managed | self-managed / Pulumi Cloud |
| Strengths | cloud resource lifecycle | OS/application configuration, orchestration | deep single-cloud integration | complex logic, developer-friendly |
Common combination: Terraform creates VMs/networks/managed services → Ansible configures the inside of the VMs (the next course in this program).
Common follow-up questions
- Ansible can also create cloud resources, so why use Terraform? Ansible has no state; deleting resources, detecting drift, and computing differences all have to be written by you.
- OpenTofu? See Q12.
Bonus points
Give selection criteria: team skills, multi-cloud needs, compliance (whether self-managed state is allowed), and how quickly new services are released.
Common wrong answers
Simply saying "Terraform is better than Ansible"—the two have different roles and are often used together.
See Lesson 1,Ansible Hour 8.
Q3. Describe what terraform init / plan / apply / destroy each do.Beginner
30-second answer
init: initializes the backend, downloads providers per the constraints and lock file, and installs modules. plan: acquires the lock, reads state, refreshes real resources, compares with the configuration, and outputs the change plan (can be -out saved). apply: executes the plan (if no plan file is given, it plans first and then asks for confirmation), calls providers in parallel according to the dependency graph, and writes each result back to state as it completes. destroy: equivalent to apply -destroy, deleting in reverse dependency order.
In-depth answer
terraform init -input=false -lockfile=readonly terraform fmt -check && terraform validate terraform plan -out=tfplan -input=false terraform show tfplan # review terraform apply tfplan # executes exactly the reviewed plan
Plan modes: normal,-destroy,-refresh-only (only syncs the real world into state).
Common follow-up questions
- Does validate access the cloud? No; it only does syntax and type checking (it requires that init has been run to load the provider schema).
- Does plan modify state? It does not persist (refresh results are only in memory);
apply -refresh-onlyonly apply writes it.
Bonus points
Mention -detailed-exitcode (0/1/2) and its use in CI, and that plan files contain sensitive values.
Common wrong answers
"plan is just a preview of apply and can be skipped"—in production, plan is the basis for review and approval.
See Lesson 1 workflow.
Q4. What is the relationship between Terraform Core and providers? How do providers work?Intermediate
30-second answer
Core is responsible for parsing HCL, building the dependency graph, managing state, and computing plans; a provider is a separate plugin process, and Core communicates with it through gRPC (plugin protocol v5/v6), calling it to get the schema and validate configuration,PlanResourceChange,ApplyResourceChange,ReadResource,ImportResourceState and so on. The provider then translates these calls into cloud API requests.
In-depth answer
- Providers are downloaded from the Registry to
.terraform/providers, versions are pinned by the lock file and verified with checksums. - One apply: Core walks the graph's nodes → calls the provider's ApplyResourceChange for each resource → the provider calls the cloud API and polls until completion → returns the new state → Core writes state.
- Providers are developed with the Plugin Framework (new) or SDKv2 (legacy); new features (ephemeral, write-only, list resources, actions) require provider-side support.
TF_LOG=TRACE terraform plan 2>&1 | grep -m5 -E 'GRPCProvider|plugin'
Common follow-up questions
- Does Core know about aws_instance? No; it only knows which resources and attributes exist from the provider schema.
- Can providers communicate directly with each other? No; data is passed only through Core's expressions.
Bonus points
Mention that a provider can return attribute paths that "require replacement" (RequiresReplace); this is the origin of # forces replacement (Q13).
Common wrong answers
"Providers are built-in code in Terraform"—since 0.10, providers have been released separately from Core.
Q5. Why does Terraform need state? What happens without state?Beginner
30-second answer
State is the mapping of "resource addresses in configuration ↔ real resource IDs", plus attribute caching, dependency relationships, and metadata. Without it, Terraform cannot know aws_instance.web which instance each address corresponds to, which resources it created itself (so it knows what to delete), or whether resources removed from configuration should be destroyed.
In-depth answer
- Mapping: many cloud APIs do not support reliable lookup by "name"; the ID is the unique identifier.
- Metadata: dependency relationships (deletion order), provider configuration addresses (#35), schema version (used for upgrades).
- Performance: at large scale it reduces API calls (
-refresh=false, and 1.17's-minimal-refresh). - Collaboration: remote state + locking lets the team share the same view.
terraform state list terraform state show azurerm_resource_group.rg
Common follow-up questions
- What are the risks in state? Plaintext secrets (Q17).
- Can tags replace state? Not all resources support tags, and tags cannot express dependencies or ownership.
Bonus points
Mention the role of serial and lineage (preventing overwriting a newer snapshot, #6).
Common wrong answers
"State is just a cache; deleting it doesn't matter"—after deleting state, Terraform will try to recreate all resources.
See Lesson 1 state.
Q6. How does Terraform decide the order in which resources are created? What is the difference between implicit and explicit dependencies?Intermediate
30-second answer
Terraform builds a directed acyclic graph from expression references (implicit dependencies), plus depends_on (explicit dependencies), then topologically sorts it and runs the nodes that have no dependencies on each other in parallel (default parallelism 10). Destruction runs in reverse order.
In-depth answer
resource "azurerm_subnet" "app" {
virtual_network_name = azurerm_virtual_network.vnet.name # implicit dependency
}
resource "azurerm_linux_web_app" "app" {
# ...
depends_on = [azurerm_role_assignment.acr_pull] # explicit: no reference, but must complete first
}
terraform graphThe graph can be output as a DOT diagram.create_before_destroychanges the node order during replacement (and propagates to dependents).- A module-level depends_on defers reading all data sources in the module; use it with care.
Common follow-up questions
- What if a cycle appears? See #13: split into standalone rule resources and adjust module boundaries.
- How do you adjust parallelism?
-parallelism=N, and lower it when throttled (#30).
Bonus points
Point out that the dependency graph contains not only resources but also provider configurations, variables, outputs, and data source nodes.
Common wrong answers
"It executes in the order written in the files"—file order has nothing to do with execution order.
Q7. What is the difference between a resource and a data source? When is a data source read during the apply phase?Beginner
30-second answer
A resource is an object that Terraform manages the lifecycle of (create/update/delete); a data source only reads information about existing objects (such as an existing VNet or the latest image ID), and never creates or deletes them. A data source is usually read during the plan phase; if its arguments depend on resources not yet created (unknown values), or it has depends_on pointing to resources with changes, its read is deferred to the apply phase.
In-depth answer
data "azurerm_client_config" "current" {}
data "aws_ami" "ubuntu" {
most_recent = true
owners = ["099720109477"]
filter {
name = "name"
values = ["ubuntu/images/hvm-ssd-gp3/ubuntu-noble-24.04-amd64-server-*"]
}
}
Note most_recent causes instance replacement with every new image release (#16).
Common follow-up questions
- What happens if a data source cannot find the object? Most cases fail with an error; for "optionally exists", use a list-type data source or
try(). - What is the difference between an ephemeral resource and a data source? An ephemeral resource is opened and closed on every run, and its result is not written to state or plan (Q17).
Bonus points
Use data sources for cross-state decoupling, replacing terraform_remote_state (#12).
Common wrong answers
"Data sources are also deleted by terraform destroy"—no, they aren't.
Q8. How do you deploy the same configuration to multiple regions/accounts? How do you use provider aliases?Intermediate
30-second answer
Define multiple configurations for the same provider, distinguished by alias ; resources select with provider = aws.west , and modules pass them in with providers = { aws = aws.west } . Cross-account setups usually use a different assume_role for each alias.
In-depth answer
provider "aws" { region = "ca-central-1" }
provider "aws" {
alias = "dr"
region = "ca-west-1"
assume_role { role_arn = "arn:aws:iam::222233334444:role/tf-deploy" }
}
module "replica" {
source = "./modules/bucket"
providers = { aws = aws.dr }
}
# declare the needed aliases inside the module
terraform {
required_providers {
aws = { source = "hashicorp/aws", configuration_aliases = [aws.peer] }
}
}
From 1.17 onward, required_providers can use variable/local (more flexible for things like version constraints); refer to the official documentation for specific usage. The provider block itself still cannot use count/for_each to dynamically generate multiple configurations (per the current documentation); for multi-region, typically write one alias per region, or split into multiple root modules/Stacks.
Common follow-up questions
- Can you write provider blocks inside modules? You can, but it is not recommended; it leads to #35.
- Multiple subscriptions? azurerm works the same way: set
subscription_idfor each alias.
Bonus points
Mention Terraform Stacks (HCP Terraform) for orchestrating deployment of the same component across multiple environments/regions.
Common wrong answers
"Copy the code and change the region"—duplicated code is hard to maintain.
Q9. Which lifecycle meta-arguments exist? What problem does each solve?Intermediate
30-second answer
create_before_destroy (on replacement, create the new one before destroying the old one, reducing downtime),prevent_destroy (errors when a destroy is planned),ignore_changes (ignores differences in certain attributes),replace_triggered_by (forces replacement when other objects change), and precondition/postcondition assertions.
In-depth answer
resource "azurerm_linux_virtual_machine_scale_set" "web" {
# ...
lifecycle {
create_before_destroy = true
ignore_changes = [instances] # changed by autoscaling
replace_triggered_by = [terraform_data.image_version] # replace when the image version changes
precondition {
condition = var.instances >= 2
error_message = "Production requires at least 2 instances."
}
}
}
- create_before_destroy requires names that can coexist (use
name_prefixor a random suffix). - ignore_changes hides drift; add a comment explaining why.
Common follow-up questions
- Can prevent_destroy stop someone from deleting the resource block? No; deleting the resource block removes the lifecycle along with it (#18).
- What about taint? has been replaced by
apply -replace=ADDR.
Bonus points
Add the removed block's lifecycle { destroy = false }, and cloud-side deletion protection as a second layer of safety.
Common wrong answers
"ignore_changes = all can solve perpetual diffs"—this makes Terraform lose management of the resource.
See Lesson 2 lifecycle.
Q10. What is the difference between count and for_each? What is each suited for?Intermediate
30-second answer
count creates N instances from an integer, and the address is the index [0]; for_each creates instances from a map/set, and the address is the key ["api"]. When an element in the middle of a list is removed, count causes address drift and unexpected replacement; for_each only affects the deleted key. Use for_each for objects with identity; use count for conditional creation of "0 or 1" and for fully identical copies.
In-depth answer
resource "azurerm_subnet" "s" {
for_each = { app = "10.10.1.0/24", db = "10.10.2.0/24" }
name = "snet-${each.key}"
address_prefixes = [each.value]
virtual_network_name = azurerm_virtual_network.vnet.name
resource_group_name = azurerm_resource_group.rg.name
}
resource "azurerm_public_ip" "pip" {
count = var.public ? 1 : 0 # conditional creation
# ...
}
For both, the keys/counts must be known at plan time (#14, #15); to migrate from count to for_each, use moved blocks (#17).
Common follow-up questions
- Can for_each use a list? It needs
toset()toset(...) or conversion to a map. - Can you use both at the same time? Not on the same resource.
Bonus points
Mention the experimental deferred actions feature (-allow-deferral) that attempts to allow unknown count/for_each.
Common wrong answers
"for_each is just syntactic sugar"—the address model is different and affects state stability.
See Lesson 1.
Q11. What is the difference between refresh, -refresh-only, -replace, and taint?Intermediate
30-second answer
refresh is a stage of plan: it reads the real resources and updates the in-memory state. plan/apply -refresh-only Only syncs the real world into state (accepts drift), with no configuration changes. -replace=ADDR Forces replacement of a resource within a single plan. taint is an older command that marks a resource for replacement and writes state immediately; it is no longer recommended. terraform refresh The command is deprecated; it is equivalent to an unconfirmed apply -refresh-only.
In-depth answer
terraform plan -refresh-only # view drift terraform apply -refresh-only # accept drift and write it to state terraform apply -replace='azurerm_linux_virtual_machine.vm' terraform plan -refresh=false # skip refresh (fast, but may be based on stale data) terraform plan -minimal-refresh # 1.17: refresh only resources with changes (refer to official documentation)
Common follow-up questions
- Why is -replace better than taint? It appears in the plan where it can be reviewed, and it does not modify shared state in advance.
Bonus points
Explain the risk of refresh-only apply: if a real resource was accidentally deleted, state will "forget" it.
Common wrong answers
"refresh modifies cloud resources"—refresh is read-only.
See Lesson 7.
Q12. What is the relationship and difference between Terraform and OpenTofu?Intermediate
30-second answer
In 2023, HashiCorp changed the Terraform license from MPL 2.0 to BSL 1.1 (HashiCorp was later acquired by IBM); the community forked OpenTofu from the MPL code of Terraform 1.5, hosted by the Linux Foundation. The two are largely compatible in HCL and provider protocol, but have since evolved separately: OpenTofu has client-side state encryption, early variable evaluation, and so on; Terraform has HCP Terraform integration, Stacks, Terraform Policy, actions, list resources, and more.
In-depth answer
- The BSL restricts "offering a product that competes with HashiCorp"; the vast majority of internal enterprise use is unaffected (refer to legal advice).
- Migration: within the compatibility window of minor versions, state can be interchanged, but once you use features unique to the other side, they are no longer interoperable; registry addresses differ (registry.opentofu.org).
- This course's version baseline: Terraform 1.17.x; OpenTofu 1.13.x (latest verified at 1.13.9).
Common follow-up questions
- Which would you choose? Choose based on license policy, whether HCP Terraform is needed, state encryption requirements, and existing team investment.
Bonus points
Point out that the new features of either need provider support too; when choosing, check the compatibility of key providers.
Common wrong answers
"Terraform is now closed source"—the source code is still public; only the license changed to BSL.
Q13. How does plan decide between "create / update in place / replace / delete"? What is "(known after apply)"?Advanced
30-second answer
For each resource, Core compares three sets of data: the prior state, the real state after refresh, and the desired values in the configuration; then it calls the provider's PlanResourceChange (PlanResourceChange): the provider returns the planned new state and which attributes change need replacement (RequiresReplace). Not in state → create; in state but not in configuration → delete; has differences without needing replacement → update; has attributes requiring replacement → replace (by default, destroy first, then create). Values that can only be determined at apply time are marked unknown and displayed as (known after apply).
In-depth answer
- Unknown values propagate along the dependency graph: the related attributes of dependents also become unknown, and data sources may be deferred until apply.
- At apply time, Core calls PlanResourceChange once more (with the newly known values); it must match the original plan, otherwise it reports "inconsistent final plan" (#21).
- In the plan JSON,
change.actions(such as["delete","create"]),replace_paths,after_unknownare machine-readable results that policies and gates rely on.
terraform show -json tfplan | jq '.resource_changes[] | {address, actions: .change.actions, replace_paths: .change.replace_paths}'
Common follow-up questions
- Why can't count/for_each use unknown values? They determine instance addresses, so they must be known when the graph is expanded (#14).
- At which step are moved/import handled? Adjust the addresses/import objects in state before planning, then compare normally.
Bonus points
Name the three RPCs ReadResource (refresh), PlanResourceChange, and ApplyResourceChange, and note that a provider can fill in default values through "planned modifications".
Common wrong answers
"Terraform directly compares the text of configuration and state"—in fact it is a structured comparison involving the provider, and it includes a refresh of the real world.
Scenario 5-1: Persuading the team to move from "portal clicks + scripts" to Terraform
The team has 3 environments on Azure, all created manually, with occasional az CLI scripts. The manager asks: what are the benefits, risks, and phased plan for introducing Terraform?
Key points of the reference answer
- Benefits: environment consistency (dev/test/prod use the same code), reviewable changes (PR + plan), auditing, disaster recovery rebuild capability, and reduced configuration drift.
- Risks: effort to bring existing resources under management (import / terraform query), state security, team skills, and bulk deletions caused by mistakes.
- Phases: ① set up the state backend (encryption, versioning, locking) and the CI skeleton; ② use Terraform for all new projects; ③ use import blocks to bring existing resources under management layer by layer (network → shared services → applications); ④ revoke portal write permissions and set up drift detection; ⑤ modularization and policies.
- Metrics: environment creation time, change failure rate, number of drift alerts.
Scenario 5-2: One apply deleted the production database
A developer changed the RDS identifier attribute; CI auto-applied it, the database was replaced, and data was lost (a snapshot from 24 hours earlier exists). In the postmortem, what technical and process improvements would you propose?
Key points of the reference answer
- Technical:
prevent_destroy,deletion_protection,skip_final_snapshot = false, PITR; a CI gate that detects delete actions on stateful resources in the plan (the plan JSON from Q13). - Process: apply must be based on a manually approved plan file (#44); production apply requires environment approval; the plan summary highlights the number of destroys.
- Recovery: restore from the snapshot + backfill data at the application layer; use import to bring the new instance under management, or roll back the code.
- Culture: blameless postmortem; automate checks instead of relying on "being more careful".
Teaching video (title and channel verified via YouTube oEmbed)
No verified video specifically on Terraform interview questions was found. It is recommended to use this module's "mock interview" and record yourself for playback.
Module 6 · Part B: State, Modules & HCL (Questions 14–25)
- Explain the locking implementation of remote backends and the use cases for state subcommands and moved/import/removed blocks.
- Answer with a complete scheme for state secrets: sensitive, ephemeral, write-only, backend encryption, permissions.
- Master module design, version constraints, variable precedence, expressions and the type system, validation and
terraform testtesting (key points for answering).
Q14. What do remote backends do? How are locks implemented in the S3 and azurerm backends?Intermediate
30-second answer
A remote backend lets the team share one state and provides locking, version history, and encryption. The S3 backend uses use_lockfile = true a conditional S3 write to create <key>.tflock an object to implement locking (the DynamoDB lock is deprecated); the azurerm backend uses a blob lease to implement locking; HCP Terraform has built-in locking and a run queue.
In-depth answer
- The backend block cannot use variables; you can use
-backend-config=file.hclor inject partial configuration at init time. - Must be paired with: versioning/soft delete, encryption (SSE-KMS / storage encryption), least privilege, and public access restrictions.
- State granularity: one key per environment × per layer, reducing blast radius and lock contention.
terraform init -backend-config=env/prod.s3.tfbackend
Common follow-up questions
- What if a lock is left behind? After confirming no one is running it,
force-unlock(#1). - How do you migrate a backend?
init -migrate-state(#3).
Bonus points
Know that use_lockfile during migration, it can coexist with dynamodb_table (#11); the state bucket itself is managed by a separate "bootstrap" configuration.
Common wrong answers
"Committing tfstate to Git is remote state"—it has no locking, leaks secrets, and causes merge conflicts.
Q15. Which terraform state subcommands are commonly used? When is "state surgery" needed?Intermediate
30-second answer
state list/show (view),state mv (change addresses),state rm (forget a resource without deleting it),state pull/push (export/upload the entire state),state replace-provider (change the provider source address). Now it is recommended to prefer using declarative moved/removed/import blocks; use commands directly only in emergencies.
In-depth answer
terraform state pull > backup.tfstate # before any surgery terraform state mv 'aws_instance.web' 'module.web.aws_instance.this' terraform state rm 'azurerm_resource_group.legacy' # hand over to another state or stop managing terraform state replace-provider registry.terraform.io/-/docker registry.terraform.io/kreuzwerker/docker
Scenarios: refactoring addresses, splitting/merging state, repairing corruption (#2), migrating provider sources.
Common follow-up questions
- Why are blocks better than commands? Blocks can be reviewed in PRs, take effect automatically in all environments, and appear in the plan; commands directly modify shared state and leave no review trail.
Bonus points
Mention that state push validates lineage/serial,-force skipping validation is extremely dangerous.
Common wrong answers
"Directly editing the tfstate JSON"—easy to corrupt, and bypasses validation.
Q16. What problem does each of the moved, import, and removed blocks solve?Intermediate
30-second answer
moved (1.1): when a resource address changes (renaming, moving into a module, count→for_each), only update the state address, avoiding destroy and recreate. import (1.5): bring existing real resources into state; can be combined with -generate-config-out to generate configuration. removed (1.7): when removing a resource from configuration, choose to forget it from state only (destroy = false) without deleting the real resource.
In-depth answer
moved {
from = aws_s3_bucket.logs
to = module.logs.aws_s3_bucket.this
}
import {
to = azurerm_storage_account.sa
id = "/subscriptions/.../storageAccounts/stlab8"
}
removed {
from = azurerm_resource_group.legacy
lifecycle { destroy = false }
}
The for_each argument in import blocks (1.7+) supports bulk import; the 1.14 terraform query block can discover existing resources (list resources) to help generate import configuration.
Common follow-up questions
- Can moved work across states? No; for cross-state moves, use removed + import.
- How long should a moved block be kept? Until all consumers (all environments and module callers) have applied.
Bonus points
Be able to explain the cause of "Moved object still exists" (#49).
Common wrong answers
"import automatically writes the configuration"—the old terraform import command only writes state; generating configuration requires -generate-config-out, and the generated result must be cleaned up manually.
Q17. How do you handle sensitive data in state? What is the difference between sensitive, ephemeral, and write-only?Advanced
30-second answer
sensitive sensitive only hides values in output; they are still written to state and plan. An ephemeral resource (1.10) is opened/fetched temporarily on each run, and its value is not written to the plan or state; a write-only argument (1.11, such as password_wo) passes the value to the provider without storing it, and works together with *_wo_version to trigger updates. In addition, state itself must be encrypted at rest and accessed with least privilege.
In-depth answer
ephemeral "azurerm_key_vault_secret" "db" {
name = "db-admin"
key_vault_id = data.azurerm_key_vault.kv.id
}
resource "aws_db_instance" "db" {
# ...
password_wo = ephemeral.random_password.db.result
password_wo_version = 2
}
variable "token" {
type = string
sensitive = true
ephemeral = true # 1.10+: variables can also be declared ephemeral; they can only be used in ephemeral contexts
}
- Defense in depth: cloud-managed passwords (RDS managed master password, managed identities with no password) > write-only > sensitive.
- OpenTofu provides client-side state encryption; Terraform relies on server-side encryption in the backend / HCP.
Common follow-up questions
- Can an ephemeral resource be referenced by a regular resource argument? No (it can only be used in write-only arguments, provider configuration, and other ephemeral contexts).
- What if it has leaked? Rotate it, and audit access to historical state versions.
Bonus points
Mention that plan files also contain secrets, so CI artifacts need protection (#44, #50).
Common wrong answers
"Marking it sensitive makes it safe."
Q18. How do you design a good Terraform module?Intermediate
30-second answer
A module is a reusable "component": clear boundaries (one responsibility, such as "a storage account with a private endpoint"), a small and stable interface (typed and validated variables, meaningful outputs), secure defaults, no provider blocks, versioning, and documentation and tests.
In-depth answer
- Structure:
main.tf / variables.tf / outputs.tf / versions.tf / README.md / examples/ / tests/. - Composition over nesting: the root module composes several shallow modules and avoids 4 levels of nesting.
- Variables:
type = object({...})+optional()defaults +validation. - Outputs: output the IDs/names and other values downstream needs; avoid outputting the entire resource object (it couples to internal implementation).
- Versioning: semantic versioning; publish breaking changes as a major version and provide moved blocks within the module.
Common follow-up questions
- When should you not write a module? A module used only once, or a "thin wrapper" around a single resource, has no value.
- Can community modules be used directly? Evaluate maintenance activity, pin the version, and read the source code.
Bonus points
Mention using terraform test and tflint/terraform-docs for automatic validation in the module repo's CI, and publishing to a private Registry.
Common wrong answers
"Putting all resources in one giant module, controlled by dozens of boolean switches."
See Lesson 2 modules,Lesson 6.
Q19. What are the module sources? How do version constraints and the lock file work for providers and modules, respectively?Intermediate
30-second answer
Module sources: local paths, the Terraform Registry (public/private; supports version), Git (?ref=), HTTP, S3/GCS, etc. Version constraint operators: =,>=,~> (pessimistic constraint,~> 6.2 means ≥6.2 and <7.0). .terraform.lock.hcl Only locks provider the exact versions and checksums of ; modules are not locked.
In-depth answer
terraform {
required_version = "~> 1.17.0"
required_providers {
azurerm = { source = "hashicorp/azurerm", version = "~> 5.0" }
}
}
module "net" {
source = "Azure/avm-res-network-virtualnetwork/azurerm"
version = "~> 0.8"
}
Upgrade process: terraform init -upgrade → terraform providers lock -platform=… → commit the lock file → validate with plan in dev (#32, #33, #45).
Common follow-up questions
- How do you pin a Git source? A tag or commit SHA; Git sources do not support
versionargument.
Bonus points
Root modules and reusable modules use different constraint strategies (root modules are strict; reusable modules use loose lower bounds).
Common wrong answers
"The lock file also locks module versions."
Q20. How are input variables assigned, and what is their precedence?Beginner
30-second answer
From lowest to highest: the variable's default → environment variables TF_VAR_name → terraform.tfvars → terraform.tfvars.json → *.auto.tfvars/*.auto.tfvars.json (in filename alphabetical order) → command line -var and -var-file (in order of appearance; later ones override earlier). If none is provided and there is no default, Terraform prompts interactively (in CI, use -input=false to make it fail outright).
In-depth answer
export TF_VAR_location=canadacentral terraform plan -var-file=env/prod.tfvars -var 'instances=3'
HCP Terraform also has workspace variables and variable sets. Do not put secrets in committed tfvars; inject them with CI secrets TF_VAR_* or ephemeral data sources.
Common follow-up questions
- How do you pass complex types via environment variables? As an HCL literal string:
TF_VAR_tags='{env="prod"}'.
Bonus points
Mention nullable = false,sensitive, and ephemeral variable attributes.
Common wrong answers
"Environment variables have the highest precedence."
See Lesson 1 variables.
Q21. What is the difference between variable, local, and output? When should you use locals?Beginner
30-second answer
A variable is a module's input (decided by the caller); a local is a module-internal named expression (avoids repetition and improves readability); an output is a module's output (for the caller or terraform output).
In-depth answer
locals {
name_prefix = "${var.app}-${var.env}"
tags = merge(var.tags, { env = var.env, managed_by = "terraform" })
}
output "web_url" {
value = "https://${azurerm_container_app.web.ingress[0].fqdn}"
description = "myapp's access address"
}
Locals cannot be overridden from outside; make "decisions that may change" variables, and make "derived values" locals.
Common follow-up questions
- Can an output be set to sensitive? Yes; an output that references a sensitive value must be marked sensitive, otherwise it errors.
Bonus points
The output's precondition can validate output values.
Common wrong answers
"locals can be assigned in tfvars."
See Lesson 1.
Q22. Explain dynamic blocks, for expressions, and splat expressions, with examples.Intermediate
30-second answer
A for expression transforms a collection into a new list/map (with optional if filtering); a splat [*] is shorthand for pulling attributes from a list; a dynamic block generates repeated nested blocks (for example, multiple security rules) from a collection.
In-depth answer
locals {
public_subnets = { for k, s in var.subnets : k => s.cidr if s.public }
subnet_ids = azurerm_subnet.s[*].id # for count resources; for_each resources use values(...)[*].id
}
resource "azurerm_network_security_group" "web" {
name = "nsg-web"
location = var.location
resource_group_name = var.rg
dynamic "security_rule" {
for_each = var.rules
content {
name = security_rule.key
priority = security_rule.value.priority
direction = "Inbound"
access = "Allow"
protocol = "Tcp"
source_port_range = "*"
destination_port_range = security_rule.value.port
source_address_prefix = security_rule.value.source
destination_address_prefix = "*"
}
}
}
Common follow-up questions
- What are the drawbacks of dynamic blocks? They reduce readability; prefer standalone resources when possible (this also avoids #13 and #22).
Bonus points
When a for expression generating a map hits duplicate keys, it errors; you can use ... grouping: { for s in list : s.zone => s... }.
Common wrong answers
"dynamic can dynamically generate resources"—it only generates nested blocks; use count/for_each to generate resources.
See Lesson 1 expressions.
Q23. Terraform's type system and common functions: optional(), try(), can(), lookup(), merge(), coalesce()?Intermediate
30-second answer
Primitive types string/number/bool, collection types list/set/map, structural types object/tuple; variables use type constraints and automatic conversion. optional(type, default) Makes object attributes optional; try() returns the first expression that doesn't error; can() checks whether an expression can be evaluated (commonly used in validation); lookup() gets a map value with a default; merge() merges maps; coalesce() returns the first non-empty value.
In-depth answer
variable "app" {
type = object({
name = string
replicas = optional(number, 2)
ingress = optional(object({ port = number, external = bool }), { port = 8000, external = true })
})
}
locals {
sku = lookup(var.sku_by_env, var.env, "B1")
owner = try(var.tags["owner"], "platform")
cidr_ok = can(cidrhost(var.cidr, 0))
}
Common follow-up questions
- What is the difference between set and list? A set is unordered, has unique elements, and cannot be accessed by index.
- Does try hide errors? Yes; use it only where something is expected to possibly be missing.
Bonus points
Use terraform console to debug expressions; from 1.8+, provider-defined functions are supported (provider::NAME::FUNC).
Common wrong answers
"Use type = any for all variables"—you lose validation and documentation value.
Q24. What is the difference between variable validation, precondition/postcondition, and check blocks?Advanced
30-second answer
validation: validates input variables (from 1.9, can reference other variables and objects); a failure blocks plan. precondition/postcondition: written in the lifecycle of a resource, data source, or output; it validates assumptions and results, and a failure stops that object and its dependents from continuing. check block (1.5): ongoing health assertions (may include scoped data sources); a failure only produces a warning, does not block apply, and suits post-deployment verification.
In-depth answer
variable "env" {
type = string
validation {
condition = contains(["dev", "test", "prod"], var.env)
error_message = "env must be dev/test/prod."
}
}
data "azurerm_container_app" "web" {
name = "ca-myapp"
resource_group_name = "rg-tf-lab"
lifecycle {
postcondition {
condition = self.ingress[0].external_enabled
error_message = "myapp must be exposed externally."
}
}
}
check "health" {
data "http" "healthz" { url = "https://${azurerm_container_app.web.ingress[0].fqdn}/healthz" }
assert {
condition = data.http.healthz.status_code == 200
error_message = "Health check did not return 200."
}
}
Common follow-up questions
- What's the difference between these and policies (OPA/Sentinel/Terraform Policy)? These are written in the module and maintained by its author; policies are organization-level, independent of code, and enforceable.
Bonus points
HCP Terraform's continuous validation periodically runs check blocks.
Common wrong answers
"A failing check block rolls back the apply"—Terraform has no rollback; a check only produces a warning.
Q25. How do you test Terraform code? How are terraform test and mock_provider used?Advanced
30-second answer
Layered approach: static (fmt, validate, tflint, Checkov/Trivy) → unit (terraform test in command = plan + mock_provider, without accessing the cloud) → integration (command = apply creates real resources in a temporary environment, asserts, and destroys them automatically) → policy testing (on plan JSON). terraform test Became GA in 1.6; test files are *.tftest.hcl; from 1.7, mock providers are supported, and from 1.17, mock_provider supports ephemeral resources.
In-depth answer
# tests/naming.tftest.hcl
mock_provider "azurerm" {}
variables {
app = "myapp"
env = "dev"
}
run "names_follow_convention" {
command = plan
assert {
condition = azurerm_resource_group.rg.name == "rg-myapp-dev"
error_message = "Resource group name does not follow the naming standard"
}
}
run "rejects_bad_env" {
command = plan
variables { env = "qa" }
expect_failures = [var.env]
}
terraform test # run all tests under tests/ terraform test -filter=tests/naming.tftest.hcl
Common follow-up questions
- How does it compare to Terratest? Terratest (Go) suits complex end-to-end validation; terraform test is native and does not require another language.
- Do integration tests leave resources behind if they fail? By default they attempt to destroy; in 1.18 experiments, there is a
terraform test cleanupoption for handling leftovers (refer to official documentation).
Bonus points
Put tests in the module repo's CI; mocks can use override_resource/override_data to specify return values.
Common wrong answers
"If plan runs through, the code is tested."
Scenario 6-1: Splitting a "monolithic state" of 1,200 resources
One repository and one state manage the entire production environment (network, databases, 5 applications); plan takes 25 minutes, often gets throttled, and all teams queue for the lock. Please provide a split plan and migration steps.
Key points of the reference answer
- Split dimension: layer by lifecycle and ownership — network/shared (changes rarely), data (high risk), each application (changes frequently); one state key per layer.
- Interface: layers pass values via data sources/parameter stores, reducing remote_state usage (#12).
- Migration: create the target root module → in the source, use
removedblock (destroy = false), and in the target, use aimportblock (orstate mv -state-outemergency use) → only apply when both sides' plans show 0 add / 0 destroy; migrate layer by layer, non-production first. - Benefit validation: plan time, lock wait, blast radius.
Scenario 6-2: Designing the company's "standard storage account" module
Security requirements: disable public blob access, enforce TLS 1.2, private endpoints, diagnostic logs. The application teams only want to pass a name and environment. How would you design the interface, defaults, testing, and release?
Key points of the reference answer
- Interface:
name,env,subnet_id(private endpoint), optionalcontainers(optional()); security settings are not exposed as variables, or only allow "stricter" values. - Defaults:
allow_nested_items_to_be_public = false,min_tls_version = "TLS1_2",public_network_access_enabled = false. - Validation: name length/character validation; postcondition checks the private endpoint status.
- Testing:
terraform test+ mock assertions on security properties; integration tests in a sandbox subscription. - Release: private Registry, semantic versioning, CHANGELOG, Renovate drives upgrades; policies (#47) as a backstop.
Teaching video (title and channel verified via YouTube oEmbed)
No verified video specifically on moved/import/removed blocks or ephemeral was found (these features are new). Talk track: following Figure 6-1, demonstrate the output of each of the three blocks in plan, then explain the layers of secret protection per Figure 6-2.
Module 7 · Part B: Multi-Environment, CI/CD & Governance (Questions 26–38)
- Compare workspace vs. directory/account isolation, and design repository and state layouts for multi-team, multi-environment setups.
- Describe a secure Terraform pipeline: PR plan, policy, approval, apply the same plan, OIDC, drift detection.
- Answer governance questions: Policy as Code, HCP Terraform capabilities, version management and major version upgrades, key points for plan review.
Q26. For multiple environments, use workspaces or separate directories? What are the pros and cons of each?Intermediate
30-second answer
CLI workspaces: same configuration, same backend, different state keys; suitable for short-lived copies with identical structure (PR previews, personal sandboxes). Directories (or separate root modules) + separate backend key/account: each environment has its own tfvars, backend, and permissions, can have structural differences, and has a low risk of mistakes; this approach is recommended for production, with shared logic placed in modules.
In-depth answer
| workspace | Directory / root module | |
|---|---|---|
| Isolation | same backend and credentials | can use separate accounts/subscriptions, credentials |
| Visibility | the current workspace is not obvious (#7) | the path is the environment |
| Differences | can only be handled with terraform.workspace conditionals | each has its own tfvars/composition |
| Duplication | None | a little root-module boilerplate |
live/
dev/ { backend.tf main.tf dev.tfvars }
prod/ { backend.tf main.tf prod.tfvars }
modules/
network/ app/ data/
Common follow-up questions
- Is an HCP Terraform workspace the same as a CLI workspace? No; an HCP workspace is an independent workspace (with its own variables, state, permissions, and run history), closer to "one instance of a root module".
Bonus points
Mention Terragrunt or Terraform Stacks for reducing multi-environment boilerplate.
Common wrong answers
"Production and development can just switch between the same workspace."
Q27. In a large organization with multiple teams and environments, how do you organize Terraform repositories and state?Advanced
30-second answer
Split by "layer × environment × owner": the platform layer (accounts/subscriptions, networking, identity), the shared services layer, and the application layer; one state per combination, with permissions and approvals matching the owner. Modules live in separate module repositories and are published with versions; the "live" configuration repository only composes modules. Principles: reduce blast radius, reduce lock contention, and have clear ownership.
In-depth answer
- A monorepo makes it easier to unify tooling and visibility and requires CODEOWNERS and path-based triggers; multiple repos provide stronger isolation but higher version coordination costs.
- Dependencies between layers are one-way: the application reads the network's outputs; the network does not depend on the application.
- Keep the number of resources per state at a scale where plan finishes within a few minutes (#30).
- Landing zone: the accounts/subscriptions themselves are also created by Terraform (or AVM, Control Tower/AFT).
Common follow-up questions
- What's wrong with splitting too finely? Cross-state dependencies increase, and changes must be applied in order in multiple places; use orchestration (Stacks, Terragrunt run-all, pipeline DAG).
Bonus points
Give real numbers, for example: "we have 40 states, each plan < 3 minutes".
Common wrong answers
"One big state is simplest"—see Scenario 6-1.
Q28. Describe a production-grade Terraform CI/CD pipeline.Intermediate
30-second answer
PR: fmt -check, validate, tflint, security scanning,terraform test with plan using a read-only identity, plan policy checks, and a plan summary commented on the PR. Merge to main: plan with the write identity → environment protection approval → apply tfplan apply (what is executed is what was approved). Serialize work on the same state; scheduled drift detection. OIDC throughout, with no long-lived keys.
In-depth answer
name: terraform
on:
pull_request:
push: { branches: [main] }
permissions: { id-token: write, contents: read, pull-requests: write }
concurrency: { group: tf-prod, cancel-in-progress: false }
jobs:
plan:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: hashicorp/setup-terraform@v3
with: { terraform_version: 1.17.2 }
- run: terraform init -input=false -lockfile=readonly
- run: terraform fmt -check -recursive && terraform validate
- run: terraform plan -input=false -out=tfplan
- run: terraform show -json tfplan > tfplan.json && conftest test tfplan.json -p policy/
apply:
if: github.ref == 'refs/heads/main'
needs: plan
environment: prod # approval
runs-on: ubuntu-latest
steps:
- run: echo "re-init, download the plan artifact, then terraform apply -input=false tfplan"
The example is a structural sketch; see Lesson 5 for the full version. Refer to each repository for the major version numbers of actions.
Common follow-up questions
- How is the plan file passed between jobs? As an artifact (short retention, sensitive), or re-plan and re-approve in the apply job.
Bonus points
Mention the trade-offs between dedicated platforms such as Atlantis, HCP Terraform VCS-driven workflows, and Spacelift versus self-built Actions.
Common wrong answers
"Applying directly from a PR," or "applying on main with -auto-approve and no approval."
See Lesson 5.
Q29. Why use OIDC in CI? How is it configured for AWS and Azure respectively?Intermediate
30-second answer
OIDC lets CI exchange a short-lived token for temporary cloud credentials, so there is no need to store long-lived access keys / client secrets in CI; this eliminates leakage and rotation issues and allows precise authorization by repository/branch/environment. AWS: IAM OIDC identity provider + role trust policy (aud and sub conditions); Azure: federated credentials on an app registration or user-assigned managed identity (issuer/subject/audience).
In-depth answer
# create the Azure side with Terraform (sketch)
resource "azurerm_user_assigned_identity" "gh_plan" {
name = "id-gh-tf-plan"
location = "canadacentral"
resource_group_name = "rg-tf-state"
}
resource "azurerm_federated_identity_credential" "pr" {
name = "github-pr"
resource_group_name = "rg-tf-state"
parent_id = azurerm_user_assigned_identity.gh_plan.id
issuer = "https://token.actions.githubusercontent.com"
subject = "repo:org/infra:pull_request"
audience = ["api://AzureADTokenExchange"]
}
On the Terraform side: azurerm use_oidc = true / ARM_USE_OIDC; for aws, configure-aws-credentials writes temporary credentials, or the provider's assume_role_with_web_identity.
Common follow-up questions
- What are the most common failures? sub mismatch (environment format), missing
id-token: write(#42, #43).
Bonus points
plan and apply each map to identities with different permissions; the apply identity only trusts protected environments.
Common wrong answers
"Storing access keys in GitHub Secrets is secure enough."
See Lesson 5 OIDC.
Q30. What is drift? How is it detected and handled?Intermediate
30-second answer
Drift is when real resources no longer match what Terraform last recorded/configured; it usually comes from manual changes, other tools, or automatic cloud platform behavior. Detection: a scheduled terraform plan -refresh-only -detailed-exitcode (or a regular plan) with exit code 2 triggering an alert; HCP Terraform provides health assessments. Handling: unwanted changes → apply to restore; correct hotfixes → write back to code.
In-depth answer
- Prevention: people have read-only access, emergency changes go through break-glass with write-back within a time limit, and cloud audit logs identify who made the change (#46).
- Note
ignore_changeshides drift; perpetual diffs (#22) make drift alerts meaningless, so eliminate them first. - The 1.17
-minimal-refreshoption speeds up routine plans, but drift needs periodic full refreshes to be found.
Common follow-up questions
- Is it risky to apply directly to overwrite drift? It may roll back someone else's emergency fix, so confirm the cause first.
Bonus points
Track the number of drifts as a platform health metric.
Common wrong answers
"Terraform blocks manual changes in real time."
Q31. What is Policy as Code? What is the difference between Sentinel, OPA, and Terraform Policy?Advanced
30-second answer
Express organizational rules in code (ban public storage, require tags, restrict SKUs/regions), run them automatically after plan and before apply, and able to block. Sentinel: HashiCorp's policy language, runs in HCP Terraform/TFE, with advisory/soft/hard levels. OPA/Rego: a general-purpose open-source engine, commonly used with conftest to check plan JSON; HCP Terraform also supports OPA policy sets. Terraform Policy: native Terraform CLI policy, generally available from 1.17 (plan/apply/query -policies), can run locally and in CI.
In-depth answer
package main
import rego.v1
deny contains msg if {
rc := input.resource_changes[_]
rc.type == "azurerm_storage_account"
rc.change.after.allow_nested_items_to_be_public == true
msg := sprintf("%s: public blob access is forbidden", [rc.address])
}
- Note
after_unknown: policies cannot evaluate values that are only known at apply time, so the policy needs a default handling. - Complements Azure Policy / AWS SCP: the former acts before deployment (shift-left), the latter acts as a cloud-side backstop.
Common follow-up questions
- How do you roll out new policies without blocking teams? Start with advisory to observe, then soft, then hard; provide an exception process (#47).
Bonus points
For the specific language and output format of Terraform Policy, refer to developer.hashicorp.com—in interviews, it is enough to state that "it is a native capability that became GA in 1.17"; do not fabricate details.
Common wrong answers
"Policies are just tflint rules"—tflint is static checking and cannot see the actual values after plan.
Q32. What capabilities do HCP Terraform (formerly Terraform Cloud) / Terraform Enterprise provide?Intermediate
30-second answer
Remote runs (consistent execution environment), managed state and locking, VCS-driven PR plans, variable sets and secrets, team permissions, private module/provider Registry, policies (Sentinel/OPA), run tasks (integrated scanning/cost tools), drift detection and continuous validation, Stacks, no-code modules, and audit logs. TFE is the self-hosted version.
In-depth answer
- Execution modes: remote (runs in HCP), local (only stores state), agent (runs on an agent in your network, accessing private resources).
- Configuration: in
terraformthe block, writecloudblock, specifyingorganizationandworkspaces(selected by name or tags); refer to the documentation for syntax. - Pricing tiers and feature availability change often,refer to developer.hashicorp.com and the official website.
Common follow-up questions
- How do you choose between self-built GitHub Actions and HCP? Team size, compliance, cost, and whether out-of-the-box features such as policies, private Registry, and audit are needed.
Bonus points
Mention alternatives: Atlantis (open source), Spacelift, env0, Scalr.
Common wrong answers
"HCP Terraform is just a state storage."
See Lesson 5.
Q33. What problems do Terragrunt and Terraform Stacks solve?Intermediate
30-second answer
Both solve the problem of "the same component deployed repeatedly across multiple environments/regions, with ordering dependencies between multiple states". Terragrunt (Gruntwork, an open-source wrapper): DRY backend/provider generation, passing values through dependency blocks, and run-all executing in dependency order. Terraform Stacks (HCP Terraform): uses .tfcomponent.hcl/.tfdeploy.hcl to declare components and deployments; the platform handles orchestration and deferred changes (refer to the official documentation for file names and status).
In-depth answer
- You can do without them: root modules + modules + pipeline DAG orchestration.
- Adoption costs: additional toolchain, learning curve, one more layer to debug.
Common follow-up questions
- Why do (or don't) you use Terragrunt? Give a reason based on scale.
Bonus points
Point out that Stacks can handle the scenario of "deferring downstream deployment when upstream outputs are unknown."
Common wrong answers
"Terragrunt is a new version of Terraform."
See Lesson 6.
Q34. What is your version management strategy (Core, providers, modules)?Intermediate
30-second answer
Core: the root module required_version = "~> 1.17.0", and the team uses .terraform-version/mise to standardize; CI specifies the version explicitly. Providers: the root module ~> pins the major version + commits the lock file (multi-platform). Modules: Registry uses version, and Git uses tags/SHA. Renovate opens PRs for all of these; CI runs plan to validate; dev goes first.
In-depth answer
- Reusable modules declare only a minimum version, to avoid constraint conflicts (#32).
- Upgrade cadence: minor versions monthly; major versions on a planned schedule (read the Upgrade Guide).
- Once state is written by a newer Core, older Cores cannot read it (#8)—upgrades must be synchronized across everyone.
Common follow-up questions
- Should the lock file be committed? Yes for root modules; reusable module repositories usually do not commit it (it is locked by the caller).
Bonus points
In CI, use init -lockfile=readonly to prevent silent upgrades.
Common wrong answers
"Don't specify versions; always use the latest."
See Lesson 2.
Q35. Which code quality and security tools would you use in a Terraform project?Beginner
30-second answer
terraform fmt (formatting),terraform validate (syntax / types),tflint (provider-specific rules, such as invalid SKUs),Checkov / Trivy (security misconfiguration scanning),terraform-docs (generates module documentation),Infracost (cost estimation),terraform test, plan-based policies (OPA/Terraform Policy), run via pre-commit and CI.
In-depth answer
# .pre-commit-config.yaml (sketch; rev per repository)
repos:
- repo: https://github.com/antonbabenko/pre-commit-terraform
rev: vX.Y.Z
hooks:
- id: terraform_fmt
- id: terraform_validate
- id: terraform_tflint
- id: terraform_docs
Common follow-up questions
- What is the difference between static scanning and plan policies? Static scanning looks at source code and cannot resolve the real values after variables/modules are evaluated; plan policies look at the computed results.
Bonus points
tfsec has been merged into Trivy; upload scan results as SARIF to GitHub code scanning.
Common wrong answers
Only mentioning fmt and validate.
See Lesson 5.
Q36. How do you manage the secrets that Terraform needs in CI/CD?Intermediate
30-second answer
Cloud credentials use OIDC (no secrets); application secrets are stored in Key Vault / Secrets Manager / Vault; Terraform reads them via ephemeral resources and writes them via write-only arguments, or only creates the secret container and lets the application read it at runtime; necessary CI secrets are stored in GitHub Environments secrets with environment restrictions; never commit them to the repository or tfvars.
In-depth answer
- The Vault provider can dynamically generate short-lived cloud credentials (AWS/Azure secrets engine).
- Clarify "who produces, who consumes" for secrets: random passwords generated by Terraform go into state (unless ephemeral); better still, let the cloud service manage them.
- Log hygiene: do not enable TF_LOG, and do not paste JSON into PR comments (#50).
Common follow-up questions
- Are sops-encrypted tfvars OK? Yes (together with the sops provider), but the values still end up in state.
Bonus points
Explain that "secrets can leak in three places: the plan file, state, and logs".
Common wrong answers
"Write the password in tfvars; just make the repository private."
Q37. How do you safely upgrade Terraform Core or a provider's major version (such as azurerm 4 → 5)?Advanced
30-second answer
Read the Upgrade Guide and CHANGELOG → upgrade the constraints and lock file in a branch → fix deprecation warnings first (fix those that can be fixed on the old version first) → plan in dev and make sure only expected changes appear (especially no unexpected replacements) → roll out environment by environment → upgrade Core across everyone and CI together (state version upgrades are irreversible).
In-depth answer
- Reviewing the azurerm 3 → 4 example (for 4 → 5 changes, refer to the 5.0 Upgrade Guide): you must set
subscription_id(#27),resource_provider_registrationsreplaces the old argument (#36); some resources and attributes were removed or renamed. - aws 6.x example: handle removed arguments and behavior changes per the Upgrade Guide (for example, multi-region support, etc.; refer to official documentation).
- Use plan JSON to count delete actions as a gate; for large numbers of updates, confirm item by item whether they only change the state representation or really change cloud resources.
- Keep a rollback plan: take a state snapshot before upgrading; provider upgrades can be rolled back before apply, but once Core has written state, it cannot be rolled back.
Common follow-up questions
- How do you coordinate across many repositories? Renovate batch PRs + shared pipeline templates + an upgrade dashboard.
Bonus points
First upgrade to the last minor version of the previous major version, handle all deprecation warnings, then cross the major version.
Common wrong answers
"Just change the version number and apply directly."
Q38. When reviewing a Terraform PR, what do you focus on in the plan?Intermediate
30-second answer
First look at the destroy count in the summary and -/+ replacements (especially for stateful resources); then check whether the changes match the PR description and whether there are unexpected resources; then look at security-related attributes (public access, firewall rules, IAM/RBAC), cost (SKU/quantity),(known after apply) whether key values are masked, and drift hints ("Objects have changed outside").
In-depth answer
terraform show -json tfplan | jq -r '.resource_changes[] | select(.change.actions != ["no-op"]) | "\(.change.actions|join(","))\t\(.address)"' | sort
- Code level: naming, tags, module version pinning, whether a provider was introduced, lock file changes, and whether moved blocks are complete.
- Process: whether the plan comes from the latest main code, and whether apply uses the same plan (#44).
Common follow-up questions
- What if the plan is too long? Split the PR; use tools to generate a summary (grouped by action); policies automatically flag high-risk changes.
Bonus points
Write high-risk patterns as policies rather than relying on human eyes.
Common wrong answers
"Only reviewing the code diff, not the plan"—a small code change can cause large-scale replacements (#16, #17).
See Lesson 5.
Scenario 7-1: Designing a self-service Terraform platform for 30 application teams
A platform team of 4 people; 30 application teams each need to deploy Container Apps + a database on Azure. How do you balance "self-service" and "governance"?
Key points of the reference answer
- Golden-path modules (application, database, network access) + private Registry; teams only write a few dozen lines of composition code.
- Repository template: pre-configured backend, OIDC, pipeline, pre-commit; one subscription or resource group per team + separate state.
- Governance: policies (tags, SKUs, regions, public access), Azure Policy as a backstop, budget alerts, drift detection.
- Support: documentation, examples, office hours; measure module adoption rate and average delivery time.
Scenario 7-2: The apply after merge doesn't match the plan in the PR, causing an accidental deletion
The PR plan shows 2 resources modified, but after merge the pipeline's apply -auto-approve deleted 1 load balancer. Analyze the possible causes and propose a pipeline redesign.
Key points of the reference answer
- Causes: apply recalculated the plan; in the meantime another PR merged and changed state; or module versions floated; or the PR and main used different variables.
- Redesign: plan -out on main → approval → apply tfplan; concurrency serialized; pin module versions; require extra approval when a delete appears in the plan (policy).
- Recovery: rebuild the load balancer from code/state history, or import it.
Scenario 7-3: The organization requires all resources to carry a cost-center tag
How would you implement this in Terraform, enforce it, and handle existing resources?
Key points of the reference answer
- Implementation: aws (default_tags)
default_tags; for azurerm, standardize tags in the moduletags = merge(local.tags, var.tags); variable validation requires the cost-center format. - Enforcement: plan policy (deny when the tag is missing) + cloud policies (Azure Policy deny/modify, AWS Tag Policies/SCP).
- Existing resources: use the audit report from cloud policy → batch PRs to add tags; note that some resources do not support tags.
Teaching video (title and channel verified via YouTube oEmbed)
No verified video specifically on Terraform governance/policy was found. Talk track: walk through the pipeline per Figure 7-1, and for each node explain "which issue number appears if it is missing".
Module 8 · Part B: Security, Cloud Practices & Scenario Design (Questions 39–50)
- Answer security design questions: least privilege for Terraform identities and hardening the state backend.
- Use Terraform to describe the reference architecture for myapp on Azure (VNet + Container Apps) and AWS (VPC + ECS Fargate).
- Answer open-ended scenario questions using the structure "clarify requirements → solution → trade-offs → risks and validation".
Q39. How do you achieve least privilege for the identities Terraform uses?Advanced
30-second answer
Split identities by environment and layer; the plan identity is read-only (plus state read/write lock permission), and the apply identity has write permission and can only be obtained by protected branches/environments (OIDC conditions); scope it to resource groups/accounts; control role-assignment permissions separately (Azure's constrained RBAC administration, AWS permission boundaries); people default to read-only, and break-glass access is audited.
In-depth answer
- Azure: the application-layer identity holds Contributor on its own resource group; when role assignments are needed, use "condition-based RBAC administrator" to restrict which roles can be assigned.
- AWS: deployment role +
permissions_boundary, to prevent Terraform from creating roles with greater permissions; SCP as a backstop. - Start with minimal permissions and add permissions as errors occur (#28); periodically tighten using access analysis (IAM Access Analyzer).
resource "aws_iam_role" "app_task" {
name = "myapp-task"
assume_role_policy = data.aws_iam_policy_document.ecs_assume.json
permissions_boundary = "arn:aws:iam::111122223333:policy/app-boundary"
}
Common follow-up questions
- Why is the Terraform identity especially sensitive? It usually can create/modify IAM, which is effectively a potential privilege-escalation path.
Bonus points
plan can also read secrets through data sources, so the plan identity's read access to secrets must also be controlled.
Common wrong answers
"Giving CI Owner/AdministratorAccess is the easiest."
Q40. How do you harden the state backend?Intermediate
30-second answer
Encryption (S3 SSE-KMS + bucket keys / storage account encryption, with customer-managed keys possible), versioning and soft delete, locking (use_lockfile / blob lease), blocking public access and restricting networks, least privilege (by key prefix), disabling shared keys (Azure), access logs and alerts, deletion protection (resource locks / object lock), and managing the state backend itself with a separate bootstrap configuration.
In-depth answer
resource "aws_s3_bucket" "state" { bucket = "org-tfstate-prod" }
resource "aws_s3_bucket_versioning" "state" {
bucket = aws_s3_bucket.state.id
versioning_configuration { status = "Enabled" }
}
resource "aws_s3_bucket_public_access_block" "state" {
bucket = aws_s3_bucket.state.id
block_public_acls = true
block_public_policy = true
ignore_public_acls = true
restrict_public_buckets = true
}
Common follow-up questions
- Where does the state bucket's own state go? The bootstrap configuration is created with local state and then migrated in, or created by a separate process / landing zone.
Bonus points
Cross-region replication for disaster recovery; lifecycle rules clean up old versions while keeping enough history.
Common wrong answers
Only saying "turn on encryption".
Q41. How would you design deploying myapp (Flask + Redis) on Azure with Terraform?Intermediate
30-second answer
Resource group + VNet (dedicated subnet for the Container Apps environment, private endpoint subnet) → Log Analytics → ACR (admin account disabled) → user-assigned managed identity (AcrPull,principal_type see #31) → Container Apps environment (VNet integration) → Container App (external ingress on 8000, health probe /healthz, minimum replicas 2) → Azure Cache for Redis (private endpoint; keys stored in Key Vault). Split state by layer: network/shared, data, application.
In-depth answer
resource "azurerm_container_app" "web" {
name = "ca-myapp"
container_app_environment_id = azurerm_container_app_environment.env.id
resource_group_name = azurerm_resource_group.rg.name
revision_mode = "Single"
identity {
type = "UserAssigned"
identity_ids = [azurerm_user_assigned_identity.app.id]
}
registry {
server = azurerm_container_registry.acr.login_server
identity = azurerm_user_assigned_identity.app.id
}
template {
min_replicas = 2
container {
name = "myapp"
image = "${azurerm_container_registry.acr.login_server}/myapp:${var.image_tag}"
cpu = 0.5
memory = "1Gi"
}
}
ingress {
external_enabled = true
target_port = 8000
traffic_weight {
latest_revision = true
percentage = 100
}
}
}
Refer to the azurerm 4.x documentation for parameters; see Lesson 3 for complete code.
Common follow-up questions
- Who updates the image tag? The application pipeline updates the variable and then runs Terraform apply, or Terraform uses
ignore_changesto hand the image off to an application deployment tool—pick one to avoid overwriting each other.
Bonus points
Mention RP registration (#36), region choice canadacentral, and cost (Consumption plan, minimum replicas).
Common wrong answers
Putting the Redis key in plaintext Terraform variables.
Q42. How would you design deploying the same myapp on AWS with Terraform?Intermediate
30-second answer
VPC (ca-central-1, 2–3 AZs, public/private subnets, NAT or VPC endpoints) → ECR → ECS cluster (Fargate) → task definition (task execution role pulls images/writes logs; task role for the application) → ALB (target group health check /healthz) → ECS service (private subnets, desired count 2, deployment circuit breaker with rollback) → ElastiCache Redis (private subnets; security group allows only the service SG) → CloudWatch Logs.
In-depth answer
resource "aws_ecs_service" "web" {
name = "myapp"
cluster = aws_ecs_cluster.main.id
task_definition = aws_ecs_task_definition.web.arn
desired_count = 2
launch_type = "FARGATE"
network_configuration {
subnets = module.vpc.private_subnets
security_groups = [aws_security_group.web.id]
}
load_balancer {
target_group_arn = aws_lb_target_group.web.arn
container_name = "myapp"
container_port = 8000
}
deployment_circuit_breaker {
enable = true
rollback = true
}
depends_on = [aws_lb_listener.http] # the target group must be attached to the listener first
}
Common follow-up questions
- NAT gateways are too expensive? Use VPC endpoints (ECR, S3, CloudWatch Logs) to reduce NAT traffic.
- Why depends_on the listener? Hidden dependency (#24).
Bonus points
Compare with the Azure approach: managed identity vs IAM task role; Container Apps built-in ingress vs ALB.
Common wrong answers
Putting tasks in public subnets with public IPs just to pull images.
Q43. How do you bring a large number of manually created existing resources under Terraform management?Advanced
30-second answer
Inventory → plan the target code structure by layer → use import blocks (batch with for_each) + plan -generate-config-out generate a draft → organize into modularized code → repeat plan until "N to import, 0 to change/destroy" → apply → revoke manual permissions and enable drift detection. From 1.14+, you can use terraform query (*.tfquery.hcl in its list block) to discover existing resources and generate import configuration (refer to the documentation for provider support scope).
In-depth answer
locals {
rgs = { app = "rg-app-prod", data = "rg-data-prod" }
}
import {
for_each = local.rgs
to = azurerm_resource_group.rg[each.key]
id = "/subscriptions/${var.subscription_id}/resourceGroups/${each.value}"
}
resource "azurerm_resource_group" "rg" {
for_each = local.rgs
name = each.value
location = "canadacentral"
}
- Generated configuration contains many default values; clean it up into maintainable code.
- Start with non-production and low-risk layers; when the first plan after import shows updates, judge each one individually.
- Tools: aztfexport (Azure's official export tool), Terraformer (community; verify its maintenance status yourself).
Common follow-up questions
- What if the plan shows updates after import? Prefer changing the code to match the current state; only let Terraform modify once it's confirmed harmless.
Bonus points
Emphasize that "bringing under management" is not only technical; it also requires freezing manual change windows and communication.
Common wrong answers
"Delete and recreate"—production resources (data, IPs, DNS) usually cannot be recreated.
See Lesson 2 import,Lesson 7.
Q44. How do you implement zero-downtime changes with Terraform?Advanced
30-second answer
Identify attributes that trigger replacement ("forces replacement" in plan); for resources that must be replaced, use create_before_destroy + names that can coexist (name_prefix/ random suffix); switch at the load balancer layer (blue-green: two sets of resources + weight/DNS switch; or rely on the platform's rolling updates: ASG instance refresh, ECS rolling deployment, Container Apps revision traffic allocation); for databases, use the platform's in-place upgrade or replication switchover.
In-depth answer
resource "aws_launch_template" "web" {
name_prefix = "web-"
image_id = var.ami_id
instance_type = "t3.small"
lifecycle { create_before_destroy = true }
}
resource "aws_autoscaling_group" "web" {
# ...
launch_template {
id = aws_launch_template.web.id
version = aws_launch_template.web.latest_version
}
instance_refresh {
strategy = "Rolling"
preferences { min_healthy_percentage = 90 }
}
}
Common follow-up questions
- What are the pitfalls of create_before_destroy? Unique name conflicts; it propagates to dependents; quotas must be large enough for two sets of resources.
Bonus points
Terraform manages the "shape of the infrastructure"; rolling/canary deployments are executed by the runtime platform; the division of labor between the two is clear.
Common wrong answers
"Terraform apply is zero-downtime by itself."
Q45. If state is lost or corrupted, how do you recover?Advanced
30-second answer
First freeze all pipelines. With version control: restore the most recent correct version (#2), then check with plan, and use import to add back resources created after the restore point. Without backups: rebuild an empty state, bring resources under management one by one with import blocks (or terraform query discovery), until plan shows no add/destroy. Finally, do a postmortem on why it was lost (permissions, no version control, manual overwrite).
In-depth answer
aws s3api list-object-versions --bucket org-tfstate-prod --prefix app/terraform.tfstate --query 'Versions[0:5].[VersionId,LastModified,Size]' --output table aws s3api get-object --bucket org-tfstate-prod --key app/terraform.tfstate --version-id <VID> restored.tfstate terraform state push restored.tfstate # if the lineage/serial check fails, understand the cause first; do not casually use -force terraform plan
- No one may apply during recovery (otherwise duplicate resources may be created).
- Verification:
state listCounts and key resource IDs match the cloud; plan shows no surprises.
Common follow-up questions
- How do you prevent this? Version control + soft delete + deletion protection + only the Terraform identity can write + regular recovery drills.
Bonus points
Have done recovery drills and can state an RTO.
Common wrong answers
"Just apply and let Terraform recreate everything"—this creates duplicate resources or name conflicts (#29).
Q46. How do you manage multi-account (AWS) / multi-subscription (Azure) environments?Advanced
30-second answer
Accounts/subscriptions are the strongest isolation boundary: divide by environment and workload. On the Terraform side: each root module corresponds to one account/subscription; the CI identity enters the "deployment account" via OIDC, then assume_role switches into the target account (AWS), or grants federated identity permissions for each subscription (Azure); cross-account resources (VPC peering, DNS delegation, central logging) use provider aliases. The accounts themselves are created by landing zone processes (Control Tower/AFT, Azure Landing Zones/AVM).
In-depth answer
provider "aws" {
region = "ca-central-1"
assume_role {
role_arn = "arn:aws:iam::${var.target_account_id}:role/terraform-deploy"
session_name = "gh-${var.env}"
}
}
provider "aws" {
alias = "network"
region = "ca-central-1"
assume_role { role_arn = "arn:aws:iam::999988887777:role/terraform-network" }
}
Common follow-up questions
- Which account should the state live in? Centralize it in a "management / tooling" account and grant access by key prefix; or give each account its own backend (stronger isolation).
Bonus points
Mention AWS Organizations SCPs and Azure management group policies as guardrails.
Common wrong answers
"Put all environments in one account and distinguish them with tags."
Q47. How do you control cloud costs with Terraform?Beginner
30-second answer
Show cost differences in PRs with Infracost; enforce tags (cost-center, owner, env) to support allocation; policies restrict expensive SKUs/regions; modules provide per-environment sizing defaults (small sizes for dev, auto-shutdown); budgets and alerts are also created by Terraform (azurerm_consumption_budget_*,aws_budgets_budget); temporary environments (PR previews) set a TTL for automatic destruction.
In-depth answer
infracost breakdown --path . --format table infracost diff --path . --compare-to infracost-base.json
Common follow-up questions
- How accurate is Infracost? Estimates are based on resource specs; usage-related items (traffic, request counts) need a usage file to supplement.
Bonus points
Give an example: how much is saved by scaling dev to 0 replicas overnight.
Common wrong answers
"Cost is finance's business and unrelated to IaC."
See Lesson 5.
Q48. A plan for one state takes 20 minutes; how would you optimize it?Advanced
30-second answer
First measure (TF_LOG=DEBUG to see where the time goes: refresh API calls, throttling retries, data sources, provider initialization). The fundamental fix is splitting the state; short-term you can adjust -parallelism (when throttled, lower it instead), use 1.17's -minimal-refresh or -refresh=false (combined with periodic full refreshes to detect drift), reduce expensive data sources, and enable the plugin cache to reduce init time.
In-depth answer
- A large number of
for_eachsmall resources created through expansion (such as thousands of DNS records/rules) can be consolidated or handed to a dedicated resource type. - Avoid a module-level depends_on that defers data source reads.
- CI: plugin cache directory, network mirror (#41), and run each state only when its relevant paths change.
Common follow-up questions
- What are the risks of -refresh=false? It computes based on stale state, which may overwrite drift or plan incorrect changes.
Bonus points
Give data before and after splitting (resource count, plan duration, throttling count).
Common wrong answers
"Set parallelism to 100"—this makes throttling more likely (#30).
Q49. Design question: the "golden path" Terraform solution that the platform team provides to application teams.Advanced
30-second answer
Clarify: number of teams, cloud, compliance requirements, degree of self-service. Solution: versioned high-level modules ("a web application" = compute + identity + logging + alerting + network access), repository templates (backend/OIDC/pipeline/pre-commit preconfigured), policies and cloud guardrails, a private Registry, documentation and examples, and metrics. Trade-offs: too high an abstraction lacks flexibility, too low loses value; provide an "escape hatch" (allow extra settings to be passed in).
In-depth answer
module "web" {
source = "app.terraform.io/org/web-app/azurerm" # private Registry (example address)
version = "~> 3.2"
name = "myapp"
env = "prod"
image = "myacr.azurecr.io/myapp:1.4.0"
replicas = { min = 2, max = 10 }
redis = true
alerts_to = "team-myapp@example.com"
}
- Inside the module: secure defaults, naming/tagging conventions, diagnostic settings, managed identity, private endpoints.
- Lifecycle: semantic versioning, CHANGELOG, moved blocks, deprecation notices, Renovate.
- Validation:
terraform test, sandbox integration tests, and policy tests.
Common follow-up questions
- What if a team needs a feature the module doesn't support? A contribution model (inner source PRs) + platform review.
Bonus points
Prove value with metrics: time to launch new services, policy violation counts, module adoption rate.
Common wrong answers
Giving code directly without first clarifying requirements and constraints.
Q50. Describe a Terraform production incident you have encountered (or can imagine), and how you would prevent it from happening again.Intermediate
30-second answer
Use the STAR structure: situation (scale, team) → task (your role) → action (diagnosis, stopping the bleeding, recovery) → result (impact, recovery time) + improvements (automated safeguards, rather than "be more careful next time"). You could choose: count address drift causing replacement (#17), force-unlock concurrent writes caused by a leftover lock (#1, #6), or an accidental deletion from a mismatch between the PR plan and apply (#44).
In-depth answer (sample answer skeleton)
- S: 12 applications share one state; CI runs apply -auto-approve after merge.
- T: on-call, responsible for recovery and postmortem.
- A: one apply replaced the load balancer; froze the pipeline; located the cause from state history and cloud audit logs; restored via code rollback + apply; updated DNS.
- R: 18-minute outage; no data loss.
- Improvements: apply uses an approved plan file; an extra approval is required when the plan contains a delete (policy); split the state; set prevent_destroy on critical resources.
Common follow-up questions
- If you did it again, what would you do?How would you get the team to accept the improvements?
Bonus points
Quantify the impact; demonstrate blameless postmortems and systemic improvement.
Common wrong answers
"I've never had an incident," or placing all the blame on others.
See the 50 questions in Part A of this lesson; see Lesson 7.
Scenario 8-1: Expanding from a single Azure region to dual-region high availability
myapp currently runs in the single region canadacentral. The business requires an RTO of 1 hour and an RPO of 15 minutes. How would you implement a second region (canadaeast) with Terraform?
Key points of the reference answer
- Code: encapsulate region-specific resources in a module, and instantiate it for each region using providers/variables; one state per region (a regional failure does not affect applies in the other region).
- Global layer: Front Door / Traffic Manager, DNS, in a separate state.
- Data: Redis geo-replication or accept cache loss; use a cross-region replica for the database to meet the RPO.
- Validation: regular failover drills; check blocks verify the health of both regions.
- Watch quotas (#37), RP registration (#36), and ACR geo-replication.
Scenario 8-2: Security audit finds CI using long-lived Owner keys
You need to remediate within 2 weeks without interrupting delivery. Provide a plan.
Key points of the reference answer
- Days 1–2: inventory all pipelines that use the key; create OIDC federated identities (plan read-only / apply write, per environment).
- Days 3–7: switch repository by repository to OIDC (#42, #43), validating with both paths running in parallel.
- Days 8–10: tighten permissions to the resource group level; control role-assignment permissions separately.
- Days 11–14: revoke the old key; confirm no one uses it via audit logs; policy prohibits creating new client secrets.
- Also check whether the key has leaked into state or logs (#5, #50).
Scenario 8-3: An AWS account has 300 manually created security groups
Many of the rules are duplicated and overly broad (0.0.0.0/0). How do you bring them under management and consolidate them?
Key points of the reference answer
- Discovery: describe-security-groups + usage (ENI associations) to distinguish in-use from idle.
- Management: import blocks (for_each) + generated configuration; rules use standalone rule resources (avoid #13, #22).
- Consolidation: import first to keep the status quo (0 change), then tighten rules in batched PRs, and use VPC flow logs to confirm no traffic before deleting.
- Preventing regression: policy forbids 0.0.0.0/0 inbound (with an exception list), and drift detection.
Teaching video (title and channel verified via YouTube oEmbed)
No verified video specifically on Terraform security design / scenario interviews was found. Talk track: answer scenario question 8-1 using the four-step structure in Figure 8-2, within a 5-minute time limit.
Troubleshooting cheat sheet + interview flashcards
A · 50 production issue quick reference
Filter by typing a keyword (for example lock,for_each,403,OIDC). Click a number to jump to the detailed explanation in the matching module.
B · 50 interview question flashcards
Read the question and try to recall the answer first, then expand to compare with the one-line key point; for details, return to the "Interview question details" in the matching module.
General command cards
State
terraform state list
terraform state show ADDR
terraform state pull > backup-$(date +%s).tfstate
terraform state pull | jq '{serial,lineage,terraform_version}'
terraform force-unlock LOCK_ID
terraform init -migrate-state | -reconfigurePlan / Apply
terraform plan -out=tfplan -detailed-exitcode
terraform show -json tfplan | jq '.resource_changes[]|{address,a:.change.actions}'
terraform plan -refresh-only
terraform apply -replace=ADDR
terraform graph -type=plan | dot -Tsvg > g.svg
terraform consoleProvider / authentication
terraform version; terraform providers terraform providers lock -platform=linux_amd64 -platform=darwin_arm64 -platform=windows_amd64 aws sts get-caller-identity az account show -o table env | grep -E '^(AWS|ARM|TF)_' | sed 's/=.*/=***/'
Debugging / CI
TF_LOG=DEBUG TF_LOG_PATH=tf.log terraform plan # delete the log when done TF_LOG_PROVIDER=DEBUG terraform apply terraform init -input=false -lockfile=readonly terraform fmt -check -recursive && terraform validate terraform test
Comprehensive drills + mock interview
I. Comprehensive failure drills
Each scenario combines several issues from Part A. First write down your first diagnostic command and judgment, then expand the answer.
Scenario 1: All prod pipelines are stuck on "Acquiring state lock" on Monday morning; an apply was manually cancelled on Friday evening
Error: Error acquiring the state lock Lock Info: ID: 7d2e... Operation: OperationTypeApply Who: runner@gh-4411 Created: 2026-11-13 22:47:10 UTC $ terraform plan (after unlocking) # azurerm_container_app.web is tainted, so must be replaced
Answer: The cancelled job left a lock behind (#1), and resources that failed midway were marked tainted (#19). Steps: confirm the runner no longer exists → state pull to back up → force-unlock → plan, and confirm the tainted resources' cloud state; if they are fine, then untaint; otherwise let Terraform replace them. Improvements: cancel-in-progress: false, and make the job timeout greater than the resource timeouts (#20).
Scenario 2: A Mac colleague upgraded the provider, and all Linux CI inits fail
Error: Failed to install provider ... doesn't match any of the checksums previously recorded in the dependency lock file (this might be because the available checksums are for packages targeting different platforms) $ grep -c 'h1:' .terraform.lock.hcl 1
Answer: The lock file only has darwin_arm64 h1 hashes, so CI cannot verify installs from the plugin cache/mirror (#33). Fix: terraform providers lock -platform=… fill in the platforms and commit; the pipeline should use -lockfile=readonly (#45).
Scenario 3: A refactoring PR moved VMs into a module and reordered a list; plan shows that 6 VMs will be deleted
# azurerm_linux_virtual_machine.vm[0] will be destroyed # module.compute.azurerm_linux_virtual_machine.this["web1"] will be created ... Plan: 6 to add, 0 to change, 6 to destroy.
Answer: The address changes were not declared with moved (#49), and the count index semantics (#17). Write a moved block for each VM (vm[0] → module.compute…this["web1"]); the plan must show 0 add / 0 destroy; add prevent_destroy to the VMs (#18); a CI gate blocks deletes.
Scenario 4: First deployment of myapp in a new subscription; apply fails twice with different errors
"1st run: MissingSubscriptionRegistration: ... namespace 'Microsoft.App'" 2nd run: Code="PrincipalNotFound" Message="Principal 9f8e... does not exist in the directory ..." 3rd run (manual retry): succeeded
Answer: Resource provider not registered (#36) + managed identity replication delay (#31). Fix: pre-register the RPs in the landing zone or configure resource_provider_registrations; add principal_type = "ServicePrincipal". Making apply re-runnable (#19) is a good design, but it should not rely on manual retries.
Scenario 5: In GitHub Actions, the PR's plan runs, but after adding environment: prod to the apply job, login to Azure fails
AADSTS700213: No matching federated identity record found for presented assertion subject 'repo:org/infra:environment:prod' $ az ad app federated-credential list --id ... --query '[].subject' ["repo:org/infra:pull_request", "repo:org/infra:ref:refs/heads/main"]
Answer: Declaring an environment changes the OIDC sub to environment format (#43). Add a subject repo:org/infra:environment:prod federated credential for the write identity; the backend also needs use_oidc = true (#10).
Scenario 6: The drift job alerts every day, but nobody has changed anything
$ terraform plan -refresh-only -detailed-exitcode; echo $?
2
~ policy = jsonencode( ... "s3:PutObject", "s3:GetObject" order changed ...)
~ tags_all { + "CreatedBy" = "AutoTagger" }
Answer: Perpetual diff (#22: JSON order; use aws_iam_policy_document) + an external auto-tagging tool (#46-type drift: the provider's ignore_tags or ignore_changes, with a comment). Eliminate the noise first; only then do drift alerts make sense.
Scenario 7: CI suddenly fails, although the same code ran last week
Error: Unsupported argument on network.tf line 9, in module "vpc": 9: enable_classiclink = false --- Another repository: Error: Unsupported Terraform Core version This configuration does not support Terraform version 1.16.7.
Answer:① A module was not version-pinned and picked up a new major version (#39): add version = "~> X.Y", and upgrade through a PR. ② The runner's Terraform version is lower than required_version (#48): explicitly specify 1.17.2 in setup-terraform.
Scenario 8: The security team saw a database password in a PR comment
workflow: env: TF_LOG: DEBUG PR comment bot: output of terraform show -json tfplan | jq ... "administrator_password": "P@ssw0rd!"
Answer: The DEBUG log and the plan JSON both contain plaintext (#50), and the password itself is also in state (#5). Rotate it immediately, delete the logs and comments; remove TF_LOG; PR comments should only post terraform show human-readable output; switch to write-only arguments + an ephemeral password or a managed password.
II. Full mock interview (10 random questions out of 50)
Each question has a 2-minute countdown: answer aloud first (you may write key points in the text box), then expand the reference answer and self-rate as "answered / partial / didn't know". At the end, this round's score is shown, along with the cumulative mastery rate by module. Self-rating results are saved in this browser.
III. Open-ended self-test (6 questions)
- Draw the read/write order of state during one apply, and mark at which step #1, #2, #6, and #8 occur.
- Using PlanResourceChange and unknown values, explain why for_each keys cannot come from resource attributes.
- What risks does "the lock file does not lock module versions" create? How would you guard against them?
- Give a pipeline from PR to prod apply, and explain which issue numbers each step prevents.
- What does each of sensitive, ephemeral, and write-only solve, and what does each not solve?
- The recovery steps after state is lost, and why you must not apply directly.
IV. Final quiz (12 questions)
Sources & version notes
Official documentation sources
| Topic | Conclusions used in this lesson | Source (accessed 2026-11-15) |
|---|---|---|
| Terraform versions and new features | 1.17.2 (2026-11-11); 1.17 Terraform Policy GA, -minimal-refresh; 1.14 list resources / terraform query (*.tfquery.hcl), action blocks; 1.18 in development (deferred actions experiment) | CHANGELOG (main) · v1.14 CHANGELOG |
| State locking | Locking mechanism, force-unlock, -lock-timeout | State locking · force-unlock |
| S3 backend | use_lockfile native lock, DynamoDB lock deprecation, required permissions, S3-compatible endpoint parameters | Backend: s3 |
| azurerm backend | use_azuread_auth, use_oidc, blob lease lock | Backend: azurerm |
| Sensitive data | sensitive does not prevent storage; ephemeral (1.10); write-only (1.11) | Sensitive data · Ephemeral resources · Write-only arguments |
| Refactoring and import | moved (1.1), import block (1.5), removed (1.7), -generate-config-out | moved · import · Removing resources |
| Meta-arguments | count, for_each, lifecycle, depends_on, timeouts | for_each · lifecycle |
| Dependency lock file | h1/zh hashes, providers lock -platform, -lockfile=readonly | Dependency lock file · providers lock |
| CLI configuration | plugin_cache_dir, provider_installation mirror | CLI configuration |
| Validation and testing | validation, pre/postcondition, check blocks, terraform test, mock_provider | Validate configuration · Tests |
| AWS provider | Credential chain, assume_role, default_tags | hashicorp/aws |
| azurerm provider (from 4.0; currently 5.x / 5.14.0) | subscription_id required; resource_provider_registrations | 4.0 Upgrade Guide |
| GitHub OIDC | sub format (ref / pull_request / environment), id-token permission | GitHub Docs |
| Entra workload identity federation | federated credential issuer/subject/audience | Microsoft Learn |
| OpenTofu | 1.13.x (latest 1.13.9); client-side state encryption | OpenTofu Docs |
Video verification notes
All videos were verified on 2026-11-15 via the YouTube oEmbed endpoint (https://www.youtube.com/oembed?url=…&format=json) to verify titles and channels; oEmbed does not return duration or publish date, so these are not labeled. Verified: TechWorld with Nana “Terraform explained in 15 mins | Terraform Tutorial for Beginners” (l5k1ai_GBDE), “GitHub Actions Tutorial - Basic Concepts and CI/CD Pipeline with Docker” (R8_veQiYBjI); Fireship “Terraform in 100 Seconds” (tomUWcQ0P3k); freeCodeCamp.org “Terraform Course - Automate your AWS cloud infrastructure” (SLB_c_ayRMo), “Learn Terraform with Azure by Building a Dev Environment – Full Course for Beginners” (V53AHWun17s); DevOps Directive “Complete Terraform Course - From BEGINNER to PRO! (Learn Infrastructure as Code)” (7xngnjfIlK4); HashiCorp, an IBM Company “Introduction to HashiCorp Terraform with Armon Dadgar” (h970ZBgKINg); KodeKloud “Terraform Tutorial for Beginners + Labs: Complete Step by Step Guide!” (YcJ9IeukJL8); Travis Media “Why You NEED To Learn Terraform | Practical Tutorial” (nvNqfgojocs). Not found No verified video specifically on Terraform production troubleshooting or interview questions was found; the related pages provide storyboards / talk tracks instead.
Voice notes
The "Voice" tab uses the browser's built-in Web Speech API and uploads no data. A Chinese (zh-CN) voice pack needs to be installed on the system; without one, you can read the talk track directly.
Known limitations
- Raw error text follows the common wording of Terraform 1.x and aws 6.x / azurerm 5.x. Provider errors include information returned by the cloud API and change with provider, SDK, and cloud service versions; entries note "wording varies by version" where applicable.
- All "sample outputs" are illustrative; IDs, ARNs, timestamps, and version numbers differ from your environment. The reproduction labs are written from the official documentation,but have not actually been run in this environment.
- Details handled conservatively (refer to the official documentation): the policy language and output format of Terraform Policy, the exact behavior of
-minimal-refresh, Stacks file names and status, HCP Terraform pricing tiers, azurermresource_provider_registrationsdefault sets, availability of write-only arguments per resource, Entra flexible federated identity credentials, and MinIO support for S3 conditional writes. - Mock interview self-rating records are saved only in the current browser's localStorage and will be lost if site data is cleared.