Advanced Terraform Interview Questions (2027)
60 advanced Terraform interview questions: state internals, graph, providers, moved/import/removed blocks, terraform test, ephemeral values, scenarios.
Advanced Terraform interview questions test how well you understand what Terraform does under the hood: how state and the dependency graph drive a plan, how providers and meta-arguments behave, how to refactor with moved, import and removed blocks, and how to test, secure and scale configurations across many teams and accounts. This page has 60 questions for engineers with three or more years of Terraform work, grouped by level and followed by scenarios.
If you are newer to Terraform, start with our Terraform interview questions for freshers. For a broad question bank that covers every level, use the 120+ Terraform interview questions guide. This page goes deeper on internals and design trade-offs, which is where senior rounds spend their time.
Key takeaways
- Senior Terraform rounds focus on state, the resource graph, provider behaviour and safe refactoring, not on basic syntax.
- Know the config-driven refactoring blocks:
moved(Terraform 1.1),import(1.5),check(1.5),removed(1.7), and native testing withterraform test(1.6). - Ephemeral values (1.10) and write-only arguments (1.11) keep secrets out of state and plan files. Interviewers increasingly ask about them.
- Be ready to explain why
countandfor_eachdiffer in how they address instances, and what that means for refactoring. - Scenario questions test judgement: state recovery, drift, blast radius, and how you would split a monolithic root module.
How the questions are organised
| Section | Questions | What it checks |
|---|---|---|
| Core internals (2 to 5 years) | 1 to 20 | State, graph, providers, expressions, meta-arguments |
| Refactoring, testing and security (2 to 5 years) | 21 to 35 | moved, import, removed, check, terraform test, secrets |
| Senior and architect | 36 to 48 | Module design, state layout, policy, scale, platform teams |
| Scenarios | 49 to 60 | Incidents and design decisions you explain aloud |
Answers are checked against the HashiCorp Terraform documentation at developer.hashicorp.com. Terraform 1.17 was the current release line in November 2026.
Core internals: questions for 2 to 5 years of experience
1. What actually happens during terraform plan?
Terraform reads the configuration, loads the current state, refreshes remote objects through the providers (unless you pass -refresh=false), builds a dependency graph, and asks each provider to plan the difference between the desired and current values. The result is a set of proposed actions: create, update in place, replace, delete or no-op. Nothing changes in real infrastructure until apply.
2. Why does Terraform need state at all?
State maps resources in your configuration to real object IDs, stores attribute values that providers need for later diffs, records dependencies so deletes happen in the right order, and caches values for performance. Without it, Terraform could not tell which cloud object belongs to which resource address.
3. How does Terraform build its dependency graph?
It creates a node for each resource, data source, module call, provider and output, then adds edges from references in expressions. If resource B references aws_vpc.main.id, B depends on the VPC. You can view the graph with terraform graph, which outputs DOT format. Terraform walks the graph and runs independent nodes in parallel (10 at a time by default, changed with -parallelism).
4. When should you use depends_on, and why is it a smell when overused?
Use depends_on only for hidden dependencies Terraform cannot see from references, such as an IAM policy that must exist before an application inside an instance calls AWS. Overuse makes plans more conservative: on a module or data source it can defer reads to apply time and produce "known after apply" values everywhere.
5. Explain the difference between count and for_each in terms of instance addresses.
count addresses instances by integer index (aws_instance.web[0]). Removing an item from the middle of a list shifts every later index, so Terraform plans to destroy and recreate them. for_each addresses instances by map key or set value (aws_instance.web["api"]), so removing one key affects only that instance. Prefer for_each for anything with identity.
6. Why can't for_each use values that are unknown until apply?
Terraform must know the full set of instance keys at plan time to build the graph. If the keys depend on an attribute that only exists after creation, such as a generated ID, the plan fails with an error about for_each values being unknown. The fix is to key on values you control, such as names from variables.
7. What does the lifecycle block control?
It changes default resource behaviour. create_before_destroy reverses the replace order, prevent_destroy makes any plan that would destroy the resource fail, ignore_changes stops Terraform from reverting specific attributes, and replace_triggered_by forces replacement when another resource or attribute changes. precondition and postcondition blocks add custom validation.
8. What is the risk of ignore_changes = all?
Terraform stops managing every argument after creation, so drift is invisible and changes you make in code are silently ignored. It is better to list specific attributes, such as tags managed by another system or an autoscaling group's desired capacity.
9. How do provider aliases work, and when do you need them?
You declare a second provider block with an alias, then select it on a resource with provider = aws.us_east_1. You need aliases for multiple regions or accounts in one configuration, for example ACM certificates for CloudFront, which must live in us-east-1.
provider "aws" {
region = "ap-south-1"
}
provider "aws" {
alias = "us_east_1"
region = "us-east-1"
}
resource "aws_acm_certificate" "cdn" {
provider = aws.us_east_1
domain_name = "www.example.com"
validation_method = "DNS"
}
10. How do you pass aliased providers into a child module?
The child module declares configuration_aliases inside its required_providers entry, and the caller maps them with the providers argument on the module block. Child modules should not contain their own provider blocks with credentials, because that blocks count and for_each on the module and makes removal hard.
11. What does the dependency lock file do?
.terraform.lock.hcl records the exact provider versions and their checksums chosen by terraform init. Commit it so every machine and pipeline uses the same provider builds. Use terraform init -upgrade to move within your version constraints, and terraform providers lock -platform=... to add hashes for other operating systems.
12. What is the difference between a data source and a resource?
A resource is managed by Terraform: it creates, updates and deletes it. A data source only reads an existing object. Data sources are read during plan when their arguments are known; if they depend on unknown values, the read waits until apply.
13. How do dynamic blocks work, and when should you avoid them?
A dynamic block generates repeated nested blocks from a collection, such as ingress rules. Avoid them when the block count is small and fixed, because they make code harder to read. HashiCorp's style guidance recommends using them sparingly.
14. What are sensitive values, and do they stay out of state?
Marking a variable or output sensitive = true hides it from CLI output. It does not remove it from state: the value is still stored in plain text in the state file. That is why state must be encrypted and access-controlled, and why ephemeral values exist (see question 30).
15. How does Terraform handle a resource that fails halfway through apply?
If creation succeeds remotely but a later step fails, the provider can mark the resource as tainted in state, and the next plan proposes replacement. You can force the same behaviour on purpose with terraform apply -replace=ADDRESS, which replaced the old terraform taint command.
16. What does terraform refresh do today?
The standalone terraform refresh command is deprecated because it updates state without showing you what changed. Use terraform plan -refresh-only or terraform apply -refresh-only, which show the detected drift and let you approve it.
17. How do workspaces differ from separate root modules?
CLI workspaces give one configuration several state files under the same backend. They suit near-identical environments. Separate root modules (or directories per environment) suit environments that differ in shape, need different credentials, or must be isolated for blast radius. HashiCorp's docs say CLI workspaces are not a good fit for strong separation between environments.
18. What is state locking and which backends support it?
Locking stops two runs from writing the same state at once. HCP Terraform, the azurerm backend and the gcs backend lock natively. The s3 backend supports native S3 locking with use_lockfile = true in recent Terraform versions; the S3 backend docs mark DynamoDB-based locking as deprecated in its favour.
terraform {
backend "s3" {
bucket = "acme-tfstate"
key = "network/prod.tfstate"
region = "ap-south-1"
encrypt = true
use_lockfile = true
}
}
19. How do you read outputs from another configuration?
Use the terraform_remote_state data source, or better, publish values to a dedicated store such as SSM Parameter Store and read them with a normal data source. Remote state access requires read access to the whole state file, which exposes every secret in it.
20. What do the type constraints and validation blocks on variables give you?
Types such as object({ name = string, size = optional(number, 20) }) reject wrong input before planning. validation blocks add custom rules with error messages. Since Terraform 1.9 validation conditions can reference other variables, which makes cross-field checks possible.
Refactoring, testing and security
21. How do you rename a resource without destroying it?
Add a moved block from the old address to the new one. Terraform updates the state address during the next plan and apply. This works across modules too, and unlike terraform state mv it is reviewed in a pull request.
moved {
from = aws_instance.app
to = module.compute.aws_instance.app
}
22. How do you switch a resource from count to for_each safely?
Write one moved block per instance, mapping each index to its new key, for example from aws_subnet.private[0] to aws_subnet.private["a"]. Run a plan and confirm there are no destroy actions before applying.
23. How does the import block differ from terraform import?
The import block (Terraform 1.5) is declared in configuration, so imports show in the plan and go through review. With terraform plan -generate-config-out=generated.tf, Terraform can write starter configuration for imported resources. Since 1.7, import blocks also accept for_each.
import {
to = aws_s3_bucket.logs
id = "acme-prod-logs"
}
24. How do you stop managing a resource without deleting it?
Use a removed block (Terraform 1.7) with lifecycle { destroy = false }. Terraform drops the resource from state and leaves the real object alone. The older way is terraform state rm, which is not reviewed in code.
removed {
from = aws_s3_bucket.legacy
lifecycle {
destroy = false
}
}
25. What is a check block and how is it different from a postcondition?
A check block (1.5) runs assertions on every plan and apply and reports failures as warnings without blocking the run. It can include a scoped data source, for example an HTTP health check on a deployed endpoint. A postcondition fails the run when its condition is false.
26. How does terraform test work?
Tests live in .tftest.hcl files. Each file contains run blocks with command = plan or apply and assert blocks. Apply-mode tests create real resources and destroy them at the end. Since 1.7 you can mock providers with mock_provider so unit-style tests run without credentials.
run "bucket_name_has_prefix" {
command = plan
variables {
env = "dev"
}
assert {
condition = startswith(aws_s3_bucket.this.bucket, "acme-dev-")
error_message = "Bucket name must start with acme-dev-"
}
}
27. What else would you put in a Terraform CI pipeline besides plan?
Run terraform fmt -check, terraform validate, a linter such as TFLint, a static security scanner such as Checkov or Trivy, terraform test, and a policy check on the plan JSON (terraform show -json plan.out). Store the saved plan and apply exactly that file after approval.
28. Why apply a saved plan file instead of running apply directly?
terraform apply plan.out applies exactly what reviewers approved. If state changed since the plan was made, Terraform refuses to apply the stale plan. Running apply without a file computes a fresh plan that nobody reviewed.
29. How do you keep secrets out of Terraform code?
Read secrets at run time from a manager such as Vault or AWS Secrets Manager, pass credentials through environment variables or OIDC federation in CI, and never commit .tfvars files with secrets. Our guide to storing secrets in Ansible and Terraform projects covers the options.
30. What are ephemeral values and write-only arguments?
Terraform 1.10 added ephemeral variables, outputs and ephemeral resources, whose values exist only during a run and are never written to state or plan files. Terraform 1.11 added write-only arguments (names usually end in _wo), which accept ephemeral values, for example a database password, and are not persisted. Providers must support them for each resource.
31. How do you rotate a write-only password?
Because Terraform does not store the value, it cannot detect a change by comparison. Providers pair write-only arguments with a version argument (for example password_wo_version); you increment it to tell Terraform to send the new value.
32. How do you authenticate CI pipelines to the cloud without static keys?
Use OIDC workload identity: GitHub Actions, GitLab CI and HCP Terraform can exchange a short-lived token for cloud credentials (AWS IAM role, Azure federated credential, GCP workload identity federation). Scope the role per repository and per environment.
33. How do you protect the state file itself?
Store it in a remote backend with encryption at rest, versioning (for recovery), locking, and strict IAM so only the pipeline role can write. Block public access on the bucket and log access. Treat read access to state as access to every secret in it.
34. What is drift, and how do you detect it on a schedule?
Drift is a difference between state and real infrastructure, usually from console changes. Run terraform plan -refresh-only -detailed-exitcode on a schedule; exit code 2 means changes were found. HCP Terraform has built-in drift detection on its paid tiers.
35. When would you use terraform_data instead of null_resource?
terraform_data (Terraform 1.4) is built in, needs no extra provider, and stores input and output values. It is the recommended replacement for null_resource, for example as a target for replace_triggered_by or to hold provisioners.
Senior and architect questions
36. How do you decide how to split state?
Split by lifecycle, ownership and blast radius. Networking changes rarely and is shared, so it gets its own state. Application stacks change often and belong to product teams. Each environment and region gets separate state. Smaller states plan faster and limit damage, at the cost of more cross-state wiring.
37. What makes a good reusable module?
A clear purpose, a small typed input surface with sensible defaults, outputs for everything callers need, no provider blocks, version pinning through a registry or Git tags, examples, and tests. Avoid thin wrappers around a single resource; they add indirection with little benefit.
38. How do you version and release modules for many teams?
Publish them to a private registry (HCP Terraform, Terraform Enterprise or a Git-based registry) with semantic version tags. Callers pin with constraints such as ~> 3.2. Breaking changes go in a major version with migration notes and moved blocks inside the module where possible.
39. What are Terraform Stacks?
Stacks are an HCP Terraform feature for deploying the same set of components across many environments or regions, defined in .tfcomponent.hcl and .tfdeploy.hcl files. They manage ordering between components. Check the HCP Terraform docs for current availability on your plan before relying on it.
40. How do you enforce policy on Terraform changes?
Evaluate the plan before apply. Options include Sentinel or OPA policy sets in HCP Terraform and Terraform Enterprise, Conftest against plan JSON in any CI system, and cloud-native guardrails (AWS SCPs, Azure Policy) as a second layer that also catches non-Terraform changes.
41. How do you handle provider upgrades across hundreds of configurations?
Pin provider versions, read the upgrade guide for the new major version, use a bot such as Renovate or Dependabot to raise pull requests that update constraints and the lock file, and roll out from low-risk environments first. Check plans for unexpected replaces.
42. Terraform or OpenTofu: what would you say if asked?
OpenTofu is a Linux Foundation fork created after HashiCorp moved Terraform to the Business Source License in August 2023. It is largely compatible but the projects have diverged on some features. The choice depends on licence requirements, features and vendor support. Answer neutrally and mention that you check compatibility for each provider and feature.
43. How do you speed up slow plans in a large state?
Split the state, reduce data sources that call slow APIs, avoid depends_on on modules, and raise parallelism carefully. -refresh=false or -target help in emergencies but should not become routine because they hide drift.
44. Why is -target discouraged?
It applies a partial graph, so state can diverge from configuration and later plans can surprise you. HashiCorp documents it for exceptional cases such as recovering from mistakes, not daily use.
45. How would you design a self-service Terraform platform?
Offer approved modules in a registry, a template repository per stack type, a pipeline that runs checks, policy and plan on every pull request, OIDC credentials per environment, and clear ownership of each state. Track cost estimates and drift reports.
46. How do you manage multiple AWS accounts?
Use one provider configuration per account with assume_role, an organisation structure with separate accounts per environment, and a deployment role in each account that the CI identity can assume. Keep state per account so a mistake in one cannot touch another.
47. How do you handle resources created outside Terraform by other tools?
Decide on one owner per resource. For shared resources, read them with data sources. For resources Terraform should take over, use import blocks. For attributes another controller changes, such as Kubernetes autoscaler replica counts, use ignore_changes on those attributes.
48. What is your approach to Terraform code review?
Review the plan output first, looking for replaces and deletes, then the code for naming, variable types, missing tags, hardcoded values and security settings. A small diff in HCL can still replace a database, which is why the plan matters more than the code.
Scenario questions
49. A plan wants to destroy and recreate your production database after a refactor. What do you do?
Stop and read which attribute forces replacement. If it is an address change, add a moved block. If an argument changed that forces replacement, revert it or plan a migration. Add prevent_destroy to critical data stores so this class of mistake fails the plan.
50. The state file was corrupted or overwritten. How do you recover?
Restore the previous version from backend versioning (S3 object versions, GCS object versioning or HCP Terraform state history). If no backup exists, rebuild state with import blocks. Then fix the root cause, usually missing locking or someone running locally with write access.
51. A pipeline run crashed and the state lock is stuck.
Confirm no run is actually in progress, then run terraform force-unlock LOCK_ID with the ID shown in the error. Never remove locks while another apply might be running.
52. Someone changed a security group rule in the console.
Run a refresh-only plan to see the drift. If the change was an emergency fix that should stay, add it to code. Otherwise apply to revert it. Then tighten console permissions and set up scheduled drift detection.
53. You need to move 200 resources from one state to another.
Since Terraform 1.7 you can use removed blocks with destroy = false in the source and import blocks with for_each in the destination, all reviewed in pull requests. Do it in batches and confirm empty plans on both sides after each batch.
54. A module upgrade shows unexpected replacements across environments.
Read the module changelog for address changes. Ask the module owner to add moved blocks inside the module, or add them in the caller. Roll out to development first and do not apply until production plans show only expected changes.
55. A for_each over a list of subnets fails with "unknown values".
The keys come from values only known after apply. Convert the input to a map keyed by static names, for example availability zone names from variables, so the keys are known at plan time.
56. Plans take 20 minutes in one root module.
Measure which providers and data sources are slow, then split the configuration by lifecycle. Move rarely changing infrastructure to its own state and expose its outputs through a parameter store.
57. A secret appeared in plaintext in the state file.
Rotate the secret first. Then restrict state access, move the value to a write-only argument or an ephemeral resource if the provider supports it, and check old state versions in the backend, which still hold the secret.
58. Two teams edit the same root module and keep blocking each other.
Split ownership: separate states per team with clear interfaces through outputs or a parameter store, CODEOWNERS on directories, and separate pipelines. Shared modules move to a registry with versioning.
59. You must adopt Terraform for an estate built by hand.
Inventory resources, start with the least risky group, write import blocks, use -generate-config-out for starter code, clean it into modules, and repeat until plans are empty. Lock down console write access once each area is under code.
60. An apply partially failed and left some resources created.
Do not delete things by hand. Run a new plan: Terraform knows what it created and will continue or replace tainted resources. Fix the error that caused the failure, such as a quota limit or a missing permission, and apply again.
Practise these hands-on
Reading answers is not enough for senior rounds. Build one small stack and practise each refactoring block, then break and recover state on purpose. The Terraform scenario drills give more incidents to rehearse, and 20 advanced Terraform techniques covers patterns in more depth. For architect-level design questions, see Terraform engineer interview questions.
If you want guided labs, our Terraform training runs in the Kharadi, Pune classroom and live online across India.
FAQ
What counts as an advanced Terraform question?
Questions about state internals, the dependency graph, provider configuration, refactoring with moved, import and removed blocks, testing, secrets handling and multi-team design. Syntax questions are usually for freshers.
Which Terraform version should I know for interviews in 2027?
Know features up to the current 1.x release line. The most asked are moved (1.1), import and check blocks (1.5), terraform test (1.6), removed blocks and mocks (1.7), ephemeral values (1.10) and write-only arguments (1.11).
Is terraform taint still used?
It is deprecated. Use terraform apply -replace=ADDRESS, which shows the replacement in the plan before you approve it.
Does marking a value sensitive keep it out of state?
No. Sensitive only hides the value in CLI output. Use ephemeral values or write-only arguments to keep secrets out of state and plan files.
Should I learn OpenTofu too?
Knowing that it exists, why it was forked and that it is mostly compatible is enough for most interviews. Learn it in depth only if the job description mentions it.
How do I prepare for scenario questions?
Practise in a sandbox account: rename resources with moved blocks, import existing objects, restore state from a backup version and clear a stuck lock. Explain each fix aloud in under two minutes.
Official references
What's Your Reaction?
Like
0
Dislike
0
Love
0
Funny
0
Angry
0
Sad
0
Wow
0