Last updated: 10 November 2026
Terraform is still the most-asked Infrastructure as Code skill in DevOps and cloud interviews. This list covers 45 questions, from the basics a fresher must know to the scenario questions senior engineers get. Each answer is short enough to say out loud, and most include a small HCL example.
New to IaC? Start with What is Terraform? and What is Infrastructure as Code?, then come back here.

Basic Terraform Interview Questions
Q1. What is Terraform?
Terraform is an open-source Infrastructure as Code tool from HashiCorp. You describe cloud resources in HCL (HashiCorp Configuration Language) files, and Terraform creates, updates or deletes real resources to match. It works with AWS, Azure, GCP, Kubernetes and hundreds of other platforms through providers.
Q2. How is Terraform different from Ansible or CloudFormation?
- Terraform vs CloudFormation: CloudFormation works only on AWS. Terraform works across clouds with one language and one workflow.
- Terraform vs Ansible: Terraform is declarative and built for provisioning infrastructure. Ansible is mostly procedural and built for configuring servers after they exist. Many teams use both.
More detail: Terraform vs Ansible and Terraform vs CloudFormation.
Q3. Explain the Terraform workflow.
The core workflow is write, init, plan, apply:
terraform init # download providers and modules, set up the backend terraform fmt # format the code terraform validate # check syntax and references terraform plan # show what will change terraform apply # make the changes terraform destroy # remove everything in this configuration
Q4. What is a provider?
A provider is a plugin that lets Terraform talk to an API, such as AWS or Azure. You pin its version in required_providers:
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 6.0"
}
}
}
provider "aws" {
region = "ap-south-1"
}
Q5. What is a resource and what is a data source?
A resource is something Terraform creates and manages. A data source only reads something that already exists.
data "aws_ami" "ubuntu" {
most_recent = true
owners = ["099720109477"]
filter {
name = "name"
values = ["ubuntu/images/hvm-ssd/ubuntu-*-24.04-amd64-server-*"]
}
}
resource "aws_instance" "web" {
ami = data.aws_ami.ubuntu.id
instance_type = "t3.micro"
}
Q6. What is the Terraform state file?
terraform.tfstate is a JSON file that maps your code to the real resources Terraform created, including their IDs and attributes. Terraform compares code, state and the real world to decide what to change. It can contain secrets, so never commit it to Git.
Q7. What are input variables, outputs and locals?
- Variables are inputs (
variable "region" {}). - Outputs expose values after apply (
output "vpc_id" { value = aws_vpc.main.id }). - Locals are named expressions you reuse inside a module.
variable "env" {
type = string
default = "dev"
}
locals {
name_prefix = "paperlive-${var.env}"
}
output "bucket_name" {
value = aws_s3_bucket.logs.bucket
}
Q8. What is the difference between variables.tf and terraform.tfvars?
variables.tf declares variables (name, type, default, validation). terraform.tfvars assigns values to them. You can keep one tfvars file per environment, such as dev.tfvars and prod.tfvars, and pass it with -var-file.
Q9. What is a Terraform module?
A module is a folder of .tf files that you call from other code. Every configuration is a root module. Modules let you package something like "a VPC" once and reuse it.
module "vpc" {
source = "terraform-aws-modules/vpc/aws"
version = "~> 5.0"
name = "main"
cidr = "10.0.0.0/16"
}
Guide: How to write reusable Terraform modules.
Q10. What does terraform init do?
It downloads providers and modules, configures the backend where state is stored, and creates the .terraform.lock.hcl file that locks provider versions. Run it again after changing providers, modules or backend settings.
Q11. What is the dependency lock file?
.terraform.lock.hcl records the exact provider versions and checksums chosen by init. Commit it to Git so every engineer and every pipeline uses the same provider builds. Use terraform init -upgrade to move to newer versions on purpose.
Q12. How do you force Terraform to recreate a resource? (Is terraform taint still used?)
terraform taint is deprecated. Use the -replace option instead. It shows the replacement in the plan first, so you can review it:
terraform plan -replace="aws_instance.web" terraform apply -replace="aws_instance.web"
Mentioning that taint is deprecated is a quick way to show you are up to date.
Q13. What does terraform fmt and terraform validate do?
fmt rewrites files into the standard style. validate checks that the configuration is syntactically valid and internally consistent, without calling any cloud API. Both belong in a pre-commit hook and the first stage of your pipeline.
Q14. What is terraform output used for?
It prints output values from state, for example to pass a load balancer DNS name to another tool. terraform output -json gives machine-readable output for scripts.
Q15. What is HCL?
HashiCorp Configuration Language is the declarative language Terraform uses. It has blocks, arguments, expressions, functions (join, lookup, cidrsubnet) and types (string, number, bool, list, map, object).
Intermediate Terraform Interview Questions
Q16. How do you manage state in a team?
Store state in a remote backend, not on laptops. A common AWS setup is an S3 bucket with versioning and encryption. Terraform 1.10+ supports native S3 locking with use_lockfile, so a DynamoDB table is no longer required.
terraform {
backend "s3" {
bucket = "paperlive-tf-state"
key = "network/prod.tfstate"
region = "ap-south-1"
encrypt = true
use_lockfile = true
}
}
Q17. What is state locking and why does it matter?
Locking stops two people or pipelines from running apply on the same state at once, which could corrupt it. The backend takes a lock at the start of a write operation and releases it at the end. terraform force-unlock is the last resort when a lock is stuck.
Q18. Local vs remote backends?
A local backend keeps state in a file on your machine. It is fine for learning. A remote backend (S3, Azure Storage, GCS, HCP Terraform) gives shared access, locking, encryption and history, which every team needs.
Q19. What is the difference between count and for_each?
count creates N copies indexed by number. for_each creates one copy per key in a map or set. Prefer for_each when items can be added or removed, because removing an item from the middle of a count list shifts the indexes and forces recreations.
resource "aws_iam_user" "team" {
for_each = toset(["asha", "ravi", "meera"])
name = each.key
}
Q20. How does Terraform handle dependencies?
Terraform builds a dependency graph from references. If resource B uses aws_vpc.main.id, Terraform creates the VPC first. Use depends_on only for hidden dependencies that do not appear in any reference.
Q21. How do you import existing infrastructure?
Since Terraform 1.5, use an import block. It is part of the plan, so it can be reviewed and run in CI. Add -generate-config-out to have Terraform write the resource code for you.
import {
to = aws_s3_bucket.logs
id = "paperlive-logs-prod"
}
terraform plan -generate-config-out=generated.tf
The older terraform import ADDRESS ID command still works but changes state immediately without a plan.
Q22. What are workspaces?
Workspaces give one configuration several separate state files (default, dev, prod). They are handy for short-lived copies of the same stack. Many teams prefer separate folders or separate backends per environment for production, because it is harder to apply to the wrong one.
terraform workspace new dev terraform workspace select prod
Q23. What are dynamic blocks?
A dynamic block generates repeated nested blocks from a collection, such as ingress rules on a security group.
dynamic "ingress" {
for_each = var.ports
content {
from_port = ingress.value
to_port = ingress.value
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}
}
Q24. What is the lifecycle block?
It changes how Terraform replaces or deletes a resource:
create_before_destroy: build the new one before removing the old one.prevent_destroy: fail any plan that would delete it.ignore_changes: ignore drift on chosen attributes.replace_triggered_by: replace when another resource changes.
lifecycle {
create_before_destroy = true
ignore_changes = [tags["LastScanned"]]
}
Q25. What are provisioners and why are they a last resort?
Provisioners (local-exec, remote-exec) run scripts during create or destroy. They are not tracked in state and are hard to make idempotent. Prefer cloud-init/user data, a configuration tool like Ansible, or baked images.
Q26. What are variable validation rules?
Validation blocks reject bad input during plan:
variable "env" {
type = string
validation {
condition = contains(["dev", "stage", "prod"], var.env)
error_message = "env must be dev, stage or prod."
}
}
Q27. What are preconditions and postconditions?
They are checks inside a resource's lifecycle block. A precondition runs before the resource is changed; a postcondition runs after. If either fails, the run fails with your error message.
Q28. What is a check block?
Added in Terraform 1.5, a check block runs assertions on every plan and apply but only produces warnings, not errors. It is useful for health checks on live infrastructure:
check "site_is_up" {
data "http" "home" {
url = "https://paperlive.in"
}
assert {
condition = data.http.home.status_code == 200
error_message = "paperlive.in did not return 200."
}
}
Q29. What is a moved block?
A moved block tells Terraform that a resource has a new address, so it updates state instead of destroying and recreating the resource. Use it when you rename resources or move them into a module.
moved {
from = aws_instance.web
to = module.web.aws_instance.this
}
Q30. What is a removed block?
Added in Terraform 1.7, a removed block takes a resource out of Terraform's management without deleting the real resource:
removed {
from = aws_s3_bucket.legacy
lifecycle {
destroy = false
}
}
Advanced Terraform Interview Questions
Q31. How do you test Terraform code?
Use layers:
terraform fmt -checkandterraform validateon every commit.- Linters and policy scanners: TFLint, Checkov, Trivy.
- terraform test (built in since 1.6):
.tftest.hclfiles run plans or applies and check assertions. - Terratest (Go) for full end-to-end tests when needed.
# tests/bucket.tftest.hcl
run "bucket_name_has_prefix" {
command = plan
assert {
condition = startswith(aws_s3_bucket.logs.bucket, "paperlive-")
error_message = "Bucket name must start with paperlive-."
}
}
Q32. How do you handle secrets in Terraform?
- Never hard-code secrets or commit tfvars that contain them.
- Read secrets at run time from Vault, AWS Secrets Manager or Azure Key Vault.
- Mark variables and outputs
sensitive = trueso they are hidden in logs. - Encrypt and restrict access to state, since values can end up there.
- On Terraform 1.10+, ephemeral values and resources keep short-lived secrets out of state and plan files; 1.11 added write-only arguments for things like database passwords.
See Secrets management in DevOps.
Q33. What is drift and how do you detect it?
Drift is when real infrastructure no longer matches code, usually because someone changed it in the console. Detect it with a scheduled terraform plan -refresh-only (or plan -detailed-exitcode, which exits with 2 when there are changes). Then either update the code to accept the change or apply to revert it.
Q34. How do you integrate Terraform into CI/CD?
A typical pipeline: format and validate, lint and scan, plan on every pull request with the plan posted as a comment, a human approval, then apply of the saved plan file on merge. The pipeline authenticates with short-lived OIDC credentials rather than long-lived keys.
terraform plan -out=tfplan terraform show -no-color tfplan > plan.txt terraform apply tfplan
Related: How to build a CI/CD pipeline from scratch.
Q35. How would you structure Terraform for multiple environments?
A common layout is reusable modules plus a thin root per environment, each with its own backend key:
modules/ network/ eks/ envs/ dev/ main.tf backend.tf dev.tfvars prod/ main.tf backend.tf prod.tfvars
Keep blast radius small by splitting state per layer (network, data, apps) instead of one huge state.
Q36. How do you refactor a large Terraform codebase safely?
Split it into modules and smaller states step by step. Use moved blocks so resources are not recreated, terraform state mv or removed + import blocks to move resources between states, and check that each plan shows "0 to add, 0 to destroy" before applying.
Q37. How do you version and publish modules?
Keep modules in their own Git repos or a private registry, tag releases with semantic versions, and pin versions in callers (version = "~> 2.1" or ?ref=v2.1.0). Add a README, examples and terraform test files to each module.
Q38. What are the risks of terraform state commands?
state rm, state mv and manual edits change state without touching real resources. A mistake can make Terraform think a resource is gone (and create a duplicate) or lose track of it. Back up state first, prefer moved/removed/import blocks, and work with locking enabled.
Q39. How do you enforce policy on Terraform plans?
Run policy-as-code against the plan JSON (terraform show -json tfplan): OPA/Conftest, Checkov, or Sentinel/OPA in HCP Terraform. Typical rules: no public S3 buckets, required tags, allowed instance types and regions.
Q40. What is OpenTofu and how is it different from Terraform?
OpenTofu is an open-source fork of Terraform 1.5, created after HashiCorp moved Terraform to the Business Source License in 2023. It is run by the Linux Foundation and uses the same HCL and providers. Since the fork it has added its own features, such as client-side state encryption. Most Terraform knowledge applies directly. Compare them in Terraform vs OpenTofu.
Q41. HCP Terraform (Terraform Cloud) vs open-source Terraform?
The CLI is the same. HCP Terraform adds hosted remote state, remote runs, a private module registry, policy checks, team permissions and run history. See Terraform Cloud vs Terraform OSS.
Scenario-Based Terraform Interview Questions
Q42. Someone deleted a resource in the console. What happens on the next plan?
Terraform refreshes state, sees the resource is gone, and plans to create it again. If the deletion was intended, remove it from code (or use a removed block) instead of letting Terraform recreate it.
Q43. Your apply failed halfway. What do you do?
Read the error, fix the cause (permissions, quota, a bad value), and run plan again. Terraform records whatever was created before the failure, so the next apply only does the remaining work. If the state lock is stuck, confirm no run is active before force-unlock.
Q44. The state file is corrupted or lost. How do you recover?
Restore an earlier version from the backend (S3 versioning, Azure blob versioning, or HCP Terraform state history). If no copy exists, rebuild state with import blocks for each resource and confirm the plan shows no changes.
Q45. A plan shows a database will be destroyed and recreated. What do you check?
Find which attribute forces replacement (the plan marks it with "forces replacement"). Often it is a rename, which a moved block fixes, or a change to an immutable setting. Protect critical resources with prevent_destroy = true and never auto-apply plans that contain deletes.
How to Prepare for a Terraform Interview
- Build one small project end to end: a VPC, an EC2 or EKS cluster, an S3 backend with locking, and a pipeline that runs plan and apply.
- Practise explaining state, locking and modules on a whiteboard.
- Know what changed recently: import/moved/removed/check blocks, terraform test, ephemeral values and OpenTofu.
Want guided, hands-on practice? Our DevOps training covers Terraform with real AWS labs. You may also like Top 20 Kubernetes Interview Questions and Top 30 Docker Interview Questions.
Frequently Asked Questions
What are the most common Terraform interview questions?
Expect questions on the Terraform workflow (init, plan, apply), state and remote backends, state locking, modules, count vs for_each, variables and outputs, import blocks, drift, and how you run Terraform in CI/CD.
Is terraform taint still used in 2026?
No. terraform taint is deprecated. Use terraform apply -replace=ADDRESS to force a resource to be recreated. It shows the replacement in the plan before anything changes.
Should I learn Terraform or OpenTofu?
Learn Terraform first, since most job posts ask for it. OpenTofu is a fork of Terraform 1.5 and uses the same HCL, so the skills transfer almost one to one.
How should I prepare for a senior Terraform interview?
Be ready to design a module layout, explain your state strategy across environments, talk through a refactor with moved blocks, and describe how plans are reviewed and applied in a pipeline.


