Terraform interview questions and answers for DevOps and cloud roles

Terraform interview questions center on state: what it records, where it lives, how it is locked, and what happens when real infrastructure drifts away from it. Around that, expect plan and apply, modules, provider versions, count versus for_each, import, lifecycle rules, environment layout and keeping secrets out of state and code. Senior rounds turn into scenarios: a corrupted state file, a plan that wants to destroy production, or a refactor that must not recreate anything.

By Published 6 min read

Where Terraform questions come up

Terraform is the default infrastructure-as-code tool in many DevOps, cloud, platform and SRE teams, so it appears in most of their interviews. Some loops ask conceptual questions only; others share a module and ask you to review it, or describe an incident and ask what you would run. OpenTofu is a fork of Terraform created after HashiCorp moved Terraform to a source-available license in 2023.

  1. ConceptsDeclarative infrastructure, providers and resources, state, and the plan and apply workflow.
  2. Code reviewA module or root configuration with problems: hardcoded values, count where for_each belongs, missing version pins.
  3. State scenariosLocks left behind, drift, resources created by hand, a resource that must move without being recreated.
  4. DesignRepository layout, environments, module versioning and how Terraform runs in CI with reviews and approvals.

Terraform fundamentals questions

Basics for freshers and first rounds
QuestionWhat it testsWhat a strong answer shows
What does Terraform do, and what does declarative mean here?Core modelYou describe the end state of infrastructure in HCL. Terraform compares it with its state and the real resources, then plans the create, update and delete calls needed to get there.
What happens in init, plan and apply?Workflowinit downloads providers and modules and configures the backend. plan refreshes state and shows the proposed changes. apply executes a plan, ideally the saved one from plan -out.
What is a provider?ProvidersA plugin that talks to one API, such as AWS, Azure, Kubernetes or GitHub, and defines its resource and data source types.
Resource versus data source?BlocksA resource is managed by Terraform: created, changed and destroyed. A data source only reads something that exists, such as an AMI ID or a VPC owned by another team.
What is the state file for?StateIt maps each resource address in your code to the real object's ID and stored attributes. Without it, Terraform cannot tell which real resources it manages or what changed.
How does Terraform decide the order of operations?Dependency graphFrom references between resources, which build a graph. depends_on adds an edge only when a dependency is not visible in the arguments.
What are variables, locals and outputs?Inputs and outputsVariables are inputs with types and validation, locals are named expressions inside a module, and outputs expose values to callers or other configurations.
What is the dependency lock file?Reproducibility.terraform.lock.hcl records the exact provider versions and checksums chosen by init. Commit it so every run uses the same providers.
How can a variable get its value?InputsFrom a default, TF_VAR_ environment variables, terraform.tfvars and *.auto.tfvars files, and -var-file or -var on the command line, with later sources in that list overriding earlier ones. Required variables without a value make plan stop and ask.
What does terraform fmt and validate check?Hygienefmt rewrites files to the canonical style. validate checks syntax and internal consistency without calling any API. Both belong in CI before plan.
Basics for freshers and first rounds. Scroll sideways on a small screen.

State, backends and locking questions

terraform {
  required_version = ">= 1.11"

  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 5.0" # pin to the major version you have tested
    }
  }

  backend "s3" {
    bucket       = "example-tf-state"
    key          = "network/prod.tfstate"
    region       = "eu-west-1"
    encrypt      = true
    use_lockfile = true # lock file in S3; older setups use a DynamoDB table
  }
}
A remote backend with encryption and locking, and pinned versions. Bucket and key names are placeholders.
  • Why use a remote backend instead of a local state file? So the team shares one source of truth, state is stored durably with versioning and encryption, and runs are locked so two applies cannot write state at the same time.
  • What does state locking prevent? Two concurrent operations reading the same state, both planning, and the second write overwriting the first, which leaves state out of step with reality.
  • A lock was left behind after a crashed run. What do you do? Confirm no run is still active, then release it with terraform force-unlock and the lock ID. Never force-unlock while someone else's apply might be running.
  • What is drift and how do you detect it? Changes made outside Terraform, for example in the console. plan shows them as differences; plan -refresh-only shows what changed without proposing fixes. A scheduled plan in CI catches drift early.
  • Why is state sensitive even when variables are marked sensitive? sensitive = true hides values in plan output, but state still stores attribute values, such as generated passwords, in plain text. Encrypt the backend and restrict who can read it.
  • Why might a team run plan with `-refresh=false`? On very large states, refreshing every resource is slow and can hit API rate limits. The cost is that the plan no longer sees drift, so a full refresh still has to run regularly.
  • When would you use `terraform state mv` or `state rm`? mv changes a resource's address after a rename; rm stops managing a resource without destroying it. Newer releases offer moved and removed blocks, which do the same in code that can be reviewed.

Modules, environments and structure questions

Intermediate questions on organizing Terraform
QuestionWhat it testsWhat a strong answer shows
What makes a good module?Module designA clear purpose, a small set of typed inputs with validation, useful outputs, no provider configuration inside, and versioned releases. Wrapping a single resource with no added value is not a good module.
How do you pin module versions?VersioningRegistry modules take a version constraint; Git sources take a ref to a tag. Unpinned modules can change underneath every run.
Workspaces or separate directories for environments?EnvironmentsCLI workspaces give several state files for one configuration and backend, which suits short-lived copies. Many teams keep production in its own directory and state, with separate credentials, so a mistake in staging cannot touch it.
How do you share outputs between configurations?CompositionThe terraform_remote_state data source, or better, publishing values to a parameter store and reading them with a normal data source, which avoids giving read access to the whole state.
How do you avoid giant state files?Blast radiusSplit by lifecycle and ownership: network, shared services, each application. Smaller states plan faster and limit what one bad apply can break.
How should Terraform run in CI?Automationfmt and validate on every change, a plan posted to the pull request, an approval, then apply of that exact saved plan with short-lived credentials. Pipeline design in general is covered in CI/CD interview questions.
Intermediate questions on organizing Terraform. Scroll sideways on a small screen.

count, for_each, import and lifecycle questions

variable "buckets" {
  type = map(object({ versioning = bool }))
}

resource "aws_s3_bucket" "this" {
  for_each = var.buckets
  bucket   = "example-${each.key}"

  lifecycle {
    prevent_destroy = true
  }
}

resource "aws_s3_bucket_versioning" "this" {
  for_each = { for name, cfg in var.buckets : name => cfg if cfg.versioning }
  bucket   = aws_s3_bucket.this[each.key].id

  versioning_configuration {
    status = "Enabled"
  }
}

# The logs bucket used to be a separate resource; keep it, do not recreate it
moved {
  from = aws_s3_bucket.logs
  to   = aws_s3_bucket.this["logs"]
}

# A bucket someone created in the console, now managed here
# ("reports" must also be a key in var.buckets)
import {
  to = aws_s3_bucket.this["reports"]
  id = "example-reports"
}
for_each keyed by name, a moved block for a refactor, an import block for a bucket made by hand, and a lifecycle guard.
Senior questions and scenarios
QuestionWhat it testsWhat a strong answer shows
count versus for_each?Addressingcount addresses instances by index, so removing an item from the middle of a list shifts every later index and Terraform plans to destroy and recreate them. for_each addresses by key, so only the removed key is affected.
When is count still the right choice?JudgementFor a simple on or off switch, such as count = var.enabled ? 1 : 0, or truly identical copies where order never changes.
How do you bring an existing resource under Terraform?ImportWrite the resource block, then import it with the CLI command or an import block, and run plan until it shows no changes. Recent versions can also generate a starting configuration.
What do create_before_destroy, prevent_destroy and ignore_changes do?LifecycleCreate the replacement first to avoid downtime; refuse any plan that would destroy the resource; ignore changes to attributes another system manages, such as an autoscaler's desired count.
The plan wants to destroy and recreate a production database. What do you do?RiskStop and read why: the plan marks the attribute that forces replacement. Often it is a renamed resource (use moved), a changed immutable argument, or a provider upgrade. Never apply until the replacement is explained.
How do you keep secrets out of Terraform code?SecretsRead them at run time from a secrets manager with a data source, or let the cloud service generate and store them. Pass any remaining values through the environment, never commit tfvars with secrets, and protect state, which may still hold them.
How do you replace one broken resource without touching others?Targeted changeterraform apply -replace=ADDRESS forces replacement of that resource as part of a normal plan. It replaced the older taint workflow.
How do you test Terraform code?Qualityfmt, validate and a linter on every change, policy checks on the plan, the built-in terraform test for modules in newer versions, and plans against a sandbox account before production.
Senior questions and scenarios. Scroll sideways on a small screen.

Fictional example

Answering "Someone changed production by hand. Now what?"
Interviewer
An engineer opened a security group port in the console during an incident. Today's plan shows Terraform wants to close it. What do you do?
Candidate
I would not just apply. First I would find out whether the port is still needed, by asking the engineer and checking the incident notes. If the change was a temporary fix that is no longer needed, I would apply the plan to close it and say so in the incident channel. If it should stay, I would add the rule to the code, open a pull request so it gets reviewed, and confirm the next plan shows no changes. Either way, I would add a scheduled drift check to the pipeline and agree with the team on an emergency path that ends with the change written in Terraform afterwards.

A one-week Terraform practice plan

  • Days 1 and 2: build a small network and one service in a sandbox account with a remote backend. Run plan, apply and destroy until the loop feels routine.
  • Day 3: change something in the console, then practice reading the drift in plan and in a refresh-only plan.
  • Day 4: convert a count-based resource to for_each with moved blocks and get a plan with zero replacements.
  • Day 5: import a resource created by hand and refine the code until plan is empty.
  • Days 6 and 7: practice the scenario answers out loud: stuck locks, a planned database replacement, secrets in state, and environment layout.

Terraform usually builds the servers that configuration management then sets up, which is where Ansible interview questions picks up, including how the two tools compare. For the pipelines that run Terraform, read Jenkins interview questions, and for the full loop see DevOps engineer interview questions.

State scenarios reward calm, step-by-step answers, and it is hard to judge your own pace from memory. Natively, an AI interview assistant for Mac and Windows, transcribes your mock infrastructure rounds on your computer so you can see whether you checked before you applied. In practice it can read a plan output or an HCL error from a screenshot and suggest what is forcing a replacement, and with Pro or the free trial it can use the résumé and job description you add. The transcript and your notes are saved to review later.

Questions people ask

What Terraform questions are asked in interviews?

What state is and where to store it, locking and drift, plan and apply, providers and version pinning, modules, workspaces versus separate state per environment, import, count versus for_each, lifecycle rules and how to keep secrets out of code and state.

What is the difference between count and for_each in Terraform?

count addresses instances by index, so removing a list item shifts later indexes and can recreate resources. for_each addresses instances by key, so adding or removing one key affects only that instance.

Why is Terraform state sensitive?

State stores resource attributes, which can include generated passwords and keys, in plain text even when variables are marked sensitive. Keep it in an encrypted remote backend with tight access.

Should I use Terraform workspaces for environments?

Workspaces suit short-lived copies of the same configuration. Many teams keep production in a separate directory and state with its own credentials, so a staging mistake cannot reach it.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP