HashiCorp Certified: Terraform Associate (003 / 004) — HCL, State Management, Modules & Governance

High-yield Terraform Associate (003/004) flashcards covering the 57-question exam blueprint, core CLI workflow, provider lock files, remote state backends & locking, state CLI vs. moved/import/removed blocks, count vs. for_each, dynamic blocks, lifecycle meta-arguments, variable precedence, Vault/sensitive data, Module Registry, and HCP Terraform / Sentinel.

Category
Multi-Cloud & DevOps Architecture — Microsoft Azure (AZ-104 & AZ-305), Google Cloud (PCA & PDE), Kubernetes (CKA / CKAD) & HashiCorp Terraform Associate
Level
advanced
Languages
en → en
Cards
32
Markdown
HashiCorp Certified: Terraform Associate (003 / 004) — HCL, State Management, Modules & Governance (.md)

Flashcards (32)

#Front (Term / Question)Back (Definition / Answer)ExampleMultiple-Choice Options
1In HCP Terraform, how do Projects, Variable Sets, and Run Triggers organize multi-workspace infrastructure at scale?Projects group Workspaces for RBAC; Variable Sets share variables/credentials across Projects or Workspaces; Run Triggers queue downstream Workspace plans when upstream Workspaces apply.Instead of duplicating AWS OIDC role variables across 40 microservices workspaces, an administrator attaches one `AWS-Prod-Auth` Variable Set to the `Production` Project and links `network-prod` to downstream workspaces via Run Triggers.
  • Projects = RBAC and organizational grouping of Workspaces; Variable Sets = reusable central variables across Workspaces/Projects; Run Triggers = cross-workspace dependency chaining.
  • No-Code Provisioning in HCP Terraform also allows self-service deployment of approved Private Registry modules without writing HCL.
  • Projects group Workspaces for RBAC; Variable Sets share variables/credentials across Projects or Workspaces; Run Triggers queue downstream Workspace plans when upstream Workspaces apply.
2Compare `terraform refresh` (now deprecated), `terraform apply -refresh-only`, and `terraform plan -refresh=false`.`terraform apply -refresh-only` previews out-of-band cloud drift and prompts before updating `terraform.tfstate` (replacing unsafe `terraform refresh`), while `-refresh=false` skips API refresh queries.If someone manually modifies a tag in the Azure Portal, running `terraform plan -refresh-only` displays the exact state drift without modifying any cloud infrastructure.
  • Legacy `terraform refresh` overwrote state immediately without a confirmation prompt; `terraform plan/apply -refresh-only` previews state updates safely.
  • `terraform apply -refresh-only` previews out-of-band cloud drift and prompts before updating `terraform.tfstate` (replacing unsafe `terraform refresh`), while `-refresh=false` skips API refresh queries.
  • Wait: `terraform apply -refresh-only` updates the Terraform state file to match real cloud resources—it does NOT revert the cloud resources!
3Does setting `sensitive = true` on a Terraform `variable` or `output` encrypt or hide the secret value inside `terraform.tfstate`?NO! Setting `sensitive = true` only redacts the value from CLI terminal output and logs; the plaintext value still persists in `terraform.tfstate`!Note that in Terraform 1.10+ (Exam 004), `ephemeral = true` variables/resources (`ephemeral "vault_kv_secret_v2"`) and provider Write-Only arguments (`password_wo`) DO omit secrets from being stored in `terraform.tfstate` or plan files.
  • `sensitive = true` masks CLI/UI console output only—`terraform.tfstate` still contains `sensitive` variables in plaintext, which is why state files must always be encrypted at rest in a remote backend.
  • In Terraform 1.10+ (004), `ephemeral` blocks and write-only (`_wo`) attributes never persist to state.
  • NO! Setting `sensitive = true` only redacts the value from CLI terminal output and logs; the plaintext value still persists in `terraform.tfstate`!
4Compare the `count` and `for_each` meta-arguments in Terraform: what collection types does each accept, and why is `for_each` generally safer when removing items from the middle of a list?`count` takes an integer and indexes by position (`[0]`); `for_each` takes a `map` or `set(string)` and indexes by key (`["prod"]`), preventing cascading re-creations.If 3 subnets are created with `count = length(var.subnets)` and `var.subnets[0]` is removed, indices `[1]` and `[2]` shift down, forcing Terraform to recreate subsequent subnets; `for_each = toset(var.subnets)` deletes only the removed key.
  • `count` uses `count.index` (`resource.name[0]`); `for_each` uses `each.key` and `each.value` (`resource.name["key"]`). Note: `count` and `for_each` CANNOT both be used on the same resource or module block.
  • To pass a `list(string)` to `for_each`, convert it first with `toset(var.list)`.
  • `count` takes an integer and indexes by position (`[0]`); `for_each` takes a `map` or `set(string)` and indexes by key (`["prod"]`), preventing cascading re-creations.
5How does the native `terraform test` framework (Terraform 1.6+, tested on Exam 004) validate modules and configurations?`terraform test` executes `.tftest.hcl` files with `run` blocks and `assert` conditions, supporting both integration tests (`apply`) and offline unit tests (`plan` + `mock_provider`).Using `mock_provider "aws" {}` inside `tests/unit.tftest.hcl` lets CI pipelines verify complex HCL variable transformations, module outputs, and preconditions in seconds without needing cloud credentials or provisioning real resources.
  • `terraform test` executes `.tftest.hcl` files with `run` blocks and `assert` conditions, supporting both integration tests (`apply`) and offline unit tests (`plan` + `mock_provider`).
  • Reads `*.tftest.hcl` files (`tests/` directory by default), executes `run "<name>" { command = plan|apply; assert { condition = ... error_message = ... } }`, and cleans up created resources automatically.
  • Terraform 1.7+ added `mock_provider` and `override_resource`/`override_data` for credential-free unit testing.
6In HCP Terraform (formerly Terraform Cloud) and Sentinel / OPA Policy-as-Code, at what point in the run lifecycle are policies evaluated, and what are the three Sentinel enforcement levels?Policies evaluate **between `plan` and `apply`**; Sentinel offers `advisory` (warn only), `soft-mandatory` (authorized override allowed), and `hard-mandatory` (cannot be overridden).A `hard-mandatory` Sentinel policy checking that no S3 bucket has `acl == "public-read"` or that estimated monthly run cost delta is `< $500` blocks the run immediately after `plan` with zero possibility of manual override.
  • Runs post-plan / pre-apply; Sentinel enforcement levels: `advisory`, `soft-mandatory`, and `hard-mandatory` (OPA policies use `advisory` and `mandatory`).
  • Cost Estimation also runs after `plan` so Sentinel/OPA policies can enforce FinOps budget guardrails before `apply`.
  • Policies evaluate **between `plan` and `apply`**; Sentinel offers `advisory` (warn only), `soft-mandatory` (authorized override allowed), and `hard-mandatory` (cannot be overridden).
7Which module `source` types support the `version` argument (e.g., `version = "~> 5.0"`) inside a `module` block?The `version` argument is ONLY supported for modules fetched from a **Terraform Registry** (Public Registry or Private Registry in HCP Terraform).Modules sourced from local paths (`./modules/vpc`), GitHub/Git URLs (`git::https://example.com/vpc.git?ref=v1.2.0`), or S3/GCS buckets do NOT accept the `version` attribute—Git sources pin versions using the `?ref=<tag/branch/sha>` query string instead!
  • Only Public and Private Terraform Registry sources support `version = "..."`; Git sources use `?ref=v1.0.0`, and local path sources (`./...`) do not support versioning.
  • Running `terraform init` (or `terraform get`) downloads child modules into `.terraform/modules/`.
  • The `version` argument is ONLY supported for modules fetched from a **Terraform Registry** (Public Registry or Private Registry in HCP Terraform).
8Compare `terraform state mv` vs. declarative `moved` blocks, and `terraform state rm` vs. declarative `removed` blocks.`moved` and `removed` blocks refactor state declaratively in HCL during `plan`/`apply`, replacing imperative `terraform state mv` and `terraform state rm` commands.When renaming `aws_instance.app` to `aws_instance.web` inside a shared module or team GitOps pipeline, committing a `moved` block ensures every workspace updates its state automatically on the next `terraform apply` without destroying the VM.
  • `moved` blocks rename/relocate resources in state without destroying them; `removed` blocks (`destroy = false`) forget a resource from state while leaving the real cloud object intact.
  • `terraform state list` and `terraform state show <address>` remain the primary read-only CLI inspection commands.
  • `moved` and `removed` blocks refactor state declaratively in HCL during `plan`/`apply`, replacing imperative `terraform state mv` and `terraform state rm` commands.
9When a `local-exec` or `remote-exec` provisioner IS used, what happens by default if the script exits with a non-zero status code, and how can you change that behavior?By default (`on_failure = fail`), a failing creation-time provisioner fails the run and marks the resource **tainted** in state; `on_failure = continue` ignores errors.Creation-time provisioners run during initial resource creation (`when = create`, default), whereas a provisioner with `when = destroy` runs immediately before the resource is destroyed.
  • Default is `on_failure = fail`, which marks the newly created resource as tainted for replacement on the next apply; `on_failure = continue` suppresses failure.
  • `local-exec` runs the command on the machine executing Terraform (or the HCP Terraform runner), whereas `remote-exec` runs on the target cloud resource via a `connection` block.
  • By default (`on_failure = fail`), a failing creation-time provisioner fails the run and marks the resource **tainted** in state; `on_failure = continue` ignores errors.
10How do Implicit Dependencies and Explicit Dependencies (`depends_on`) differ in Terraform's execution graph?Terraform infers Implicit Dependencies automatically from attribute references (`vpc_id = aws_vpc.main.id`); `depends_on` is only needed for hidden side-effect dependencies without attribute references.If an EC2 instance's bootstrap script needs an `aws_iam_role_policy_attachment` or an `aws_s3_bucket_policy` to exist before booting—even though the instance block doesn't reference that policy's ID—you add `depends_on = [aws_iam_role_policy_attachment.app]`.
  • Always prefer implicit reference dependencies; use `depends_on` only when a resource relies on another resource's behavior without referencing its attributes.
  • Terraform executes independent nodes in the dependency graph in parallel (default `-parallelism=10`).
  • Terraform infers Implicit Dependencies automatically from attribute references (`vpc_id = aws_vpc.main.id`); `depends_on` is only needed for hidden side-effect dependencies without attribute references.
11How does config-driven `import` (`import { to = ... id = ... }`) in Terraform 1.5+ improve upon the legacy imperative `terraform import <address> <id>` CLI command?Declarative `import` blocks execute inside the standard `plan`/`apply` cycle, support `for_each`, and auto-generate HCL configuration via `terraform plan -generate-config-out=generated.tf`.Unlike legacy `terraform import` (which immediately mutates state without a plan preview and requires writing the `resource` block manually beforehand), `import` blocks preview the exact import in `terraform plan`.
  • Runs safely inside `plan` and `apply`, works in GitOps/HCP Terraform remote runs, and supports `-generate-config-out` to scaffold resource HCL.
  • Declarative `import` blocks execute inside the standard `plan`/`apply` cycle, support `for_each`, and auto-generate HCL configuration via `terraform plan -generate-config-out=generated.tf`.
  • Neither legacy `terraform import` nor `import` blocks deletes the cloud resource if you later delete the `import` block after state adoption.
12In Terraform HCL expressions, what is the Splat Expression (`[*]`), how does `try()` / `can()` handle errors, and how do you test built-in functions interactively?The Splat operator (`aws_instance.web[*].id`) extracts attributes across a list/tuple/set; `try()` and `can()` handle evaluation errors; `terraform console` opens an interactive expression REPL.Note that the Splat operator `[*]` works on `count` resources (`aws_instance.web[*].id`) and lists, but does NOT work directly on `for_each` maps—for `for_each` maps, use `values(aws_instance.web)[*].id` or a `[for k, v in ...]` expression!
  • The Splat operator (`aws_instance.web[*].id`) extracts attributes across a list/tuple/set; `try()` and `can()` handle evaluation errors; `terraform console` opens an interactive expression REPL.
  • Use `terraform console` to test HCL functions like `cidrsubnet()`, `lookup()`, `merge()`, `flatten()`, `jsonencode()`, `templatefile()`, `toset()`, and `try()` interactively.
  • Terraform does NOT support user-defined custom HCL functions (outside provider-defined functions in Terraform 1.8+: `provider::<provider>::<func>()`).
13What are the six stages of the core Terraform CLI workflow, and what does each command do regarding state and cloud APIs?`init` initializes backend/providers/modules; `fmt` formats HCL; `validate` checks syntax offline; `plan` previews diffs; `apply` executes changes; `destroy` deletes managed infrastructure.Crucially for the exam, `terraform validate` runs entirely offline against downloaded provider schemas and does NOT access remote state or cloud APIs, whereas `terraform plan` and `terraform apply` refresh remote state by default.
  • Write -> `init` (downloads plugins/backend) -> `fmt` / `validate` (offline syntax check) -> `plan` (calculates execution plan) -> `apply` (provisions) -> `destroy`.
  • `init` initializes backend/providers/modules; `fmt` formats HCL; `validate` checks syntax offline; `plan` previews diffs; `apply` executes changes; `destroy` deletes managed infrastructure.
  • Running `terraform apply tfplan` with a saved binary plan file skips confirmation prompts because the exact changes were already reviewed.
14What does the Dependency Lock File (`.terraform.lock.hcl`) track, and should it be committed to Version Control (Git)?`.terraform.lock.hcl` locks the exact versions and SHA-256 hashes of **Providers** only (NOT modules!) and MUST be committed to Git.When you change a provider version constraint in `required_providers`, running `terraform init -upgrade` updates `.terraform.lock.hcl` to the newest allowed provider release.
  • `.terraform.lock.hcl` locks the exact versions and SHA-256 hashes of **Providers** only (NOT modules!) and MUST be committed to Git.
  • Locks provider versions and cryptographic checksums (does NOT lock child modules); always commit `.terraform.lock.hcl` to Git, and never commit `.terraform/` or `terraform.tfstate`.
  • Use `terraform providers lock -platform=linux_amd64 -platform=darwin_arm64` to pre-populate checksums across multiple OS architectures.
15How does variable and resource scoping work between a Root Module and a Child Module in Terraform?Modules are encapsulated: Child Modules only see explicitly passed input variables, and the Root Module only sees Child Module attributes exported via `output` blocks.If child module `modules/vpc` creates `aws_vpc.main`, the root module cannot reference `module.vpc.aws_vpc.main.id` directly—`modules/vpc/outputs.tf` must declare `output "vpc_id" { value = aws_vpc.main.id }`, which the root module accesses as `module.vpc.vpc_id`.
  • Modules are encapsulated: Child Modules only see explicitly passed input variables, and the Root Module only sees Child Module attributes exported via `output` blocks.
  • Pass inputs down via `module "name" { var_name = ... }`; pass outputs up via child `output` blocks referenced as `module.<module_name>.<output_name>`.
  • Every Terraform configuration has at least one module—the Root Module consisting of `.tf` files in the current working directory.
16What is the format, duration, and question type breakdown of the HashiCorp Certified: Terraform Associate (003 / 004) exam?57 questions in 60 minutes consisting of multiple-choice, multiple-answer, true/false, and text-match questions covering Terraform Community Edition and HCP Terraform.Exam 004 updates the blueprint to emphasize config-driven refactoring (`import`, `moved`, and `removed` blocks), native `check` assertions, the `terraform test` framework, and ephemeral values/write-only arguments alongside core HCL and state management.
  • 57 questions over 60 minutes testing IaC concepts, Terraform workflow, HCL syntax, modules, state management, and HCP Terraform (formerly Terraform Cloud).
  • Certification remains valid for 2 years.
  • 57 questions in 60 minutes consisting of multiple-choice, multiple-answer, true/false, and text-match questions covering Terraform Community Edition and HCP Terraform.
17Compare CLI-managed OSS `terraform workspace` (Local/Backend Workspaces) vs. **HCP Terraform Workspaces** (formerly Terraform Cloud Workspaces).CLI OSS workspaces are simply alternate state files sharing one working directory; HCP Terraform Workspaces are isolated environments with independent variables, state, VCS, and RBAC.HashiCorp warns that CLI OSS workspaces alone are NOT suitable for strong security isolation between prod and dev (since they share backend credentials), whereas HCP Terraform Workspaces enforce strict per-workspace RBAC.
  • CLI OSS workspaces are simply alternate state files sharing one working directory; HCP Terraform Workspaces are isolated environments with independent variables, state, VCS, and RBAC.
  • CLI Workspaces (`${terraform.workspace}`) = multiple state files in one backend (`env:/`); HCP Terraform Workspaces = independent cloud environments with RBAC, VCS triggers, and private state.
  • The default CLI workspace is always named `default` and cannot be deleted.
18What are the three Execution Modes available in an HCP Terraform Workspace?`Remote` (runs on HCP managed runners), `Local` (runs on local CLI while HCP stores/locks state), and `Agent` (runs on self-hosted private `tfc-agent` workers).When an enterprise needs HCP Terraform to provision internal VMware vSphere or private AKS/GKE clusters behind a corporate firewall without opening inbound firewall ports, they select `Agent` execution mode with HCP Terraform Agents.
  • `Remote` (runs on HCP managed runners), `Local` (runs on local CLI while HCP stores/locks state), and `Agent` (runs on self-hosted private `tfc-agent` workers).
  • Remote = HCP cloud runners + VCS/UI workflows; Local = local CLI compute + remote HCP state/locking; Agent = self-hosted private network runners (`tfc-agent`).
  • `terraform login` generates a user API token stored in `~/.terraform.d/credentials.tfrc.json` to authenticate the CLI with HCP Terraform.
19What problem do `dynamic` blocks solve in Terraform HCL, and when should you avoid overusing them?`dynamic` blocks generate repeatable nested configuration blocks (such as `ingress` rules) inside a resource using `for_each` and a `content {}` block.Inside an `aws_security_group`, a `dynamic "ingress" { for_each = var.ports; content { from_port = ingress.value ... } }` block generates one `ingress` block per port; however, use literal blocks when possible for readability.
  • `dynamic` blocks generate repeatable nested configuration blocks (such as `ingress` rules) inside a resource using `for_each` and a `content {}` block.
  • Generates multiple nested blocks inside a resource using `dynamic "<label>" { for_each = ... content { ... } }`.
  • By default, the iterator variable inside `content {}` is named after the dynamic block label (unless overridden via `iterator = ...`).
20Why does HashiCorp state that Terraform `provisioner` blocks (`local-exec`, `remote-exec`, `file`) should only be used as a **last resort**?Provisioners execute imperative scripts outside Terraform's declarative graph: Terraform cannot model, preview, or roll back script changes inside `terraform plan`.Instead of using `remote-exec` over SSH/WinRM to install packages on a new VM, HashiCorp recommends passing declarative `user_data` / `custom_data` (`cloud-init`) or pre-baking immutable machine images with **HashiCorp Packer**.
  • Provisioners execute imperative scripts outside Terraform's declarative graph: Terraform cannot model, preview, or roll back script changes inside `terraform plan`.
  • Provisioners are opaque to `terraform plan`, brittle (require direct network/SSH access for `remote-exec`), and do not track configuration drift.
  • Prefer `cloud-init` / `user_data`, native provider resources, or immutable golden images built with Packer.
21Why was `terraform taint` deprecated in Terraform 0.15.2+, and what command or meta-argument replaces it?`terraform apply -replace="<resource_address>"` replaced `terraform taint` so replacement happens atomically inside a single planned run without mutating state beforehand.If `terraform taint aws_instance.web` was run by mistake in legacy workflows, another teammate running `terraform apply` would unexpectedly recreate the VM; `terraform apply -replace="aws_instance.web[0]"` scopes the replacement to that exact execution plan.
  • Use `terraform apply -replace="<address>"` for one-off CLI replacements, or `lifecycle { replace_triggered_by = [...] }` for config-driven replacements.
  • Avoids persistent state side-effects prior to plan approval.
  • `terraform apply -replace="<resource_address>"` replaced `terraform taint` so replacement happens atomically inside a single planned run without mutating state beforehand.
22Compare Input Variables (`var.<name>`), Local Values (`local.<name>`), and Output Values (`output`) in Terraform.Input Variables (`var.x`) parameterize a module externally; Local Values (`local.x` in `locals {}`) define internal reusable expressions; Outputs (`output "x"`) export values.Notice the singular vs. plural syntax trap tested on the exam: you declare `variable "x" {}` (singular) and reference `var.x`, whereas you declare `locals { x = ... }` (plural block!) and reference `local.x` (singular!).
  • Variables = external inputs (`var.<name>`); Locals = internal DRY expressions (`locals {}` -> `local.<name>`); Outputs = returned values (`output "<name>" {}` -> `module.<mod>.<output>`).
  • Root module outputs can be queried at any time via `terraform output` or `terraform output -json`.
  • Input Variables (`var.x`) parameterize a module externally; Local Values (`local.x` in `locals {}`) define internal reusable expressions; Outputs (`output "x"`) export values.
23How do Custom Condition Checks (`validation`, `precondition`, `postcondition`) and `check` blocks differ in Terraform?`validation`, `precondition`, and `postcondition` are **blocking** (halt `plan`/`apply` on failure), whereas standalone `check` blocks execute non-blocking assertions that only emit warnings!Adding a `check "health_check" { data "http" "api" { ... } assert { condition = data.http.api.status_code == 200 ... } }` block verifies that a newly deployed load balancer returns HTTP 200 after `apply` completes.
  • `validation`, `precondition`, and `postcondition` are **blocking** (halt `plan`/`apply` on failure), whereas standalone `check` blocks execute non-blocking assertions that only emit warnings!
  • `validation`/`precondition`/`postcondition` fail and block `plan`/`apply`; `check` blocks (with optional scoped `data` sources) validate real-world infrastructure health and only warn on failure.
  • Variable `validation` in Terraform 1.9+ can also reference other variables, locals, and data sources.
24What is the exact order of precedence (from lowest to highest priority) when Terraform loads Input Variable (`variable`) values?Lowest to highest: 1) variable `default` -> 2) `TF_VAR_<name>` -> 3) `terraform.tfvars` -> 4) `terraform.tfvars.json` -> 5) `*.auto.tfvars` -> 6) CLI `-var` / `-var-file`.If `instance_type` is set to `t3.micro` in `TF_VAR_instance_type`, `t3.small` in `terraform.tfvars`, `t3.medium` in `prod.auto.tfvars`, and `-var="instance_type=t3.large"` on the CLI, Terraform uses `t3.large`.
  • Lowest = variable `default` / `TF_VAR_name`; Middle = `terraform.tfvars` then `*.auto.tfvars`; Highest = `-var` and `-var-file` on the command line.
  • Lowest to highest: 1) variable `default` -> 2) `TF_VAR_<name>` -> 3) `terraform.tfvars` -> 4) `terraform.tfvars.json` -> 5) `*.auto.tfvars` -> 6) CLI `-var` / `-var-file`.
  • If no value is provided anywhere and the variable has no `default`, Terraform prompts interactively on the CLI.
25Why does Terraform require a State file (`terraform.tfstate`), and why must teams use a Remote Backend with State Locking?State maps HCL addresses to real-world cloud IDs and tracks dependencies; remote backends share encrypted state and lock it during runs.Without state locking, two engineers running `terraform apply` concurrently could corrupt state or create duplicate resources; if a lock gets stuck after a crash, clear it cautiously with `terraform force-unlock <LOCK_ID>`.
  • Maps declarative HCL to real-world IDs, tracks dependency order (`depends_on`), and improves performance; remote backends encrypt state at rest and prevent concurrent write corruption via state locking.
  • Note that standard Git repositories are NOT a supported Terraform state backend and should never store `terraform.tfstate`.
  • State maps HCL addresses to real-world cloud IDs and tracks dependencies; remote backends share encrypted state and lock it during runs.
26How does integrating Terraform with HashiCorp Vault reduce secret sprawl, and what is the caveat with the standard `data "vault_generic_secret"` data source?Vault injects short-lived dynamic credentials during runs, though standard `data` sources still write secrets into `terraform.tfstate` unless using `ephemeral` Vault resources.Because standard Vault data sources write fetched database passwords into `terraform.tfstate`, architects restrict RBAC on the remote state bucket, enable KMS encryption, or use Terraform 1.10+ `ephemeral` blocks with write-only resource attributes.
  • Vault dynamically generates short-lived cloud/DB credentials at `plan`/`apply` time; protect `terraform.tfstate` or use `ephemeral` resources so secrets aren't exposed.
  • Vault injects short-lived dynamic credentials during runs, though standard `data` sources still write secrets into `terraform.tfstate` unless using `ephemeral` Vault resources.
  • HCP Terraform Dynamic Provider Credentials can also authenticate directly to AWS, Azure, GCP, and Vault via OIDC Workload Identity without static keys.
27How do you enable verbose debugging logs in Terraform CLI, and how do you save them to a file without cluttering standard output?Set `TF_LOG` to `TRACE`, `DEBUG`, `INFO`, `WARN`, or `ERROR` (`TRACE` is most verbose) and set `TF_LOG_PATH` (e.g., `./terraform.log`) to save logs.To debug only provider plugin API calls or only Terraform core graph evaluation, you can also set `TF_LOG_PROVIDER=TRACE` or `TF_LOG_CORE=TRACE` independently.
  • `TF_LOG=TRACE` (most detailed, followed by `DEBUG`, `INFO`, `WARN`, `ERROR`) + `TF_LOG_PATH=/path/to/file.log`.
  • `TF_LOG_PATH` requires `TF_LOG` (or `TF_LOG_CORE`/`TF_LOG_PROVIDER`) to also be set in order to write logs.
  • Set `TF_LOG` to `TRACE`, `DEBUG`, `INFO`, `WARN`, or `ERROR` (`TRACE` is most verbose) and set `TF_LOG_PATH` (e.g., `./terraform.log`) to save logs.
28Explain the four `lifecycle` meta-arguments in Terraform: `create_before_destroy`, `prevent_destroy`, `ignore_changes`, and `replace_triggered_by`.`create_before_destroy` creates replacements first; `prevent_destroy` blocks destruction plans; `ignore_changes` ignores drift on listed attributes; `replace_triggered_by` forces replacement when referenced items change.Note an important exam nuance: `prevent_destroy = true` protects against accidental replacement or `terraform destroy` while the block remains in HCL, but removing the entire `resource` block from HCL bypasses `prevent_destroy`!
  • `create_before_destroy` (zero-downtime swaps), `prevent_destroy` (blocks destruction), `ignore_changes = [tags, ami]` (ignores out-of-band modifications), `replace_triggered_by` (cascades replacements) plus `precondition`/`postcondition` checks.
  • `create_before_destroy` propagates automatically to upstream dependencies.
  • `create_before_destroy` creates replacements first; `prevent_destroy` blocks destruction plans; `ignore_changes` ignores drift on listed attributes; `replace_triggered_by` forces replacement when referenced items change.
29In Terraform version constraint expressions, what do the operators `=`, `!=`, `>=`, `~>` (pessimistic constraint), and `1.2.0` mean?The pessimistic operator `~>` allows only the rightmost version component to increment: `~> 1.2` allows `>= 1.2.0, < 2.0.0`; `~> 1.2.3` allows `< 1.3.0`.Writing `version = "~> 5.4.0"` on a provider or registry module permits patch bug-fix upgrades (`5.4.1`, `5.4.9`) while blocking minor (`5.5.0`) and major (`6.0.0`) releases.
  • `~> X.Y` allows minor and patch updates (`< (X+1).0.0`); `~> X.Y.Z` allows patch updates only (`< X.(Y+1).0`).
  • The pessimistic operator `~>` allows only the rightmost version component to increment: `~> 1.2` allows `>= 1.2.0, < 2.0.0`; `~> 1.2.3` allows `< 1.3.0`.
  • Omitting an operator (`version = "1.2.0"`) is equivalent to exact equality (`= 1.2.0`).
30When migrating from a local state file to a remote `backend` block (or changing backends), which `terraform init` flags are used?Use `terraform init -migrate-state` to copy existing state to the new backend, or `terraform init -reconfigure` to ignore prior state.After adding `backend "azurerm" { ... }` or a `cloud { ... }` block to `terraform {}`, running `terraform init -migrate-state` safely uploads local `terraform.tfstate` into the remote backend.
  • `-migrate-state` copies existing state to the new backend; `-reconfigure` discards prior backend configuration and initializes fresh.
  • Note that `backend` blocks cannot reference input variables (`var.*`), locals, or data sources—use `-backend-config=file.hcl` for dynamic partial configurations.
  • Use `terraform init -migrate-state` to copy existing state to the new backend, or `terraform init -reconfigure` to ignore prior state.
31What is the difference between a `resource` block and a `data` block (Data Source) in Terraform?A `resource` block creates, updates, and destroys managed infrastructure; a `data` block performs a read-only query against a provider API without managing lifecycle.Referencing `data.aws_ami.ubuntu.id` queries AWS for the latest canonical Ubuntu AMI ID during the plan phase without taking ownership of that AMI.
  • `resource` = read/write lifecycle management (`<type>.<name>.<attr>`); `data` = read-only lookup (`data.<type>.<name>.<attr>`).
  • If a `data` source depends on a managed resource attribute not known until apply, Terraform defers reading the data source until the `apply` phase.
  • A `resource` block creates, updates, and destroys managed infrastructure; a `data` block performs a read-only query against a provider API without managing lifecycle.
32How do you configure multiple configurations of the same Terraform Provider (for example, deploying resources across `us-east-1` and `us-west-2` in the same root module)?Define a default `provider` block and additional `provider` blocks with the `alias` meta-argument, then reference `provider = <provider>.<alias>` on resources.A second `provider "aws" { alias = "west"; region = "us-west-2" }` block is referenced on a DR bucket via `provider = aws.west`, or passed to child modules via `providers`.
  • Use the `alias` meta-argument on additional `provider` blocks and select them with `provider = <name>.<alias>` on resources/data sources.
  • Inside reusable child modules, declare `configuration_aliases` in `required_providers` instead of hardcoding provider blocks.
  • Define a default `provider` block and additional `provider` blocks with the `alias` meta-argument, then reference `provider = <provider>.<alias>` on resources.