# 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.

- **Canonical URL:** https://flashcards.world/flashcards/sets/f30a1d59-7876-4e94-a18b-5c3892417721/
- **Markdown URL:** https://flashcards.world/flashcards/sets/f30a1d59-7876-4e94-a18b-5c3892417721.md
- **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
- **Total Cards:** 32

## Flashcards (32 Cards)

| # | Front (Term / Prompt) | Back (Definition / Answer) | Example | Multiple-Choice Options |
| :--- | :--- | :--- | :--- | :--- |
| 1 | In 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. | A) Projects = RBAC and organizational grouping of Workspaces; Variable Sets = reusable central variables across Workspaces/Projects; Run Triggers = cross-workspace dependency chaining.; B) No-Code Provisioning in HCP Terraform also allows self-service deployment of approved Private Registry modules without writing HCL.; C) Projects group Workspaces for RBAC; Variable Sets share variables/credentials across Projects or Workspaces; Run Triggers queue downstream Workspace plans when upstream Workspaces apply. ✓ |
| 2 | Compare `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. | A) Legacy `terraform refresh` overwrote state immediately without a confirmation prompt; `terraform plan/apply -refresh-only` previews state updates safely.; B) `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. ✓; C) Wait: `terraform apply -refresh-only` updates the Terraform state file to match real cloud resources—it does NOT revert the cloud resources! |
| 3 | Does 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. | A) `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.; B) In Terraform 1.10+ (004), `ephemeral` blocks and write-only (`_wo`) attributes never persist to state.; C) NO! Setting `sensitive = true` only redacts the value from CLI terminal output and logs; the plaintext value still persists in `terraform.tfstate`! ✓ |
| 4 | Compare 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. | A) `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.; B) To pass a `list(string)` to `for_each`, convert it first with `toset(var.list)`.; C) `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. ✓ |
| 5 | How 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. | A) `terraform test` executes `.tftest.hcl` files with `run` blocks and `assert` conditions, supporting both integration tests (`apply`) and offline unit tests (`plan` + `mock_provider`). ✓; B) Reads `*.tftest.hcl` files (`tests/` directory by default), executes `run "<name>" { command = plan\|apply; assert { condition = ... error_message = ... } }`, and cleans up created resources automatically.; C) Terraform 1.7+ added `mock_provider` and `override_resource`/`override_data` for credential-free unit testing. |
| 6 | In 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. | A) Runs post-plan / pre-apply; Sentinel enforcement levels: `advisory`, `soft-mandatory`, and `hard-mandatory` (OPA policies use `advisory` and `mandatory`).; B) Cost Estimation also runs after `plan` so Sentinel/OPA policies can enforce FinOps budget guardrails before `apply`.; C) Policies evaluate **between `plan` and `apply`**; Sentinel offers `advisory` (warn only), `soft-mandatory` (authorized override allowed), and `hard-mandatory` (cannot be overridden). ✓ |
| 7 | Which 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! | A) Only Public and Private Terraform Registry sources support `version = "..."`; Git sources use `?ref=v1.0.0`, and local path sources (`./...`) do not support versioning.; B) Running `terraform init` (or `terraform get`) downloads child modules into `.terraform/modules/`.; C) The `version` argument is ONLY supported for modules fetched from a **Terraform Registry** (Public Registry or Private Registry in HCP Terraform). ✓ |
| 8 | Compare `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. | A) `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.; B) `terraform state list` and `terraform state show <address>` remain the primary read-only CLI inspection commands.; C) `moved` and `removed` blocks refactor state declaratively in HCL during `plan`/`apply`, replacing imperative `terraform state mv` and `terraform state rm` commands. ✓ |
| 9 | When 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. | A) Default is `on_failure = fail`, which marks the newly created resource as tainted for replacement on the next apply; `on_failure = continue` suppresses failure.; B) `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.; C) 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. ✓ |
| 10 | How 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]`. | A) Always prefer implicit reference dependencies; use `depends_on` only when a resource relies on another resource's behavior without referencing its attributes.; B) Terraform executes independent nodes in the dependency graph in parallel (default `-parallelism=10`).; C) 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. ✓ |
| 11 | How 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`. | A) Runs safely inside `plan` and `apply`, works in GitOps/HCP Terraform remote runs, and supports `-generate-config-out` to scaffold resource HCL.; B) 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`. ✓; C) Neither legacy `terraform import` nor `import` blocks deletes the cloud resource if you later delete the `import` block after state adoption. |
| 12 | In 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! | A) 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. ✓; B) Use `terraform console` to test HCL functions like `cidrsubnet()`, `lookup()`, `merge()`, `flatten()`, `jsonencode()`, `templatefile()`, `toset()`, and `try()` interactively.; C) Terraform does NOT support user-defined custom HCL functions (outside provider-defined functions in Terraform 1.8+: `provider::<provider>::<func>()`). |
| 13 | What 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. | A) Write -> `init` (downloads plugins/backend) -> `fmt` / `validate` (offline syntax check) -> `plan` (calculates execution plan) -> `apply` (provisions) -> `destroy`.; B) `init` initializes backend/providers/modules; `fmt` formats HCL; `validate` checks syntax offline; `plan` previews diffs; `apply` executes changes; `destroy` deletes managed infrastructure. ✓; C) Running `terraform apply tfplan` with a saved binary plan file skips confirmation prompts because the exact changes were already reviewed. |
| 14 | What 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. | A) `.terraform.lock.hcl` locks the exact versions and SHA-256 hashes of **Providers** only (NOT modules!) and MUST be committed to Git. ✓; B) 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`.; C) Use `terraform providers lock -platform=linux_amd64 -platform=darwin_arm64` to pre-populate checksums across multiple OS architectures. |
| 15 | How 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`. | A) Modules are encapsulated: Child Modules only see explicitly passed input variables, and the Root Module only sees Child Module attributes exported via `output` blocks. ✓; B) Pass inputs down via `module "name" { var_name = ... }`; pass outputs up via child `output` blocks referenced as `module.<module_name>.<output_name>`.; C) Every Terraform configuration has at least one module—the Root Module consisting of `.tf` files in the current working directory. |
| 16 | What 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. | A) 57 questions over 60 minutes testing IaC concepts, Terraform workflow, HCL syntax, modules, state management, and HCP Terraform (formerly Terraform Cloud).; B) Certification remains valid for 2 years.; C) 57 questions in 60 minutes consisting of multiple-choice, multiple-answer, true/false, and text-match questions covering Terraform Community Edition and HCP Terraform. ✓ |
| 17 | Compare 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. | A) 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. ✓; B) CLI Workspaces (`${terraform.workspace}`) = multiple state files in one backend (`env:/`); HCP Terraform Workspaces = independent cloud environments with RBAC, VCS triggers, and private state.; C) The default CLI workspace is always named `default` and cannot be deleted. |
| 18 | What 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. | A) `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). ✓; B) Remote = HCP cloud runners + VCS/UI workflows; Local = local CLI compute + remote HCP state/locking; Agent = self-hosted private network runners (`tfc-agent`).; C) `terraform login` generates a user API token stored in `~/.terraform.d/credentials.tfrc.json` to authenticate the CLI with HCP Terraform. |
| 19 | What 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. | A) `dynamic` blocks generate repeatable nested configuration blocks (such as `ingress` rules) inside a resource using `for_each` and a `content {}` block. ✓; B) Generates multiple nested blocks inside a resource using `dynamic "<label>" { for_each = ... content { ... } }`.; C) By default, the iterator variable inside `content {}` is named after the dynamic block label (unless overridden via `iterator = ...`). |
| 20 | Why 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**. | A) Provisioners execute imperative scripts outside Terraform's declarative graph: Terraform cannot model, preview, or roll back script changes inside `terraform plan`. ✓; B) Provisioners are opaque to `terraform plan`, brittle (require direct network/SSH access for `remote-exec`), and do not track configuration drift.; C) Prefer `cloud-init` / `user_data`, native provider resources, or immutable golden images built with Packer. |
| 21 | Why 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. | A) Use `terraform apply -replace="<address>"` for one-off CLI replacements, or `lifecycle { replace_triggered_by = [...] }` for config-driven replacements.; B) Avoids persistent state side-effects prior to plan approval.; C) `terraform apply -replace="<resource_address>"` replaced `terraform taint` so replacement happens atomically inside a single planned run without mutating state beforehand. ✓ |
| 22 | Compare 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!). | A) Variables = external inputs (`var.<name>`); Locals = internal DRY expressions (`locals {}` -> `local.<name>`); Outputs = returned values (`output "<name>" {}` -> `module.<mod>.<output>`).; B) Root module outputs can be queried at any time via `terraform output` or `terraform output -json`.; C) Input Variables (`var.x`) parameterize a module externally; Local Values (`local.x` in `locals {}`) define internal reusable expressions; Outputs (`output "x"`) export values. ✓ |
| 23 | How 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. | A) `validation`, `precondition`, and `postcondition` are **blocking** (halt `plan`/`apply` on failure), whereas standalone `check` blocks execute non-blocking assertions that only emit warnings! ✓; B) `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.; C) Variable `validation` in Terraform 1.9+ can also reference other variables, locals, and data sources. |
| 24 | What 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`. | A) Lowest = variable `default` / `TF_VAR_name`; Middle = `terraform.tfvars` then `*.auto.tfvars`; Highest = `-var` and `-var-file` on the command line.; B) 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`. ✓; C) If no value is provided anywhere and the variable has no `default`, Terraform prompts interactively on the CLI. |
| 25 | Why 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>`. | A) 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.; B) Note that standard Git repositories are NOT a supported Terraform state backend and should never store `terraform.tfstate`.; C) State maps HCL addresses to real-world cloud IDs and tracks dependencies; remote backends share encrypted state and lock it during runs. ✓ |
| 26 | How 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. | A) Vault dynamically generates short-lived cloud/DB credentials at `plan`/`apply` time; protect `terraform.tfstate` or use `ephemeral` resources so secrets aren't exposed.; B) Vault injects short-lived dynamic credentials during runs, though standard `data` sources still write secrets into `terraform.tfstate` unless using `ephemeral` Vault resources. ✓; C) HCP Terraform Dynamic Provider Credentials can also authenticate directly to AWS, Azure, GCP, and Vault via OIDC Workload Identity without static keys. |
| 27 | How 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. | A) `TF_LOG=TRACE` (most detailed, followed by `DEBUG`, `INFO`, `WARN`, `ERROR`) + `TF_LOG_PATH=/path/to/file.log`.; B) `TF_LOG_PATH` requires `TF_LOG` (or `TF_LOG_CORE`/`TF_LOG_PROVIDER`) to also be set in order to write logs.; C) 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. ✓ |
| 28 | Explain 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`! | A) `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.; B) `create_before_destroy` propagates automatically to upstream dependencies.; C) `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. ✓ |
| 29 | In 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. | A) `~> X.Y` allows minor and patch updates (`< (X+1).0.0`); `~> X.Y.Z` allows patch updates only (`< X.(Y+1).0`).; B) 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`. ✓; C) Omitting an operator (`version = "1.2.0"`) is equivalent to exact equality (`= 1.2.0`). |
| 30 | When 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. | A) `-migrate-state` copies existing state to the new backend; `-reconfigure` discards prior backend configuration and initializes fresh.; B) Note that `backend` blocks cannot reference input variables (`var.*`), locals, or data sources—use `-backend-config=file.hcl` for dynamic partial configurations.; C) Use `terraform init -migrate-state` to copy existing state to the new backend, or `terraform init -reconfigure` to ignore prior state. ✓ |
| 31 | What 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. | A) `resource` = read/write lifecycle management (`<type>.<name>.<attr>`); `data` = read-only lookup (`data.<type>.<name>.<attr>`).; B) If a `data` source depends on a managed resource attribute not known until apply, Terraform defers reading the data source until the `apply` phase.; C) A `resource` block creates, updates, and destroys managed infrastructure; a `data` block performs a read-only query against a provider API without managing lifecycle. ✓ |
| 32 | How 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`. | A) Use the `alias` meta-argument on additional `provider` blocks and select them with `provider = <name>.<alias>` on resources/data sources.; B) Inside reusable child modules, declare `configuration_aliases` in `required_providers` instead of hardcoding provider blocks.; C) Define a default `provider` block and additional `provider` blocks with the `alias` meta-argument, then reference `provider = <provider>.<alias>` on resources. ✓ |

---
Study this deck interactively with FSRS-6 spaced repetition, audio review, and multiple-choice mode at [Flashcards World](https://flashcards.world/flashcards/sets/f30a1d59-7876-4e94-a18b-5c3892417721/).
