supraj.dev

Interview questions & answers

Terraform

State, plan/apply, modules, and drift.

  • 136 questions
  • 4 easy
  • 51 medium
  • 81 hard
  • 1 related article

136 questions

Question 1Easy

What is Terraform state and why does it matter?

#
Show answer

State is Terraform's record (terraform.tfstate) mapping your configuration to real-world resource IDs. It's how Terraform knows what it already created, computes diffs, and stores metadata/dependencies. Without it Terraform couldn't tell create from update from delete. It can contain secrets, so it should live in a secure remote backend, never plain in git.

Question 2Easy

What is the difference between terraform plan and apply?

#
Show answer

plan computes and shows the diff between desired config and current state — what will be created, changed, or destroyed — without making changes. apply executes that plan against the real infrastructure. In CI you typically save the plan and apply exactly that artifact so what you reviewed is what runs.

Question 3Medium

Why use remote state with locking, and how does locking work?

#
Show answer

Remote state (S3, GCS, Terraform Cloud) lets a team share one source of truth and keeps secrets off laptops. Locking (e.g. DynamoDB for the S3 backend) prevents two applies from running at once and corrupting state — the first apply takes the lock, others wait or fail fast. Always pair remote state with a lock for any shared environment.

Question 4Medium

What is configuration drift and how do you handle it?

#
Show answer

Drift is when real infrastructure no longer matches state because someone changed it out-of-band (console click, another tool). terraform plan surfaces it as unexpected changes; terraform refresh/-refresh-only reconciles state with reality. You fix it by re-applying to bring resources back to config, or by importing/updating config to match the intended new reality — and ideally prevent it with policy and least-privilege console access.

Question 5Hard

How do count and for_each differ, and when do you prefer for_each?

#
Show answer

count creates resources indexed by integer (resource[0], [1]…). Removing an item in the middle shifts every later index, causing destroy/recreate churn. for_each keys resources by a stable map/set key, so adding or removing one item only affects that key. Prefer for_each whenever the set can change or items have meaningful identities; reserve count for simple "N identical copies" or conditional (count = var.enabled ? 1 : 0) cases.

Question 6Medium

Your Terraform plan output shows a security group rule will be destroyed and recreated even though you only added a new rule. What causes this, and how do you prevent unnecessary churn?

#
Show answer

This happens when you use a resource "aws_security_group_rule" with count or inline ingress/egress blocks that are order-sensitive. Terraform sees the entire block as an unordered set, but if you use TypeSet with ingress blocks inline, adding a rule in the middle shifts indices. Fix: use separate aws_security_group_rule resources (one per rule) with for_each keyed by a stable value (port+protocol+CIDR), not count. Or use aws_vpc_security_group_ingress_rule / aws_vpc_security_group_egress_rule (AWS provider v4+) which use a separate resource per rule and never cause churn on unrelated rules. Always prefer for_each over count for rule-like resources.

Question 7Hard

You need to split a monolithic Terraform state into two separate states (e.g., network and application). Walk through the complete migration with exact commands.

#
Show answer

Step 1: Create new root modules (terraform/network, terraform/app) and new empty state backends (e.g., separate S3 keys). Step 2: In the monolith directory, use terraform state list to identify resources to move. Step 3: terraform state mv -state-out=../network/terraform.tfstate aws_vpc.main aws_vpc.main — this moves the VPC along with implicit dependencies (subnets, route tables) because Terraform tracks them via references. However, parent-child moves must be explicit; Terraform does not automatically move dependents. You must move each resource individually: terraform state mv aws_subnet.main[0] aws_subnet.main[0]. Step 4: Import moved state into the new backend: in the new module dir, terraform init then terraform state push ../monolith/terraform.tfstate. Step 5: Remove moved resources from the monolith config and state: terraform state rm aws_vpc.main. Step 6: terraform plan in both directories — they should show no changes. Risk: if dependent resources reference moved resources across state files, you need terraform_remote_state data sources, which add latency and potential for stale reads. Test in a clone of prod state first.

Question 8Hard

A terraform apply fails halfway — 10 resources created, then an API rate limit hits and the process is killed. What state is the infrastructure in? Walk through recovery.

#
Show answer

The infrastructure has 10 resources created, but Terraform's state file was never updated (or was partially updated if the process was killed mid-write). Recovery: (1) Run terraform plan — Terraform shows 10 resources it thinks need creating (it doesn't know they exist) and the failed resource as needing creation. (2) Import the 10 orphaned resources: terraform import <resource_type>.<name> <id> for each. (3) Alternatively, use terraform refresh -target=<resource> to pull the 10 resources into state without touching the failed one. (4) Delete the orphaned resources if they're safe to recreate: either via cloud console/CLI or terraform destroy -target=<resource> after importing. (5) Once state is reconciled, terraform apply succeeds. Prevention: always use -auto-approve with caution, set higher max_retries and retry_max_attempts in the provider config, and use a remote backend with state locking so partial state writes don't corrupt the file.

Question 9Hard

How does Terraform resolve provider versions, and what happens when a provider upgrade introduces breaking changes to your resources? Walk through a safe provider upgrade strategy.

#
Show answer

Terraform resolves providers via required_providers blocks, consulting version constraints (e.g. >= 4.0, < 5.0), the lock file (.terraform.lock.hcl), and available provider registries. When upgrading, the lock file pins exact versions by hash. Safe upgrade strategy: (1) Run terraform init -upgrade to update the lock file to latest matching constraint. (2) Review the provider changelog for breaking attributes. (3) Run terraform plan — any ForceNew attributes will show as destroy/recreate; note them. (4) Use -refresh-only first to check for unexpected drift. (5) Apply in a non-production environment first. (6) If the provider changed the internal type of an attribute (e.g. from string to list(string)), use terraform state replace-provider hashicorp/aws hashicorp/aws to migrate state, then use terraform plan to verify. (7) For major version bumps, run both providers side-by-side during migration using provider aliases. Key insight: never run terraform init -upgrade in production without first running the exact same upgrade in a lower environment and verifying zero unexpected changes.

Question 10Hard

Explain the moved block (Terraform 1.1+). When would you use it instead of terraform state mv?

#
Show answer

The moved block lets you declare in HCL that a resource was renamed or moved to a new module path, and Terraform handles the state migration automatically during plan/apply. Example: moved { from = aws_instance.web_old; to = aws_instance.web }. Use it over terraform state mv when: (1) the refactor is permanent and committed to version control — the moved block lives in config so all team members and CI get the migration automatically; (2) you're refactoring a module — moved blocks in the module automatically migrate consumers of that module; (3) you're changing count to for_each — moved { from = aws_subnet.private[0]; to = aws_subnet.private["az1a"] } handles key changes. Keep moved blocks for one release cycle, then remove them after everyone has applied. terraform state mv is better for ad-hoc operations, emergency state fixes, or cross-state moves where the target lives in a different backend.

Question 11Hard

What is the removed block in Terraform 1.7+, and how does it differ from deleting a resource block from config?

#
Show answer

The removed block explicitly tells Terraform to destroy a resource and remove it from state when you apply, but keeps the config visible for documentation. Example: removed { from = aws_s3_bucket.old_bucket; lifecycle { destroy = true } }. Difference from just deleting the config block: if you delete the resource block and run apply, Terraform prompts you to destroy the resource (or you confirm with -target). With removed, you declare intent explicitly — Terraform will destroy it on next apply without needing -target. The lifecycle { destroy = false } variant creates a terraform state rm effect (forget the resource without destroying it). This is useful for: (1) migrating resources to a new state file — remove with destroy = false and import into the new state; (2) explicitly documenting that a resource is being decommissioned; (3) suppressing the destructive plan until you're ready. Unlike simply deleting the block, removed gives you a safer, tracked process visible to your team in the same config.

Question 12Hard

How do Terraform dynamic blocks work, and what are their limitations compared to generating resources with for_each?

#
Show answer

dynamic blocks generate nested configuration blocks inside a single resource, not separate resources. They iterate over a collection and produce block instances. Example: dynamic "tag" { for_each = var.tags; content { key = tag.key; value = tag.value } }. Limitations: (1) Only supports nested blocks that a resource schema defines as TypeList or TypeSet — you cannot use dynamic to create multiple resources. (2) The generated block arguments must all be optional in the schema; required arguments inside a dynamic block will fail if the collection is empty. (3) Debugging is harder — a complex dynamic block produces opaque errors. (4) Cannot use count or for_each inside a dynamic block. (5) for_each on resource creation (resource "x" { for_each = var.items }) is fundamentally different — it creates N separate resources, each with its own state, lifecycle, and ability to be targeted independently. Use dynamic for optional inline rule blocks within a single resource (e.g., security group rules inside one aws_security_group). Use for_each on the resource itself when you need independent lifecycle management for each instance.

Question 13Hard

What are provider-defined functions (Terraform 1.8+), and how do they differ from templatefile, local values, or terraform_data?

#
Show answer

Provider-defined functions are functions exposed by providers (e.g., AWS, GCP) that can be called directly in HCL as provider::namespace::function_name(args). For example, provider::aws::arn_build("s3", var.bucket_name, var.region) to construct an ARN without string interpolation. They differ from: (1) templatefile — renders a file template with variables; it's a built-in function, provider-defined functions go beyond what built-ins can offer, like parsing cloud-specific resource IDs. (2) local values — computed expressions used to reduce repetition; provider functions can be called inside locals but are not a replacement — they add new computational capabilities that previously required external data sources or null_resource with local-exec. (3) terraform_data — a resource used as a container for arbitrary data; provider functions replace many use cases where you needed a terraform_data to call an external script just to compute something provider-specific. The key difference: provider functions are pure computation — they don't create, read, or manage infrastructure state, so they can be used in locals, variables, and outputs without creating additional resources in the state file.

Question 14Hard

What is the Terraform test framework (introduced in 1.6+)? Walk through the structure of a test file and how you would test a module that creates an S3 bucket with versioning.

#
Show answer

Terraform tests use .tftest.hcl files that define run blocks, each running terraform plan and apply against the module with different inputs, then asserting conditions. Structure: a mock_provider or real provider block at the top, then run blocks. Example: run "setup_network" { command = apply; variables = { cidr_block = "10.0.0.0/16" } } followed by assertions: assert { condition = aws_vpc.main.cidr_block == "10.0.0.0/16"; error_message = "CIDR mismatch" }. For a versioned S3 bucket: (1) Create tests/basic.tftest.hcl with a run "create_bucket" block that passes bucket name and enables versioning. (2) Assert the bucket exists and versioning[0].enabled == true. (3) Add a run "update_bucket" block that changes a tag and re-applies, asserting the change applied without recreating. (4) Run terraform test — it creates real resources (unless using mock_provider), runs all assertions, and destroys everything in the correct order. Best practices: use command = plan for validation-only tests (cheap), command = apply for state-dependent assertions (slower). Condition functions like can() and try() help write robust assertions. The framework runs in isolation — state is separate from your working state file.

Question 15Medium

What is the difference between terraform init, terraform plan, and terraform apply in a CI/CD pipeline?

#
Show answer

In CI/CD: (1) terraform init is run once per job to initialize the working directory, download providers, and configure the backend. It should use the lock file (.terraform.lock.hcl) committed to version control for deterministic provider versions. (2) terraform plan is run on pull requests/merge requests to produce a diff artifact (plan file). The plan should be saved and reviewed as part of the PR. (3) terraform apply runs only on the main branch after merge, consuming the exact plan artifact from the plan step — never re-planning. This ensures what was reviewed is exactly what runs. The apply step also requires access to the remote backend (S3/GCS/TFC) for state locking. Additional CI patterns: use -input=false everywhere to prevent blocking on prompts; use terraform validate and terraform fmt -check as pre-merge checks; use terraform show -json on the plan file for programmatic review (e.g., checking for unintended resource destruction).

Question 16Hard

A production terraform apply wants to replace an RDS database because identifier changed. How do you stop data loss and still complete the rename requirement?

#
Show answer

First stop the apply and confirm whether the rename is a provider ForceNew attribute. For an RDS identifier, create a migration plan: snapshot the DB, add lifecycle { prevent_destroy = true }, use a blue/green or replica cutover if downtime matters, update DNS or application endpoints, then intentionally remove the old instance after validation. Terraform should model the safe migration steps, not blindly accept a destroy/create plan.

Question 17Hard

Two engineers run Terraform against the same AWS account and the second run fails with a state lock error. What do you check before using force-unlock?

#
Show answer

Check the backend lock record and CI history to confirm no apply is still running. For S3 backends, inspect the DynamoDB lock item or native lock file if configured; for Terraform Cloud, check the active run. Use force-unlock only when the original process is definitely dead, because unlocking during an active apply can corrupt state and cause duplicate infrastructure changes.

Question 18Hard

A module used count for subnets and removing one subnet from the middle of a list causes Terraform to recreate several others. How do you fix the design without downtime?

#
Show answer

Move from list indexes to stable keys with for_each, such as subnet names or AZ IDs. Use moved blocks or terraform state mv to map aws_subnet.private[0] to aws_subnet.private["app-a"] and so on before changing the resource. Run a plan that shows only the intended deletion; if replacements appear, stop and repair the state mapping.

Question 19Medium

A team stores Terraform state in S3 but sees occasional concurrent applies. What backend controls should be enabled?

#
Show answer

Use a remote backend with locking and versioning. For S3, enable bucket versioning, encryption, strict bucket policy, and state locking using the backend-supported lock mechanism for the Terraform version in use. CI should serialize environment applies and require reviewed saved plans so state locking is the last line of defense, not the only one.

Question 20Hard

Terraform shows drift because an autoscaling group desired capacity changed during a production incident. Should you add ignore_changes?

#
Show answer

Only ignore fields that are intentionally controlled outside Terraform. If the ASG desired capacity is managed by autoscaling policies or incident runbooks, ignore_changes = [desired_capacity] is reasonable while keeping min and max capacity managed. Do not use broad ignore rules to hide real drift such as launch template, subnet, security group, or tag changes.

Question 21Hard

A provider upgrade changes default behavior and the plan shows hundreds of tag diffs. How do you roll out the upgrade safely?

#
Show answer

Pin the current provider, read the upgrade guide, test in a non-production workspace, and separate the provider version bump from functional infrastructure changes. If defaults changed, set explicit arguments or provider default_tags to preserve behavior. Review JSON plan output in CI and merge only when the diff is understood and intentionally accepted.

Question 22Medium

A resource was created manually in AWS and now must be managed by Terraform. What is the safest import workflow?

#
Show answer

Write the matching resource block first, import the real ID with an import block or terraform import, then run terraform plan and adjust arguments until the plan is empty or contains only intentional changes. Never import into a guessed config and immediately apply; that often overwrites production settings.

Question 23Hard

A Terraform module outputs a password generated by random_password. Why is marking the output sensitive = true not enough?

#
Show answer

sensitive = true hides the value in CLI output, but the value still exists in Terraform state. The backend must be encrypted and access-controlled, state access should be limited, and secrets should preferably be written to a secrets manager with only references exposed to downstream modules.

Question 24Hard

A CI pipeline runs terraform plan on pull requests from forks. What security risk does that create?

#
Show answer

Terraform can execute provider code and data sources that may use credentials, and PR code can alter providers, modules, or external data commands. Do not expose cloud credentials to untrusted fork plans. Use read-only speculative plans in isolated accounts, restrict module sources, avoid external data sources for untrusted changes, and require trusted maintainers to run privileged plans.

Question 25Medium

Your plan file was saved in CI but apply fails because variables changed between plan and apply. What should the pipeline do?

#
Show answer

Generate a binary plan with all variables and provider versions fixed, store it as an immutable artifact, and apply exactly that file with terraform apply tfplan. The apply job should not recompute a fresh plan with different environment variables, because the reviewed diff would no longer be the executed diff.

Question 26Hard

A VPC module is used by 20 services and a breaking output rename is needed. How do you release it?

#
Show answer

Use semantic versioning and publish a backwards-compatible version first that exposes both old and new outputs. Migrate consumers gradually, then release a major version removing the old output. Pin module versions in every consumer so one module release does not unexpectedly break all environments.

Question 27Hard

Terraform wants to delete and recreate an IAM role used by live workloads because the role name changed. How do you avoid outage?

#
Show answer

Treat IAM names as stable API contracts. If a rename is mandatory, create the new role in parallel, attach equivalent policies, update workloads to assume or attach the new role, validate, then remove the old role. In Terraform, use separate resources or staged applies; do not let a single plan replace an in-use identity unexpectedly.

Question 28Medium

When should a value be a module input variable versus discovered through a data source?

#
Show answer

Use variables for explicit dependencies and environment decisions that callers own. Use data sources for stable existing infrastructure that Terraform does not manage or that is managed in a separate state. Avoid hidden data-source lookups for critical dependencies because they make plans less predictable and can accidentally bind to the wrong resource.

Question 29Hard

A data.aws_ami lookup always picks the latest image and causes unexpected EC2 replacement. How do you control this?

#
Show answer

Use a tested AMI promotion process instead of resolving latest directly in production. Pin the AMI ID through a variable, SSM parameter, or environment release artifact. Let Terraform consume the promoted value, so instance replacement happens only when the platform team intentionally promotes a new image.

Question 30Hard

A root module has 2,000 resources and plans take 35 minutes. What practical changes improve Terraform performance and operability?

#
Show answer

Split state by ownership and blast radius, such as network, shared data, cluster, and application layers. Reduce expensive data sources, avoid giant module graphs, use provider aliases only where needed, and run plans only for affected stacks in CI. Do not split purely by resource type if teams still need cross-stack coordination for every change.

Question 31Medium

A developer used depends_on between two modules to fix ordering. What is the downside?

#
Show answer

Module-level depends_on forces all resources in one module to depend on all resources in another, making plans conservative and slower and causing unnecessary replacement or unknown values. Prefer passing the exact output needed by the dependent module; that creates a precise dependency edge.

Question 32Hard

An S3 bucket policy references a CloudFront distribution ARN from another state. How should the dependency be wired?

#
Show answer

Prefer explicit remote state outputs or a shared configuration registry such as SSM Parameter Store. The producer state should output only the distribution ID or ARN needed, and the consumer should read that value by environment. Avoid duplicating naming logic in both stacks because it can silently point the policy at the wrong distribution.

Question 33Hard

A terraform destroy in a shared sandbox would delete a shared VPC used by other stacks. How do you design for safer teardown?

#
Show answer

Separate shared infrastructure into its own state and restrict destroy permissions for that state. Add prevent_destroy on critical shared resources, use ownership tags and policy checks, and make application stacks consume shared IDs as inputs rather than owning the shared VPC resources.

Question 34Medium

How do you structure Terraform for dev, staging, and production without copy-pasting entire directories?

#
Show answer

Keep reusable modules for common infrastructure and use thin environment root modules that pass different inputs. Pin module versions, keep backend state separate per environment, and keep production changes gated by reviews. Avoid workspaces as the only isolation boundary for complex environments with different blast radii or approval rules.

Question 35Hard

A Terraform workspace points to the wrong AWS account and the plan wants to create duplicate resources. What controls prevent this?

#
Show answer

Use explicit provider account checks with data.aws_caller_identity and preconditions or validation against the expected account ID. Configure CI credentials per environment, name backend keys clearly, and fail fast when workspace, region, or account does not match the expected values.

Question 36Hard

A resource argument is unknown during plan and causes a module to fail validation. How do you redesign it?

#
Show answer

Avoid requiring apply-time values for plan-time decisions such as for_each keys or provider configuration. Use stable input keys, split the deployment into layers, or output the generated value from one state and consume it in a later run. Terraform needs collection keys known during planning.

Question 37Medium

What is the difference between terraform taint, -replace, and deleting from state?

#
Show answer

-replace=addr asks Terraform to replace a resource in the next plan and is the modern explicit option. taint marks state for replacement but is less preferred for CI workflows. Removing from state only makes Terraform forget the object; it does not destroy it and can lead to duplicate resource creation if the config still exists.

Question 38Hard

An apply failed halfway after creating a load balancer but before updating DNS. What is your recovery flow?

#
Show answer

Do not rerun blindly. Inspect state and cloud resources, run terraform plan to see what Terraform believes is done, and complete or roll back using Terraform where possible. If a resource exists but is missing from state, import it or remove the duplicate before applying again. Then add tests or staged changes for the failure point.

Question 39Hard

A module accepts a list of security group rules. Reordering the list causes rule replacements. How do you avoid noisy and risky diffs?

#
Show answer

Model rules as a map keyed by a stable semantic ID, then use for_each. Each rule key should represent intent, such as ingress_https_from_alb, not its list position. This keeps Terraform from treating a reorder as deletion and recreation of unrelated rules.

Question 40Medium

When should you use lifecycle { create_before_destroy = true }?

#
Show answer

Use it for replaceable resources where the new object can exist alongside the old one, such as launch templates or some target groups. It is not a universal zero-downtime switch; names, quotas, uniqueness constraints, and dependencies may prevent parallel creation. Always verify the plan and naming strategy.

Question 41Hard

A security group rule resource uses create_before_destroy, but replacement fails due to duplicate rule errors. Why?

#
Show answer

Some cloud APIs treat equivalent rules as unique even if Terraform sees them as separate resources. Terraform tries to create the replacement first, but AWS rejects a duplicate. The fix is to avoid unnecessary replacement, use stable keyed rules, or allow destroy-before-create for that specific rule when the brief change is acceptable.

Question 42Hard

A team wants to use Terraform to manage Kubernetes resources immediately after creating an EKS cluster in the same apply. What can go wrong?

#
Show answer

The Kubernetes provider needs cluster endpoint, auth, and API readiness during planning and applying. In one graph, provider configuration may be unknown or the cluster API may not be ready when Kubernetes resources apply. A safer pattern is two stages: create the cluster first, then configure Kubernetes and Helm providers from the stable cluster outputs.

Question 43Medium

How do you prevent accidental public S3 buckets with Terraform?

#
Show answer

Set bucket public access block resources, restrictive bucket policies, encryption, and ownership controls in the module. Add policy-as-code checks in CI for public ACLs and wildcard principals. Use account-level S3 Block Public Access so Terraform mistakes are blocked by AWS as well.

Question 44Hard

A module uses random_id for resource names and every environment gets different names. When is that good and when is it harmful?

#
Show answer

Random suffixes are useful for globally unique names such as S3 buckets or test environments. They are harmful when names are operational contracts used by monitoring, IAM, DNS, or humans. For production, prefer deterministic names with controlled suffixes and only use randomness where the cloud API requires uniqueness.

Question 45Hard

Terraform plan shows an IAM policy JSON diff on every run even though permissions did not change. How do you fix it?

#
Show answer

Generate IAM JSON with aws_iam_policy_document or jsonencode from structured values so key ordering is stable. Avoid heredocs assembled by string concatenation. If AWS normalizes the policy differently, compare the effective document and update the config to match provider normalization.

Question 46Medium

How do you handle provider aliases for deploying resources across multiple AWS regions?

#
Show answer

Define one provider block per region with an alias, then pass the correct provider explicitly into modules using the providers map. Keep region-specific resources in keyed maps so the module knows which provider to use. Avoid relying on the default provider for multi-region stacks because accidental region placement is hard to detect later.

Question 47Hard

An ACM certificate in us-east-1 is needed for CloudFront, but the rest of the stack is in ap-south-1. How should Terraform model this?

#
Show answer

Use an aliased AWS provider for us-east-1 for the ACM certificate and DNS validation resources as needed, while keeping regional infrastructure on the primary provider. Pass the certificate ARN to the CloudFront resource. This avoids creating the certificate in the wrong region, which CloudFront cannot use.

Question 48Hard

A module uses null_resource with local-exec to configure production servers. What risks does this create?

#
Show answer

local-exec runs outside Terraform stateful resource semantics and depends on the runner environment, network access, and command idempotency. It can leak secrets, fail partially, and be hard to roll back. Prefer cloud-init, image baking, SSM documents, Kubernetes jobs, or provider-native resources that expose declarative state.

Question 49Medium

What is a good use case for terraform_data compared with null_resource?

#
Show answer

terraform_data is useful for storing computed values or creating replacement triggers inside Terraform without the external provisioner behavior of null_resource. It can help coordinate lifecycle triggers, but it should not become a replacement for real provider resources or configuration management.

Question 50Hard

A Terraform module must enforce that production RDS has deletion protection enabled. Where do you enforce it?

#
Show answer

Enforce it in multiple layers: module defaults and validation, resource preconditions, CI policy checks, and cloud IAM or SCP controls where possible. Terraform validation gives fast feedback, but cloud-side controls protect against manual changes and misconfigured modules outside the repo.

Question 51Hard

A plan includes known after apply for a value used in a DNS record name. Why is this dangerous?

#
Show answer

DNS record names are public and often part of dependencies. If the name is unknown until apply, reviewers cannot verify the exact endpoint being created and downstream references may fail. Prefer deterministic names from inputs and use apply-time values only for record values such as generated load balancer hostnames.

Question 52Medium

How do you migrate Terraform state from local files to an S3 backend?

#
Show answer

Commit backend configuration without the local state file, initialize with terraform init -migrate-state, and let Terraform copy the state to S3. Then verify versioning, encryption, and locking, remove local state from developer machines, and ensure .tfstate files are ignored by git.

Question 53Hard

A state file accidentally committed to Git contains secrets. What is the incident response?

#
Show answer

Assume compromise. Rotate all exposed credentials, remove the file from the repository history, invalidate any derived tokens, and audit access logs. Moving the state to a secure backend is necessary but not sufficient because Git history may have already exposed the values.

Question 54Hard

A module output exposes a full database connection string. What is a better design?

#
Show answer

Expose non-secret metadata such as endpoint, port, and secret ARN separately. Store credentials in a secrets manager and let applications retrieve them through IAM. If a connection string must be assembled, do it at deploy time in the consuming platform, not as a Terraform output stored in state.

Question 55Medium

How do variable validation blocks improve production safety?

#
Show answer

They fail fast before planning or applying invalid inputs, such as unsupported instance classes, CIDR ranges, or environment names. They are not a substitute for policy-as-code, but they make module contracts explicit and prevent common caller mistakes.

Question 56Hard

A caller passes 0.0.0.0/0 to a database security group module. How should a mature module handle it?

#
Show answer

The module should reject that input with validation or a precondition unless an explicit emergency override is provided and audited. Security-sensitive modules should encode safe defaults and narrow allowed sources. CI policy should also block public database ingress regardless of module behavior.

Question 57Hard

Terraform Cloud speculative plans pass, but applies fail due to missing runtime permissions. How do you diagnose this?

#
Show answer

Compare credentials used for speculative plan and apply, including workspace variables, run tasks, and cloud role assumptions. Plans may need only read permissions while applies need writes. Ensure the apply role has the intended least privilege and that policy checks are not masking provider authentication failures.

Question 58Medium

Why should production Terraform runs avoid developer laptops?

#
Show answer

Laptop runs vary by Terraform version, provider cache, credentials, local environment variables, and network access. CI or Terraform Cloud gives auditable runs, consistent versions, saved plan artifacts, controlled credentials, and review gates. Emergency manual applies should be rare and documented.

Question 59Hard

A provider data source calls an API that rate-limits heavily and makes every plan flaky. What do you change?

#
Show answer

Cache or promote the discovered value into a controlled input such as SSM Parameter Store, remote state output, or release metadata. Reduce repeated data source calls by centralizing lookups in locals. If the value changes independently, create a scheduled update process rather than making every Terraform plan depend on a flaky API.

Question 60Hard

You need to rotate a KMS key used by many encrypted resources. How should Terraform represent the rotation?

#
Show answer

For automatic annual rotation, enable rotation on the existing key if supported. For a new key, create it in parallel, update aliases and resource encryption settings in stages, re-encrypt or recreate dependent resources according to service behavior, then retire the old key only after all consumers and backups no longer need it.

Question 61Medium

What should be included in a Terraform module README for interview-quality production work?

#
Show answer

Inputs, outputs, provider requirements, examples, security assumptions, resource ownership, upgrade notes, known limitations, and migration guidance. The README should state what the module manages and what it intentionally leaves to callers, because unclear ownership creates drift and unsafe changes.

Question 62Hard

A module version upgrade changes a default from private to public subnets. How do you prevent accidental exposure?

#
Show answer

Do not rely on risky defaults. Make sensitive placement explicit with required variables, validate allowed subnet types, and add CI policies that detect public route table associations or public IP assignment. Module upgrades should be reviewed with a plan from every affected environment.

Question 63Hard

Terraform destroys and recreates an EKS node group when changing labels. How do you reduce disruption?

#
Show answer

Check whether the provider marks the field ForceNew. If replacement is required, create a new node group with the desired labels, let workloads drain through PDB-aware rolling migration, then remove the old node group. For mutable settings, prefer managed update mechanisms, but verify real provider behavior before applying.

Question 64Medium

How do you model optional resources in Terraform without creating index errors?

#
Show answer

Use for_each with an empty or single-item map, or expose outputs with try and clear null handling. Avoid scattered resource[0] references that fail when count = 0. Optional modules should have well-defined null outputs and callers should handle the disabled case explicitly.

Question 65Hard

A module has a boolean create_vpc and many conditional resources. When does this become a bad design?

#
Show answer

If the module has many modes, complex conditional outputs, and hidden dependencies, it becomes hard to reason about and test. Split into smaller modules: one to create the VPC and another to consume an existing VPC. Simple feature toggles are fine; whole ownership modes usually deserve separate modules.

Question 66Hard

A Terraform apply updates Route 53 records before the new load balancer is healthy. How do you design a safer cutover?

#
Show answer

Separate provisioning from traffic cutover. Create the new load balancer and target group, validate health checks, then update weighted or failover DNS records gradually. Terraform can manage both stages, but the pipeline should require an explicit approval before shifting production traffic.

Question 67Medium

How does Terraform decide resource order?

#
Show answer

Terraform builds a dependency graph from references, provider dependencies, lifecycle rules, and explicit depends_on. Resources without dependencies can run in parallel. Correctly passing outputs between resources is better than adding broad manual dependencies because it gives Terraform an accurate graph.

Question 68Hard

A resource must be replaced whenever a rendered user-data template changes. What is a robust approach?

#
Show answer

For EC2 instances, put user data in a launch template and let an autoscaling group instance refresh or deployment process replace instances safely. Use hash-based triggers only where the provider lacks native change detection. Avoid directly replacing pets in production without drain and rollback steps.

Question 69Hard

A Terraform run fails because the provider plugin version differs between developers. How do you fix version consistency?

#
Show answer

Commit .terraform.lock.hcl, pin provider constraints deliberately, and run terraform init -upgrade only during planned upgrades. CI should use a fixed Terraform version and the lock file. This ensures everyone gets the same provider checksums and avoids surprise behavior changes.

Question 70Medium

What is the difference between required_version and provider version constraints?

#
Show answer

required_version constrains the Terraform CLI version. required_providers constrains provider plugins such as AWS, AzureRM, or Kubernetes. Both matter because language features, state behavior, and provider schemas can change independently.

Question 71Hard

A new Terraform CLI version changes plan behavior in CI. What rollout process should be used?

#
Show answer

Pin the old version, test the new version in a branch against representative stacks, review release notes, and roll it out environment by environment. Keep provider upgrades separate from CLI upgrades where possible so failures have a clear cause.

Question 72Hard

A module references remote state from production while planning staging. What is the risk?

#
Show answer

It can accidentally couple staging to production IDs, secrets, or endpoints, causing tests to hit real production infrastructure or apply policies to the wrong resources. Remote state keys should be parameterized and validated by environment, and sensitive production outputs should not be broadly readable.

Question 73Medium

How do you handle secrets needed by providers, such as cloud credentials?

#
Show answer

Use short-lived credentials from OIDC or a workload identity system in CI. Avoid static keys in variables or tfvars files. Provider credentials should come from the runner identity or secure workspace variables, and state access should be separated from infrastructure write permissions where possible.

Question 74Hard

A Terraform module manages IAM policies for many teams. How do you prevent privilege escalation through module inputs?

#
Show answer

Do not accept raw arbitrary policy JSON for high-trust roles unless the caller is equally trusted. Offer constrained inputs, validate allowed actions and resources, run policy-as-code checks, and use permission boundaries or SCPs so even a bad module call cannot grant unrestricted admin access.

Question 75Hard

A plan wants to remove a prevent_destroy resource after someone deleted the lifecycle block. How can this be caught?

#
Show answer

Use code review and CI policies that require prevent_destroy for critical resource types such as production databases, KMS keys, and DNS zones. Lifecycle blocks are config, so deleting them removes the guard. Cloud-side deletion protection and IAM deny rules provide stronger independent protection.

Question 76Medium

What is an appropriate use of terraform refresh-only?

#
Show answer

Use it to update state to match real infrastructure without changing resources, typically during drift investigation or after emergency manual changes. Review the refresh-only plan carefully because it can record drift into state, making later plans treat the changed real-world values as the new baseline unless config disagrees.

Question 77Hard

An emergency console change fixed production. How do you bring Terraform back under control?

#
Show answer

Document the change, run a plan or refresh-only plan to understand drift, then decide whether Terraform config should adopt the change or revert it. Update code and tests, import any new objects if needed, and apply from CI. The goal is to make the emergency change intentional in version control.

Question 78Hard

Terraform is used to manage DNS records across many microservices. How do you avoid teams overwriting each other?

#
Show answer

Give each service ownership of only its record names, or centralize DNS in a platform module with clear inputs. Use separate states by zone or service, enforce naming conventions, and avoid broad aws_route53_record resources generated from shared mutable maps unless ownership and review are strict.

Question 79Medium

How should .tfvars files be handled in a repository?

#
Show answer

Non-secret environment values can be committed if they are reviewed configuration. Secret tfvars should not be committed; use secure workspace variables or a secrets manager. Keep examples such as example.tfvars to document required inputs without exposing real credentials.

Question 80Hard

A module depends on an external service account existing before apply. Should Terraform create it or read it?

#
Show answer

That depends on ownership. If the platform team owns the service account lifecycle, Terraform should create and output it. If another team owns it, read it through a controlled input or data source and validate it exists. Avoid a module that sometimes owns and sometimes borrows the same identity without clear mode separation.

Question 81Hard

A Terraform apply changes an ALB listener rule priority and causes routing conflicts. How do you manage listener rules safely?

#
Show answer

Use deterministic priority assignment, validate uniqueness, and avoid deriving priorities from unstable list indexes. For large shared ALBs, centralize listener rule ownership or allocate priority ranges per service. Plans should clearly show old and new routing behavior before apply.

Question 82Medium

What is the problem with using timestamps in resource names or triggers?

#
Show answer

Timestamps change on every plan or apply, causing perpetual diffs and unnecessary replacement. Use content hashes for real change detection or stable release versions for intentional rollouts. Terraform configuration should be deterministic wherever possible.

Question 83Hard

A Docker image tag latest is passed into Terraform for ECS task definitions. Why is this a production problem?

#
Show answer

Terraform cannot know when the image behind latest changes, and rollbacks are ambiguous. Use immutable image digests or versioned tags produced by CI. Terraform should deploy a specific artifact, so the plan represents a reproducible release.

Question 84Hard

An ECS service update through Terraform causes all tasks to restart at once. What controls should be checked?

#
Show answer

Review deployment configuration such as minimum healthy percent and maximum percent, health check grace period, load balancer health checks, capacity, and task definition changes. Terraform submits the desired service update, but ECS controls rollout behavior. Set safe deployment parameters and verify enough capacity exists before applying.

Question 85Medium

How do you avoid circular dependencies between security groups?

#
Show answer

Create security groups first, then create rules as separate resources that reference both group IDs. Inline rules can create cycles or force replacement in complex graphs. Separate rule resources also make ownership and diffs clearer.

Question 86Hard

A state split is needed because one stack became too large. How do you migrate safely?

#
Show answer

Create the new root module and backend, move selected resources with terraform state mv or equivalent moved/import workflow, and verify both old and new plans are clean. Do not recreate resources. Migrate in small batches, back up state first, and coordinate locks so no one applies during the split.

Question 87Hard

A state backend bucket is accidentally deleted. What recovery options exist?

#
Show answer

If bucket versioning and backups exist, restore the latest valid state object and lock metadata. If not, rebuild state by importing existing infrastructure into matching config, starting with critical shared resources. This is why remote state needs versioning, retention, backups, and restricted delete permissions.

Question 88Medium

What are moved blocks and when are they better than terraform state mv?

#
Show answer

moved blocks declare address changes in code so Terraform can migrate state during plan for everyone consistently. They are better for reviewed refactors that should travel with the module. terraform state mv is still useful for one-off emergency or cross-state migrations.

Question 89Hard

A resource address changes because a module was renamed. What happens without a moved block?

#
Show answer

Terraform treats the old address as removed and the new address as a separate desired resource, so the plan may destroy and recreate infrastructure. A moved block maps the old module address to the new one and preserves the real object in state.

Question 90Hard

How do you test Terraform modules before production?

#
Show answer

Use static checks (terraform fmt, validate, linting), policy checks, example plans, and ephemeral integration tests in a sandbox account for critical modules. Validate outputs and important resource attributes. For modules managing risky resources, test upgrade paths and replacement behavior, not just initial creation.

Question 91Medium

What should a good Terraform pull request include?

#
Show answer

It should include the code change, the relevant plan output or link, explanation of replacements and destroys, blast radius, rollback notes, and any required manual steps. Reviewers should be able to tell what real infrastructure will change without running Terraform themselves.

Question 92Hard

A plan shows -/+ replacement for a production load balancer. What questions should you answer before approval?

#
Show answer

Why is replacement required, can the new load balancer exist in parallel, how will DNS or clients cut over, are certificates and security groups ready, what is rollback, and what downtime is expected? If those answers are not clear, split the change into provision, validate, cutover, and cleanup stages.

Question 93Hard

A Terraform module provisions both network and application resources. Why might that be bad?

#
Show answer

Network and application resources usually have different owners, lifecycles, blast radius, and approval requirements. Combining them means a routine app change can accidentally affect shared networking. Separate stacks let network changes be rare and controlled while application deployments stay fast.

Question 94Medium

When is a monorepo for Terraform helpful, and when is it painful?

#
Show answer

A monorepo helps standardize modules, policies, and review workflows across environments. It becomes painful if every change triggers plans for every stack, ownership is unclear, or state boundaries are too broad. Use path-based CI and clear CODEOWNERS to keep it manageable.

Question 95Hard

A provider bug creates bad state for one resource. How do you proceed?

#
Show answer

Back up state, read provider issues and upgrade notes, test a provider upgrade, and use state surgery only as a last resort. If editing state is unavoidable, do it with locks held, minimal changes, peer review, and a clean plan afterward. Prefer import or provider-supported fixes where possible.

Question 96Hard

A cloud resource was deleted manually but still exists in Terraform state. What will the next plan show?

#
Show answer

After refresh, Terraform should detect the object is gone and plan to recreate it if the config still declares it. If recreation is unsafe, remove or modify the config first. If the deletion was intentional, remove it from config and state through a reviewed change.

Question 97Medium

How should Terraform handle generated files such as rendered Helm values?

#
Show answer

Prefer generating values in memory with templatefile, yamlencode, or structured inputs rather than committing generated artifacts. If generated files are needed for review, ensure they are deterministic and produced by CI. Avoid local files that differ between developer machines.

Question 98Hard

A Helm release managed by Terraform fails and leaves Kubernetes resources partially updated. What is the recovery approach?

#
Show answer

Inspect Helm release status, Kubernetes events, and Terraform state. Fix the chart values or cluster condition, then rerun the plan. If the release is stuck, use Helm-native rollback or uninstall carefully, then reconcile Terraform state. For critical apps, consider GitOps controllers for app rollout and Terraform only for cluster prerequisites.

Question 99Hard

Terraform manages both a database and the application schema migration job. Why is this risky?

#
Show answer

Terraform is infrastructure orchestration, not an application deployment transaction manager. Schema migrations need ordering, rollback, retries, and app version coordination. Terraform can provision the database and permissions, but migrations are usually safer in a deployment pipeline or migration tool with explicit operational controls.

Question 100Medium

What is the difference between module composition and deeply nested modules?

#
Show answer

Composition keeps root modules wiring small focused modules together with visible inputs and outputs. Deep nesting hides dependencies and makes changes hard to reason about. Prefer shallow composition so environment owners can see the infrastructure graph and override important settings deliberately.

Question 101Hard

A cost spike happens after Terraform creates NAT gateways in every AZ. How should this be reviewed?

#
Show answer

Check whether high availability required one NAT gateway per AZ or whether a lower-cost non-production design is acceptable. Terraform modules should expose cost-impacting choices clearly and use environment-specific defaults. Add cost estimation or policy checks in CI for expensive resources.

Question 102Hard

A module creates CloudWatch alarms but alert thresholds differ by service. How should inputs be designed?

#
Show answer

Provide sensible defaults and allow explicit per-service threshold maps with validation. Avoid hardcoding thresholds in the module or accepting an unstructured blob that bypasses validation. Outputs should make alarm names and ARNs visible to incident tooling.

Question 103Medium

How do you use tags effectively in Terraform-managed infrastructure?

#
Show answer

Set common tags at the provider or module level and require ownership, environment, cost center, and data classification tags. Avoid tag drift by centralizing defaults, but allow resource-specific tags where needed. Use policy checks to block missing mandatory tags.

Question 104Hard

A provider-level default_tags change updates thousands of resources. How do you roll it out?

#
Show answer

Treat it as a broad infrastructure change. Plan by environment, check which resources support tag updates in place versus replacement, and avoid mixing tag rollout with functional changes. If many APIs are touched, apply during a low-risk window and monitor rate limits and service-specific behavior.

Question 105Hard

Terraform wants to recreate a KMS key because its description changed. What should you suspect?

#
Show answer

A description alone normally should not require key replacement, so suspect an address change, provider schema issue, changed key spec, multi-region setting, or imported state mismatch. Inspect the exact ForceNew attribute in the plan JSON and provider docs before approving any KMS replacement.

Question 106Medium

Why should backend configuration usually not depend on Terraform variables?

#
Show answer

Backend initialization happens before normal Terraform evaluation, so standard variables are not available in the usual way. Use partial backend configuration with CI-provided backend config files or flags. Keep backend keys explicit and predictable to avoid writing state to the wrong location.

Question 107Hard

A CI job initializes the wrong backend key for production. How can this be prevented?

#
Show answer

Make backend config derived from trusted pipeline metadata, not user-edited PR files, and validate account, region, and workspace before planning. Use separate credentials and protected branches for production. A plan should fail if the backend key or caller identity does not match the environment.

Question 108Hard

A service team wants direct write access to the production Terraform state bucket. What is the concern?

#
Show answer

State write access is equivalent to control over Terraform ownership and may expose secrets. Teams should trigger controlled runs through CI or Terraform Cloud, not edit state directly. Grant least-privilege read only when needed, and separate state admin permissions from infrastructure authoring permissions.

Question 109Medium

How do you handle Terraform outputs consumed by non-Terraform systems?

#
Show answer

Publish stable outputs to a controlled registry such as SSM Parameter Store, Secrets Manager, DNS, or a service catalog. Directly reading state from scripts couples external systems to Terraform internals and may expose secrets. Outputs should have clear compatibility expectations.

Question 110Hard

An apply creates a resource but times out waiting for readiness. The next plan wants to create it again. What do you do?

#
Show answer

Check whether the resource exists in the provider and whether it was recorded in state. If it exists but is missing from state, import it before applying again. Then tune timeouts or readiness dependencies if the API is slow. Reapplying blindly may create duplicates or fail on name conflicts.

Question 111Hard

A Terraform run is blocked by API throttling in a large AWS account. What mitigations are available?

#
Show answer

Reduce unnecessary parallelism, split state by ownership, remove repeated data sources, use provider retry settings where available, and avoid broad account-wide lookups. Schedule large applies away from other automation and consider service quota increases if the workload is legitimate.

Question 112Medium

When should you lower Terraform -parallelism?

#
Show answer

Lower it when provider APIs throttle, dependencies are fragile, or a service cannot handle many concurrent changes. It can make applies slower but safer. Do not use it to hide bad dependency modeling; fix missing dependencies where order actually matters.

Question 113Hard

A module configures backup retention for databases. What production safeguards should it include?

#
Show answer

Require minimum retention for production, enable deletion protection where supported, configure final snapshots, tag backups, and expose restore-related outputs. Use validation and policy checks so a caller cannot accidentally set retention to zero in a protected environment.

Question 114Hard

A resource must be adopted from another Terraform state. How do you avoid duplicate ownership?

#
Show answer

Coordinate a state handoff: remove or move the resource from the old state and import or move it into the new state while both states are locked and no applies are running. Verify the old state no longer plans changes for it and the new state has a clean plan. Two states must never manage the same object.

Question 115Medium

What is the danger of using the same module source branch for production?

#
Show answer

A branch is mutable, so production can get different module code without an explicit version change. Use immutable tags or registry versions. Branch sources are acceptable for development testing but not for stable production dependencies.

Question 116HardTerraform replacement & change governance

A routine Terraform plan unexpectedly proposes replacing a production load balancer and database. What do you inspect before any apply, and how do you distinguish drift, address refactoring and an immutable-field change?

#

A platform PR updates a module and provider constraint. The CI plan now includes -/+ for a critical database and load balancer, even though the ticket only requested tags. A teammate suggests applying with -target to save time.

Show answer

Triage: Block production apply and preserve the plan and provider lockfile securely. Confirm the correct workspace, remote backend, state lineage, variable files and credentials. Inspect the resource address, the -/+ cause, any 'forces replacement' attributes, provider schema or version changes, lifecycle rules, taint or explicit -replace arguments, for_each keys and module renames. Compare with previous known-good plans and audit cloud-side changes. A rename or move may need a declarative moved block; a changed immutable property may truly require replacement; a drifted object may need a deliberate reconciliation decision.

Containment: Do not approve replacement simply because CI ran successfully. For irreplaceable or stateful resources, consider an appropriate prevent_destroy safeguard and a staged, reviewed change plan. Use terraform plan and terraform show -json on a protected CI runner with a saved, access-controlled plan file; the JSON and plan can include sensitive values. Use moved blocks or controlled state migration only when the same real object should retain ownership. Never hand-edit state or suppress broad fields with ignore_changes to make a scary plan disappear. -target is an exceptional recovery option, not a shortcut to bypass review.

Prevention: Pin and review provider versions, require human approval for destroys/replacements, validate policy-as-code gates, back up and protect state, add module/upgrade tests and staged non-prod plans. If replacement is required, specify data backups, service migration, restore tests, cutover and rollback before scheduling the change. Success means the plan matches an explicitly approved change, not that Terraform printed green.

Trade-offs

prevent_destroy reduces accident risk but can block legitimate migrations; moved blocks preserve tracked identities only when the remote object truly stays the same.

Common mistake

Applying with -target or removing state entries to 'fix' a forced replacement without understanding ownership and data-loss impact.

Follow-up

The diff shows only a module address change and the remote object ID is unchanged. What evidence supports a moved block rather than a new object?

Read-only plan review in a protected workspace · shell
terraform workspace show
terraform version
terraform plan -out=review.tfplan
terraform show -json review.tfplan  # treat plan output as sensitive
Review before any destructive infrastructure action
  1. Pause approval and identify environment/state
  2. Inspect replacement reason and provider drift
  3. Classify address move vs mutable vs immutable change
  4. Plan safe migration, backup and approvals
  5. Re-plan and verify intent before apply

Check your reasoning

  • Explain the difference between -/+, moved blocks and -replace.
  • Name two risks of copying a Terraform plan file outside controlled CI.
  • Explain when prevent_destroy is useful and when it is insufficient.
Question 117MediumState

DynamoDB locking is deprecated for the S3 backend. How do you migrate safely?

#

Twelve pipelines and several engineers share one S3 backend that locks with a DynamoDB table.

Show answer

Terraform 1.10 added S3-native locking (use_lockfile = true) and 1.11 deprecated the DynamoDB arguments. The lock is a .tflock object next to the state file.

Migrate in two steps. First upgrade every runner to a version that supports lockfiles, then configure both use_lockfile and dynamodb_table; Terraform must then acquire both locks, so old and new runners cannot collide. Grant the role permission to put and delete the lock object, and run terraform init -reconfigure. Once no runner relies on DynamoDB, remove the table argument and later the table.

Trade-offs

Native locking removes a table to manage, but the lock now depends on S3 permissions and bucket policies being right.

Common mistake

Switching some pipelines to lockfile-only while others still lock only in DynamoDB, so two applies can run at once.

Follow-up

How would you detect a runner still using an old Terraform version before removing DynamoDB?

Transitional backend configuration · hcl
terraform {
  backend "s3" {
    bucket         = "acme-tf-state"
    key            = "network/terraform.tfstate"
    region         = "ap-south-1"
    use_lockfile   = true
    dynamodb_table = "tf-locks" # remove once every runner uses the lockfile
  }
}
Question 118MediumSecurity

A database password keeps ending up in Terraform state. Which modern features help?

#

The state bucket is encrypted, but the security review still flags plaintext passwords in state and plan files.

Show answer

Ephemeral values exist only during a run: ephemeral resources can fetch a secret from a secret manager, and Terraform does not write it to plan or state. Write-only arguments let you send such a value to a provider without storing it; providers usually pair them with a version argument so you can trigger a rotation.

Better still, let the service own the secret where possible, for example a managed master password stored in a secret manager. Keep state encrypted and access-controlled anyway, because state still holds other sensitive data such as connection details.

Trade-offs

Write-only values cannot be compared on later plans, so changes must be signalled explicitly through the version argument.

Common mistake

Marking a value sensitive = true and believing it is no longer stored; it only hides output.

Follow-up

How would you rotate a write-only password without causing a full resource replacement?

Question 119MediumTooling

Terraform or OpenTofu for a new platform team — how would you decide?

#

Leadership asks whether the licence change affects you and whether to switch.

Show answer

In 2023 HashiCorp moved Terraform from the MPL to the Business Source License. OpenTofu was forked from the last open-source version and is run under the Linux Foundation with an open-source licence. For most companies using Terraform internally, the licence does not block use; it matters mainly if you build a product that competes with HashiCorp. Check with your legal team.

Technically the two started compatible and have diverged: OpenTofu added features such as client-side state and plan encryption, while Terraform has its own new features and HCP integrations. Decide on the features you need, provider and module compatibility, support options and your CI tooling, then pin one tool per repository.

Trade-offs

Staying on Terraform keeps vendor support and HCP features; OpenTofu keeps an open licence and community governance.

Common mistake

Mixing both tools on the same state files without checking compatibility.

Follow-up

How would you test a migration of one state from Terraform to OpenTofu?

Question 120HardAutomation

How would you let AI coding agents write Terraform without risking production?

#

Engineers use agents to draft infrastructure changes and want them to open pull requests on their own.

Show answer

Give the agent no apply rights. It can edit code and run terraform fmt, validate and plan with read-only credentials in a sandbox or against production in plan-only mode. Apply happens only through the normal pipeline after review.

Check the plan, not just the code: export it with terraform show -json and run policy checks on it, for example blocking destroys of databases, public exposure or IAM wildcards. Keep states small so a bad change has limited reach, pin providers with the lock file, and require a human to read the plan summary for anything that deletes or replaces resources.

Trade-offs

Strict gates slow agents down, but plans are the only reliable view of what code will actually do.

Common mistake

Giving an agent the same credentials as the deploy pipeline.

Follow-up

Which three plan-level policies would you enforce first?

Question 121MediumState

You must bring 300 hand-made S3 buckets under Terraform. How do you do it without writing 300 import commands or 300 resource blocks by hand?

#

Buckets were created in the console over five years. An audit wants them managed in code with no downtime and no accidental changes.

Show answer

Use import blocks instead of the terraform import command. An import block, added in Terraform 1.5, declares that Terraform should adopt an existing object at a given address. Because it lives in configuration, the import shows up in terraform plan, goes through code review, and runs in your normal pipeline instead of on someone's laptop. Since 1.7 an import block can use for_each, so one block can adopt a whole map of buckets.

For the resource code itself, terraform plan -generate-config-out=generated.tf writes HCL for imported resources that have no configuration yet. The docs still mark config generation as experimental, so treat its output as a first draft: clean it up, move shared settings into a module, and remove noisy defaults.

The safety rule is that the first plan after import must show only imports and no changes. Any diff means your code does not match reality; fix the code until the plan is clean, then apply. Do it in batches (for example 30 buckets per pull request) so a mistake affects a small set.

Trade-offs

Declarative imports are reviewable and repeatable, but generated configuration needs cleanup and the first applies must be watched closely.

Common mistake

Applying an import plan that also shows updates, so adopting the buckets silently changes their settings.

Follow-up

How would you handle bucket policies, lifecycle rules and other sub-resources that the AWS provider models as separate resources?

Adopt many buckets with one import block (Terraform 1.7+) · hcl
variable "legacy_buckets" {
  type = map(string) # key => bucket name
}

import {
  for_each = var.legacy_buckets
  to       = aws_s3_bucket.legacy[each.key]
  id       = each.value
}

resource "aws_s3_bucket" "legacy" {
  for_each = var.legacy_buckets
  bucket   = each.value
}
Question 122MediumValidation

Where should an assertion live: variable validation, a precondition, a postcondition, or a check block?

#

A reviewer asks for four rules: the environment name must be valid, the chosen AMI must be from the approved owner, the created load balancer must be internal, and the public endpoint should answer with HTTP 200.

Show answer

Each mechanism runs at a different time and has a different effect.

Variable validation checks inputs before anything else, so it fits rules about values the caller passes in, such as a valid environment name. Preconditions (Terraform 1.2+) sit in a resource's lifecycle and check assumptions before Terraform acts on that resource, such as the AMI owner returned by a data source. Postconditions check the result after the object is created or read; the docs say a failed postcondition halts processing and prevents downstream actions that rely on the object, but does not undo what was already done. That fits "the load balancer must be internal".

Check blocks are different: when an assertion fails, Terraform reports a warning and continues. They suit things that are not the configuration's fault and should not block a deploy, like an endpoint health check. A check can contain a scoped data source that only it can reference, and HCP Terraform can run checks continuously as health checks.

Rule of thumb: block on what the configuration controls, warn on what the world controls.

Trade-offs

Blocking conditions stop bad changes early but can block urgent deploys; warning-only checks never block, so someone has to act on them.

Common mistake

Using a check block for a security rule and assuming it will stop the apply.

Follow-up

How would you alert on failed check blocks from scheduled runs?

Precondition on an input, postcondition on the result · hcl
resource "aws_lb" "app" {
  internal = var.internal
  # ...
  lifecycle {
    precondition {
      condition     = data.aws_ami.app.owner_id == var.approved_ami_owner
      error_message = "The AMI must come from the approved owner account."
    }
    postcondition {
      condition     = self.internal
      error_message = "This load balancer must be internal."
    }
  }
}
Question 123MediumValidation

How would you use a check block to catch problems that happen outside Terraform, such as a failing health endpoint, without blocking deploys?

#

An outage happened because a manually managed dependency went unhealthy. Infrastructure code was fine, but nobody noticed until users did.

Show answer

A check block holds one or more assert conditions and, optionally, a nested data source that only that check can reference. When an assertion fails, Terraform reports a warning and keeps going, so the check never blocks a plan or apply. That makes it a good fit for facts about the outside world: an API's health endpoint, whether a dependency exists, whether something drifted.

Write the check against what users depend on, for example an HTTP data source that calls the health URL and asserts on the status code. Every plan in CI now prints a warning when it fails. On HCP Terraform you can enable health checks on a workspace so checks run continuously, which turns this into scheduled monitoring for infrastructure assumptions.

Keep checks cheap and read-only, because they run on every plan, and do not let them replace real monitoring. They are best for assumptions your Terraform code makes that a dashboard would not show.

Trade-offs

Checks give early warnings in the same place engineers look at plans, but warnings are easy to ignore unless something alerts on them.

Common mistake

Putting slow or rate-limited API calls in check blocks, which makes every plan slower and flakier.

Follow-up

Which of your Terraform assumptions would you turn into checks first?

Warn on every plan if the public endpoint is unhealthy · hcl
check "api_health" {
  data "http" "health" {
    url = "https://api.example.com/healthz"
  }

  assert {
    condition     = data.http.health.status_code == 200
    error_message = "api.example.com/healthz did not return HTTP 200."
  }
}
Question 124MediumLifecycle

Instances must be replaced whenever the app version changes, but the version is a variable. Why does replace_triggered_by reject it, and what do you do?

#

An ASG-less fleet of instances bakes the app at boot. The team wants a new version to force replacement, and tried replace_triggered_by = [var.app_version].

Show answer

replace_triggered_by, added in Terraform 1.2, replaces a resource when a referenced managed resource, or one of its attributes, has a planned change. The lifecycle docs say you can only reference managed resources there; plain values such as input variables and locals have no planned actions of their own, so there is nothing to trigger on.

The standard pattern is to wrap the value in a terraform_data resource. Its input stores the version, so changing the variable plans an update to terraform_data, and that planned change triggers the replacement of the instances.

Before using this, ask whether replacement is what you want. For fleets, a launch template change plus an instance refresh in an Auto Scaling group gives rolling replacement with health checks, which a single Terraform apply does not. Reserve replace_triggered_by for cases where the dependency is real but invisible to Terraform, and pair it with create_before_destroy if downtime matters.

Trade-offs

Forced replacement makes hidden dependencies explicit, but replacing instances in one apply is blunter than a rolling update.

Common mistake

Triggering replacement from an attribute that changes on every apply, so the resource is recreated every run.

Follow-up

How would you make the replacement roll one instance at a time?

Trigger replacement from a variable through terraform_data · hcl
resource "terraform_data" "app_version" {
  input = var.app_version
}

resource "aws_instance" "app" {
  # ...
  lifecycle {
    replace_triggered_by = [terraform_data.app_version]
  }
}
Question 125EasyTooling

terraform init works on a Mac but fails in Linux CI with a provider checksum error after a lock file update. Why?

#

A developer on an Apple Silicon laptop ran terraform init -upgrade and committed the new .terraform.lock.hcl. The CI runner is linux_amd64.

Show answer

The dependency lock file records checksums for the provider packages Terraform installed. When the developer upgraded on a Mac, the lock file recorded hashes for the darwin_arm64 package only. In CI, Terraform downloads the linux_amd64 package, and its checksum does not match anything recorded for that provider version, so init fails with a checksum error.

The fix is to record hashes for every platform you use when you update the lock file: terraform providers lock with one -platform option per target system. The docs describe exactly this: pre-populate hashes for all the platforms you intend to use.

Make it routine: provider upgrades happen in their own pull request, generated by a script or bot that runs providers lock for all platforms, and CI runs terraform init without -upgrade so it never changes the lock file on its own.

Trade-offs

Multi-platform hashes cost a slower lock step but remove a whole class of "works on my machine" failures.

Common mistake

Deleting the lock file to make CI pass, which throws away version pinning and supply-chain checks.

Follow-up

How would you stop CI from ever modifying the lock file?

Record hashes for every platform you run on · shell
terraform providers lock \
  -platform=linux_amd64 \
  -platform=darwin_arm64 \
  -platform=windows_amd64
Question 126MediumArchitecture

Your team deploys the same network, cluster and app layers to 15 environments with wrapper scripts. Would you move to Terraform Stacks?

#

Each layer is a separate workspace. A bash script runs them in order per environment and passes outputs along. Adding a Region means editing the script and creating more workspaces.

Show answer

Terraform Stacks, now generally available in HCP Terraform, describe infrastructure as components and deployments. Components (in .tfcomponent.hcl files) are the layers, each built from a module, with the wiring between them declared instead of scripted. Deployments (in .tfdeploy.hcl files) are the copies of the whole stack, such as one per environment or Region, each with its own inputs. HCP Terraform then plans and applies the components in dependency order for each deployment.

That matches this problem well: the ordering and output passing in the script become configuration, and adding a Region becomes adding a deployment. Check the limits against your design: the docs state up to 100 components per stack and a maximum of 20 deployments per stack today, so 15 environments fit but leave limited room.

I would not move if the team does not use HCP Terraform, since Stacks run there, or if the layers have very different owners and release cadences, where separate workspaces with clear contracts are still simpler. Pilot one stack for one product before migrating everything.

Trade-offs

Stacks remove orchestration glue and repeated workspaces, but tie you to HCP Terraform and to the current component and deployment limits.

Common mistake

Packing unrelated teams' infrastructure into one stack, so one team's change waits on another's plan.

Follow-up

How would you split ownership between the platform team and app teams in a stack?

Question 127MediumModules

A module input is only valid in combination with another input. How do you validate that, and since when is it possible?

#

A database module takes environment and multi_az. Production must be multi-AZ, but a caller passed environment = "prod" and multi_az = false.

Show answer

Before Terraform 1.9, a validation block could refer only to the variable it belonged to, so cross-field rules had to be preconditions on some resource or a messy workaround. Since 1.9, validation conditions can refer to other input variables and to other objects such as data resources.

So put the rule on the variable it constrains: a validation on multi_az that fails when environment is prod and multi_az is false. The error appears at plan time with a clear message, before anything is created, and it lives next to the input in the module's interface where callers will see it.

Two cautions. A module that uses this needs required_version = ">= 1.9", otherwise older CLIs fail with a confusing error. And keep rules about policy that differs by organization (allowed regions, instance families) in a central policy layer rather than in every module, so changing a policy does not mean releasing every module.

Trade-offs

Validating at the interface gives early, clear errors, but rules baked into modules are harder to change than central policy.

Common mistake

Writing the rule as a postcondition, so the plan passes and the failure appears only after resources exist.

Follow-up

Which rules would you put in module validation versus a policy engine run on the plan?

Validation that reads another variable (Terraform 1.9+) · hcl
variable "environment" {
  type = string
}

variable "multi_az" {
  type = bool

  validation {
    condition     = var.environment != "prod" || var.multi_az
    error_message = "Production databases must set multi_az = true."
  }
}
Question 128HardSecurity

Your organization uses OpenTofu. How would you encrypt existing state and plan files, and what can go badly wrong?

#

State in an S3 bucket contains database passwords and private keys. Bucket encryption exists, but anyone with read access to the bucket can still read state.

Show answer

OpenTofu 1.7 added client-side encryption for state and plan files, for local storage and remote backends. You configure a key provider (passphrase-based pbkdf2, or a KMS such as AWS KMS, GCP KMS or OpenBao) and a method; AES-GCM is the only supported encryption method. Data is encrypted before it reaches the backend, so bucket read access alone no longer exposes secrets.

Migrating existing state follows the documented sequence. Add an unencrypted method and list it as the fallback, so OpenTofu can still read the old plaintext state while writing encrypted state. Run tofu apply so the state is rewritten encrypted. Then remove the fallback and consider the enforced option so unencrypted state can never be written again.

The big risk is losing the key. The docs are blunt: once encryption is on, OpenTofu cannot read the state without the correct key. Back up keys, restrict who can delete the KMS key, and test a restore. Also remember encryption does not shrink who can run plans: anyone allowed to decrypt still sees the secrets, so keep secrets out of state where you can.

Trade-offs

Client-side encryption narrows who can read secrets in state, but makes the key a hard dependency for every plan, apply and restore.

Common mistake

Enabling encryption with a passphrase kept only in one engineer's shell history, so the state is unreadable when they leave.

Follow-up

How would you rotate the encryption key without a window where state is unreadable?

Migration phase: encrypt with KMS, still read old plaintext · hcl
terraform {
  encryption {
    key_provider "aws_kms" "state" {
      kms_key_id = "a4f791e1-0d46-4c8e-b489-917e0bec05ef"
      region     = "eu-west-1"
      key_spec   = "AES_256"
    }
    method "aes_gcm" "state" {
      keys = key_provider.aws_kms.state
    }
    method "unencrypted" "migrate" {}

    state {
      method = method.aes_gcm.state
      fallback {
        method = method.unencrypted.migrate
      }
    }
  }
}
Question 129MediumTooling

Terraform 1.14 added actions and list resources with terraform query. What problems do they target, and how would you adopt them carefully?

#

Your team uses local-exec provisioners to invalidate a CDN cache after deploys, and spreadsheets to find unmanaged resources before imports.

Show answer

Terraform 1.14.0 (November 2025) introduced two features. Actions are provider-defined operations meant to codify use cases outside the normal create, read, update and delete model, such as invalidating a cache or triggering a job, which teams previously faked with local-exec or null_resource. List resources, defined in *.tfquery.hcl files, let you query existing infrastructure, and terraform query runs those list operations and shows the results, which is useful for finding objects to import.

Both depend on provider support: an action or list resource exists only if the provider implements it, so check your provider versions before planning around them.

Adopt them like any new language feature. Pin required_version so older CLIs fail clearly, try them in a non-production workspace first, and replace one provisioner at a time while keeping the old path until the new one has run cleanly through several releases. For queries, treat the output as input to reviewed import blocks, not as something applied automatically.

Trade-offs

Provider-native actions are more predictable than shell provisioners, but they are new and coverage differs by provider.

Common mistake

Rewriting every provisioner at once on a new CLI version that half the team and CI do not run yet.

Follow-up

Which of your local-exec provisioners would you replace first, and why?

Question 130MediumOperations

How would you build scheduled drift detection for 200 Terraform root modules without anyone reading plan output?

#

Console changes keep surprising the team weeks later, when an unrelated pull request shows a big diff.

Show answer

Run a read-only plan on a schedule and use -detailed-exitcode. With it, terraform plan exits 0 when there are no changes, 1 on error, and 2 when it succeeded and changes are present. A nightly job can loop over root modules and turn exit code 2 into an alert or a ticket with the plan attached, and exit code 1 into a separate "the plan itself is broken" alert, which matters just as much.

Details that make it work. Use a role with read-only cloud permissions, so the drift job can never apply. Use a full refresh; skipping refresh defeats the purpose. Run modules in parallel with limits so you do not hit API rate limits. Route each alert to the module's owning team, using a CODEOWNERS-style mapping, and include the changed resource addresses so the owner can decide quickly: revert the console change with an apply, or adopt it into code.

Track drift count per module over time. Repeat offenders usually point to a missing self-service path that people work around in the console.

Trade-offs

Scheduled plans catch drift early but cost API calls and need ownership routing, or alerts are ignored.

Common mistake

Treating exit code 1 as "no drift", so broken modules look healthy for months.

Follow-up

When is it safe to auto-apply to fix drift, and when must a human decide?

Turn plan results into alerts · shell
terraform plan -detailed-exitcode -input=false -lock=false -out=drift.tfplan
case $? in
  0) echo "no drift" ;;
  2) echo "drift detected"; terraform show -no-color drift.tfplan > drift.txt ;;
  *) echo "plan failed"; exit 1 ;;
esac
Question 131MediumPerformance

Plans take 20 minutes, and someone proposes always running with -refresh=false. What is the risk, and what would you do instead?

#

A large root module spends most of its plan time refreshing thousands of resources against the cloud API.

Show answer

Refresh compares state with the real infrastructure. With -refresh=false, the plan docs say Terraform ignores external changes, which could result in an incomplete or incorrect plan. A plan built on stale state can miss drift, propose changes that conflict with reality, or overwrite a manual emergency fix without showing it.

Using it occasionally is reasonable: when you know nothing changed outside Terraform and you need a quick look during development, or when an API outage makes refresh impossible and you accept the risk knowingly. Using it always, especially for applies in production, removes Terraform's main safety check.

Fix the root cause instead. Split the root module by ownership and change rate, so each plan refreshes hundreds of resources rather than thousands. Replace expensive data sources with inputs or outputs from other stacks. Reduce API throttling, and use -target only for genuine emergencies. Keep full refresh on scheduled drift checks, so even if a team uses shortcuts during development, drift is still caught.

Trade-offs

Skipping refresh speeds plans a lot but trades away drift detection; splitting state is more work but keeps plans fast and honest.

Common mistake

Making -refresh=false the CI default and then applying plans that silently revert console changes.

Follow-up

How would you decide where to split a 3,000-resource root module?

Question 132HardDependencies

A small change makes the plan show dozens of unrelated resources as "known after apply" and some as replaced. A data source is involved. Why?

#

A module reads data.aws_iam_policy_document and an aws_ami lookup with depends_on = [module.network]. Any change in the network module now ripples into the compute resources.

Show answer

Terraform normally reads data sources during plan. But if a data source's configuration depends on values that are not known until apply, the references docs say it cannot be read during plan and is deferred to apply. The data sources docs add that when a data source depends on other objects, its results are unknown during plan. Everything that uses those results also becomes unknown, which can show as "known after apply" and, for arguments that force replacement, as planned replacements.

depends_on on a data source makes this worse: it ties the read to every change in the dependency, not to a specific value. The depends_on docs warn that it can make Terraform treat more values as unknown. So a routine change in the network module defers the AMI lookup, and the instance plan looks alarming.

The fix is to depend on data, not on whole modules. Pass the specific values the data source needs (such as a VPC ID output) as arguments, so Terraform knows exactly what the read depends on. Remove depends_on from data sources unless there is a hidden dependency you cannot express otherwise, and pin AMI lookups to explicit IDs or versions in production.

Trade-offs

Explicit value references keep plans precise but require modules to expose the outputs callers need.

Common mistake

Approving a plan full of "known after apply" values because they look harmless, when some of them force replacement.

Follow-up

How would you review a plan that contains many unknowns before approving it?

Question 133EasyModules

A module fails because a for_each argument is sensitive. Why does Terraform refuse, and how do you fix it without leaking secrets?

#

A map of database users to generated passwords is passed to for_each. The map is marked sensitive because of the passwords, and the plan fails.

Show answer

Terraform uses the for_each value to identify each resource instance; the keys appear in resource addresses, in plan output and in state. The for_each docs state that sensitive values are not allowed for exactly that reason: an address cannot be hidden.

So separate identity from secrets. Iterate over something non-sensitive, such as the set of user names (toset(keys(...)) when the keys themselves are not secret, or a separate non-sensitive list of names), and look up the secret value inside the resource with each.key. The password stays sensitive where it is used, while the keys that name instances are ordinary values.

If the names themselves are confidential, that is a design smell: anything used as an address will be visible in plans and state, so use neutral keys such as app1, app2 and keep the real identifiers inside sensitive arguments.

Trade-offs

Passing names separately adds one input, but keeps addresses readable and secrets marked sensitive.

Common mistake

Wrapping the whole map in nonsensitive() to make the error go away, which prints the passwords in the plan.

Follow-up

How would you keep these passwords out of state entirely?

Iterate over names, read secrets by key · hcl
variable "db_users" {
  type      = map(string) # user name => password
  sensitive = true
}

variable "db_user_names" {
  type = set(string)
}

resource "postgresql_role" "app" {
  for_each = var.db_user_names
  name     = each.key
  login    = true
  password = var.db_users[each.key]
}
Question 134MediumProvisioning

What are provisioners and why are they a last resort?

#

A team puts a remote-exec block in an EC2 resource to install packages after creation. The apply fails halfway and the instance is marked tainted.

Show answer

Provisioners run commands outside the provider model. local-exec runs on the machine running Terraform; remote-exec runs on the created resource and needs a connection block. You refer to the enclosing resource as self. They run during creation or, with when = destroy, before destruction.

They are a last resort because Terraform cannot predict or track their effects. A failed creation-time provisioner taints the resource, so the next apply destroys and recreates it. A destroy provisioner must be repeatable, is skipped with create_before_destroy, and disappears if you remove the resource block. Default on_failure = halt stops the apply; continue ignores errors and taint forces replacement.

Prefer a provider resource, a machine image with the software baked in, cloud-init or user data, or a configuration-management tool. Use data sources to discover facts instead of shelling out to fetch them.

Trade-offs

Provisioners are quick for a one-off bootstrap but leave work Terraform cannot plan, diff or audit.

Common mistake

Treating a provisioner as a normal, idempotent resource and expecting terraform plan to show its changes.

Follow-up

How would you replace a remote-exec package install with image-based provisioning?

Question 135HardCLI

What do the -target, -replace and -refresh-only options do, and what are their risks?

#

A plan wants to destroy a production database. Someone suggests targeting only the safe resources, replacing the state record, and skipping refresh to make the plan faster.

Show answer

-target=ADDRESS restricts the operation to that resource and its dependencies. HashiCorp reserves it for exceptional circumstances such as recovering from a mistake or working around a provider limitation; routine use hides drift and makes configurations hard to reason about.

-replace=ADDRESS plans a destroy and create for that object even when the configuration has not changed (available since 0.15.2). It supersedes the deprecated terraform taint, and cannot be combined with -destroy. For recurring replacement needs, lifecycle arguments such as create_before_destroy and replace_triggered_by are clearer.

-refresh-only (since 0.15.4) updates state and root outputs to match out-of-band changes without applying configuration changes — useful for inspecting drift. Supplying -refresh=false or -minimal-refresh can produce incomplete or wrong plans; avoid minimal refresh during provider upgrades.

Trade-offs

Narrowing a plan reduces immediate blast radius but leaves the rest of the configuration unverified.

Common mistake

Using -target as a normal deployment strategy, or assuming a refresh-only plan applies config changes.

Follow-up

How would you review a plan that unexpectedly proposes replacing a stateful resource?

Question 136MediumStructure

Workspaces versus separate directories versus separate repositories for environments: trade-offs?

#

A team wants dev, staging and prod to share one module but use different credentials and backends.

Show answer

CLI workspaces are several named states for one configuration and one backend. The selected name is stored locally in .terraform, and terraform.workspace can drive names, counts or tags. They suit near-identical temporary copies, such as a parallel stack for testing before production.

They are not an isolation mechanism: every workspace in a directory shares the backend, so it cannot give different environments separate credentials or ACLs. Separate working directories give each environment its own state, backend and configuration, at the cost of repeated init, plugin and module caches, and separate VCS updates. Separate repositories add independent ownership and review boundaries, but make sharing code harder.

HashiCorp recommends reusable modules plus a separate configuration per environment, each with its own backend and a small root module containing backend config and module blocks. Share values across configurations through remote-state outputs, data sources, tags or DNS.

Trade-offs

Workspaces minimise duplication; separate configurations cost more setup but make access control explicit.

Common mistake

Using workspaces as a security boundary between prod and dev, or expecting each workspace to use a different backend.

Follow-up

When would a temporary feature-branch workspace be preferable to a new directory?