
Terraform Interview Questions and Answers for 2026
Terraform Interview Questions and Answers for 2026
Whether you are interviewing for a cloud engineer, DevOps, or platform role, interviewers test both HCL syntax and how you handle state, refactoring, and production failures. This guide covers 22 Terraform interview questions across beginner, intermediate, and architecture scenarios. Read each question, answer it aloud first, and compare your reasoning against the model answers and HCL examples.
How to use this guide
Start with the beginner section to confirm you can explain state, dependency resolution, and variable precedence clearly without relying on memorized definitions. Move to the intermediate questions to practice explaining trade-offs around for_each, lifecycle rules, moved blocks, secrets, and CI testing. Treat the scenario section like a live system design round: state your assumptions, walk through failure modes, and describe how you verify changes before applying them.
Beginner Terraform interview questions
What is Terraform, and what advantages does Infrastructure as Code provide?
Terraform is an open-source Infrastructure as Code (IaC) tool that lets you define cloud and SaaS resources declaratively using HashiCorp Configuration Language (HCL). Instead of writing imperative scripts that issue step-by-step API calls, you describe the desired end state, and Terraform computes the operations needed to reach it. Compared to manual console provisioning, IaC gives you version-controlled changes, peer-reviewed pull requests, repeatable environments, and clear visibility into configuration drift.
How does the core init, plan, apply, and destroy workflow operate?
terraform init prepares the working directory by configuring the state backend, downloading required provider plugins and modules, and generating .terraform.lock.hcl. terraform plan refreshes state against real infrastructure, compares it with your HCL files, and outputs an execution preview without modifying resources. terraform apply executes that plan in dependency order and updates the state file. terraform destroy reverses the graph to tear down every resource tracked in the current state.
How do Terraform providers and version constraints work?
Providers are plugins that translate HCL resource definitions into API calls for platforms such as AWS, Azure, Google Cloud, or Kubernetes. You declare provider sources and version ranges in a terraform block, while .terraform.lock.hcl pins exact hashes so every teammate and CI runner uses identical provider binaries.
terraform {
required_version = ">= 1.5"
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 5.0"
}
}
}
What is the difference between variables, locals, and outputs?
Input variable blocks define external parameters callers can override per environment. locals compute internal expressions, naming prefixes, or merged maps inside a module without exposing them as inputs. output values export attributes—such as an endpoint or resource ID—to the terminal, parent modules, or downstream stacks.
variable "environment" {
type = string
default = "dev"
}
locals {
name_prefix = "app-${var.environment}"
}
output "prefix" {
value = local.name_prefix
}
How does variable precedence work across terraform.tfvars, environment variables, and CLI flags?
Terraform resolves variable values from lowest to highest precedence, so later sources override earlier ones. Environment variables prefixed with TF_VAR_ sit at the bottom, followed by terraform.tfvars or terraform.tfvars.json, then any *.auto.tfvars or *.auto.tfvars.json files loaded in lexical order, and finally -var or -var-file flags passed directly on the CLI. If no value is provided, Terraform falls back to the variable's default or prompts interactively.
What is Terraform state, and why does Terraform need it?
Terraform state is a JSON mapping that links resource addresses in your HCL code to real-world cloud resource IDs, along with cached attributes and dependency metadata. State is essential because cloud APIs do not automatically know which HCL block owns a specific VPC or bucket. By reading state during terraform plan, Terraform knows whether to create a new resource, update an attribute in place, or destroy a removed block, while enabling faster diffs on large deployments.
How do terraform fmt and terraform validate differ?
terraform fmt formats HCL files into canonical style—adjusting indentation, alignment, and spacing—without needing initialized providers or state. terraform validate checks whether your configuration is syntactically valid and internally consistent, verifying argument names, variable references, and expression types against initialized provider schemas. Neither command contacts remote cloud APIs or evaluates environment-specific variable values from external files; they catch structural errors early in local development and CI checks.
How do resource addresses, modules, and data sources work together?
Every managed object has a unique address such as aws_s3_bucket.logs or module.network.aws_subnet.private["a"]. You inspect those addresses with terraform state list and examine their stored attributes or saved plan details with terraform show. Modules package reusable resource groups behind clean inputs and outputs, whereas data blocks perform read-only lookups of infrastructure managed elsewhere.
data "aws_caller_identity" "current" {}
module "vpc" {
source = "./modules/vpc"
cidr = "10.0.0.0/16"
account = data.aws_caller_identity.current.account_id
}
Intermediate Terraform interview questions
Why are remote state backends and state locking essential for teams?
Storing terraform.tfstate locally fails in teams because teammates quickly overwrite each other's changes or work from stale files. A remote backend—such as S3, GCS, Azure Blob Storage, or HCP Terraform—centralizes state, supports encryption at rest, and provides versioning for recovery. State locking ensures only one apply or state mutation runs at a time, preventing concurrent runs from corrupting state JSON or provisioning duplicate infrastructure.
When should you choose for_each over count?
Use count only for simple boolean toggles (zero or one instance) or genuinely identical resources where order never changes. count indexes instances by integer position, so deleting an item from the middle of a list shifts subsequent indices and forces destructive replacements. for_each keys each instance by a stable map key or set string, so adding or removing an element affects only that specific key.
resource "aws_iam_user" "engineers" {
for_each = toset(["alice", "bob"])
name = each.value
}
How does Terraform build its dependency graph, and when do you need depends_on?
Terraform builds a directed acyclic graph (DAG) automatically from implicit references—whenever one resource or module reads an attribute exported by another, Terraform orders creation and deletion accordingly and runs unrelated branches in parallel. You should only add depends_on for hidden dependencies that have no direct attribute reference, such as ensuring an IAM role policy attachment completes before a compute instance starts reading from a restricted bucket.
How do lifecycle meta-arguments control resource replacement and deletion?
lifecycle rules customize how Terraform plans risky transitions. create_before_destroy provisions a replacement resource before tearing down the old one, minimizing downtime on immutable updates. prevent_destroy causes plans that would delete the resource to fail with an error, protecting databases or KMS keys. ignore_changes tells Terraform not to revert specific attributes modified externally, such as autoscaling desired counts or dynamic tags.
resource "aws_instance" "app" {
ami = var.ami_id
instance_type = "t3.micro"
lifecycle {
create_before_destroy = true
ignore_changes = [tags["LastPatched"]]
}
}
How do moved blocks let you refactor configurations without recreating resources?
When you rename a resource, migrate from count to for_each, or extract resources into a child module, Terraform normally interprets the change as destroying the old address and creating a new one. Adding a moved block instructs Terraform during plan and apply to update the address in state without touching the real infrastructure. Unlike manual terraform state mv commands, moved blocks are reviewed in Git and applied automatically across environments.
moved {
from = aws_instance.web
to = aws_instance.app
}
How do you bring existing infrastructure under Terraform management with import?
To adopt a manually created resource, write a matching resource block in HCL and pair it with an import block (or the terraform import CLI command) specifying the cloud resource ID. During terraform plan, Terraform reads the live object, maps it into state, and shows whether your HCL matches the actual attributes. Fix any unexpected diffs before running apply so Terraform does not overwrite live settings.
import {
to = aws_s3_bucket.legacy
id = "company-audit-logs"
}
How do Terraform workspaces compare to a directory-per-environment layout?
CLI workspaces let a single root configuration maintain multiple isolated state files (such as dev and staging). They work well for short-lived feature or test environments that share identical architecture, but become awkward when production diverges in backend permissions, provider versions, or module topology. A directory-per-environment layout—with separate state backends and explicit tfvars—gives clearer blast-radius isolation, independent version upgrades, and safer credential boundaries for production.
How should you handle secrets in Terraform, and what are the limits of sensitive?
Marking a variable or output with sensitive = true masks its value in CLI logs and plan previews, preventing casual exposure in CI output. However, Terraform still stores sensitive attribute values in plaintext inside the state file and saved binary plan files. Never commit secrets to Git; fetch credentials dynamically from a secret manager, encrypt remote state with strict IAM access, and limit who can download state or plan artifacts.
variable "db_password" {
type = string
sensitive = true
}
output "db_user" {
value = "admin:${var.db_password}"
sensitive = true
}
Why should you avoid provisioners, and how do you handle drift, saved plans, testing, and policy-as-code?
HashiCorp treats provisioners (local-exec, remote-exec) as a last resort because they execute imperative scripts outside Terraform's state model and require fragile network or SSH access. Prefer cloud-init, pre-baked images, or dedicated configuration tools instead. To keep changes reliable, detect drift with scheduled terraform plan -detailed-exitcode runs, save exact execution artifacts with terraform plan -out=tfplan, verify HCL logic using terraform test, and enforce security guardrails by evaluating plan JSON with OPA or Sentinel.
run "verify_bucket_name" {
command = plan
assert {
condition = aws_s3_bucket.logs.bucket == "prod-app-logs"
error_message = "Bucket name must match naming standard."
}
}
Scenario and architecture questions
How would you replace load-balanced or stateful instances with zero downtime?
First, separate persistent data from compute so instances can be replaced safely while databases or object storage remain untouched. Place instances behind a load balancer target group and configure lifecycle { create_before_destroy = true } on the launch template or instance resource. New instances register and pass health checks before Terraform deregisters and terminates old ones. Verify connection draining timeouts, test the replacement plan in staging first, and confirm rollback simply requires reverting the AMI or template commit.
How would you recover from a corrupted state file or an accidentally deleted resource?
Immediately freeze CI applies and keep state locking enabled so no additional runs compound the damage. If state is corrupted, restore the most recent healthy snapshot from your remote backend's object versioning (such as S3 versioning) and run terraform plan to compare state against live cloud APIs. If a resource was deleted outside Terraform, check whether backups or snapshots exist before recreating it via apply and restoring data, or import a replacement resource cleanly.
How would you structure a multi-environment, multi-account Terraform repository?
Split infrastructure into small, layered root stacks—such as networking, shared data, and application compute—inside per-environment directories (envs/dev, envs/prod) that consume versioned modules from a shared modules/ directory or private registry. Give each account and stack its own isolated state key and dedicated IAM role so a mistake in development cannot affect production. Keep environment differences explicit in small .tfvars files rather than burying environment conditionals inside modules.
How would you run Terraform safely in CI/CD using pull-request plan artifacts?
On every pull request, run terraform fmt -check, terraform validate, and terraform plan -out=tfplan, posting a readable summary back to the PR for peer review. Use short-lived OIDC credentials rather than static keys, and enforce branch protection plus manual approval for production environments. On merge, either apply the saved plan artifact (if state has not moved) or re-generate and verify the plan under a state lock before executing apply.
How would you reduce a 40-minute terraform apply without sacrificing safety?
Start by identifying whether the delay comes from slow cloud resources (like managed databases or CDN distributions) or serial bottlenecks during state refresh. Break monolithic configurations into smaller layered stacks connected through remote state outputs or data sources so unrelated changes never refresh hundreds of resources. Remove unnecessary depends_on blocks that serialize the dependency graph. Increase -parallelism cautiously only after checking provider API rate limits, and avoid skipping refreshes unless drift is controlled.
Common mistakes to avoid
- Storing state locally — Teammates overwrite changes and leak secrets in Git; always use an encrypted remote backend with locking.
- Using
countfor named lists — Removing an item shifts indices and destroys healthy resources; usefor_eachwith stable keys. - Hand-editing
terraform.tfstate— Syntax or lineage errors corrupt plans; usemoved,import, orterraform statecommands after backing up state. - Building monolithic root modules — Putting networking, databases, and apps in one state slows plans and widens blast radius; split into layered stacks.
- Running
apply -auto-approvein production — Minor edits can force replacements (-/+); review every plan diff and require approval. - Committing secrets in
.tfvars— Values leak via Git and state even withsensitive = true; read secrets at runtime from a secret manager.
Recommended certification and study resources
| Resource | Best for | Format | Cost tier |
|---|---|---|---|
| Free Terraform courses with 100%-off Udemy coupons on CouponCode.dev | Hands-on HCL labs and exam prep | Video courses | Free with coupon |
| Free DevOps and cloud courses with coupons | Broader CI/CD and cloud context | Video courses | Free with coupon |
| Udemy paid Terraform practice tests | Timed Terraform Associate mock exams | Practice tests | Paid |
| Pluralsight | Structured enterprise IaC learning paths | Interactive paths | Paid subscription |
| Educative | Browser-based text labs and reading | Text courses | Paid subscription |
Pair structured video or text coursework with daily terminal practice building and refactoring small stacks in a sandbox cloud account. Current partner links are listed in the recommended-platforms section beneath this article.
Key takeaways
- State drives every decision: Know how state maps HCL addresses to real resources, why locking matters, and how to recover from backend versioning.
- Prefer declarative refactoring: Use
for_each,lifecycle,moved, andimportblocks instead of manual state edits or fragilecountlists. - Design for small blast radius: Split stacks by lifecycle and account, authenticate CI with OIDC, and treat state files as sensitive artifacts.
- Communicate trade-offs clearly: Explain how you verify plans, protect stateful workloads during replacements, and catch drift before applying.
Recommended Paid Learning Platforms & Certifications
Affiliate disclosure — we may earn a commissionUdemy Flash Sales (Up to 85% Off)
Top-rated courses in Python, Cloud, AI & Web Dev starting around $11.99.
Coursera Plus
Unlimited access to 7,000+ Google, Meta, IBM & AWS professional certificates.
DataCamp
Hands-on interactive tracks for Python, SQL, Machine Learning & TensorFlow.





