Autocoder

Terraform Interview Questions and Answers

Last updated 2026-11-19

Terraform interviews separate people who have run terraform apply from people who have operated Terraform in a team. The recurring themes are state (where it lives, how it is locked, what happens when it is lost), module design, safe refactoring with moved blocks and imports, and how changes flow through review. This page has 16 worked questions with HCL and commands.

Examples use the HashiCorp Terraform CLI; OpenTofu is a compatible fork and the same ideas apply. For where Terraform fits in delivery, read the DevOps questions, and for the cloud providers it manages, the AWS and Azure pages.

Workflowinit, validate, plan, apply, destroy
Core objectsProviders, resources, data sources, variables, outputs, modules, state
Team concernsRemote state, locking, version pinning, review of plans, secrets in state

A baseline configuration to recognise

Interviewers often show a short file and ask what is wrong. Pin the Terraform and provider versions, store state remotely with locking, and keep variables typed with descriptions. The example uses an S3 backend with native lockfile support, introduced in recent Terraform releases; older setups use a DynamoDB table for locking.

hcl
terraform {
  required_version = ">= 1.10"
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 5.0"
    }
  }
  backend "s3" {
    bucket       = "acme-tf-state"
    key          = "prod/network/terraform.tfstate"
    region       = "ap-south-1"
    encrypt      = true
    use_lockfile = true
  }
}

variable "cidr" {
  type        = string
  description = "VPC CIDR block"
  default     = "10.20.0.0/16"
}

resource "aws_vpc" "main" {
  cidr_block = var.cidr
  tags       = { Name = "prod" }
}

output "vpc_id" {
  value = aws_vpc.main.id
}

Terraform Interview Questions and Answers: questions with worked answers

  1. 1

    Explain the Terraform workflow and what init, plan and apply each do.

    easy

    terraform init downloads providers and modules and configures the backend; run it after cloning or changing providers. terraform validate checks syntax and internal consistency. terraform plan refreshes state, compares it to configuration and prints the actions it would take without making changes; saving it with -out gives an exact plan to apply later. terraform apply executes the plan, asking for confirmation unless given a saved plan or auto-approve. destroy removes everything managed by the configuration. In CI, run plan on pull requests and apply the reviewed, saved plan after merge.

    bash
    terraform init
    terraform fmt -check -recursive
    terraform validate
    terraform plan -out=tfplan
    terraform apply tfplan
  2. 2

    What is Terraform state and why does it matter?

    easy

    State is a JSON file mapping each resource address in your configuration to the real object's ID and attributes. Terraform needs it to know what already exists, to compute diffs, to order dependencies and to track metadata. Losing it means Terraform no longer knows it owns the resources and would try to create duplicates. State can contain secrets in plain text, such as database passwords, so store it in an encrypted, access-controlled backend and never commit it to Git. Do not edit it by hand; use terraform state commands, moved blocks or import.

  3. 3

    Why use a remote backend and state locking? Describe a typical setup.

    medium

    A remote backend shares state between teammates and CI, adds encryption and versioning and avoids local-file loss. Locking prevents two applies from writing state at once, which could corrupt it. For AWS, an S3 bucket with versioning and encryption holds state; locking is done with a DynamoDB table in older versions or with the native lockfile option in newer ones. Azure uses a storage account blob container with lease-based locking, Google Cloud uses a GCS bucket, and Terraform Cloud or HCP Terraform offers managed state with run history. Restrict write access tightly, since state access equals infrastructure control.

  4. 4

    What is the difference between count and for_each, and why does for_each usually win?

    medium

    count creates N copies indexed by position. Removing an item from the middle of a list shifts every later index, so Terraform wants to destroy and recreate resources that did not change. for_each iterates over a map or set and keys each instance by a stable string, so removing one key affects only that instance. Use count for simple on-or-off toggles such as count = var.enabled ? 1 : 0, and for_each for collections. for_each requires keys known at plan time, and you cannot use values that depend on resources not yet created as keys.

    hcl
    variable "buckets" {
      type = map(object({ versioning = bool }))
      default = {
        logs    = { versioning = false }
        reports = { versioning = true }
      }
    }
    
    resource "aws_s3_bucket" "this" {
      for_each = var.buckets
      bucket   = "acme-${each.key}"
    }
    
    resource "aws_s3_bucket_versioning" "this" {
      for_each = { for k, v in var.buckets : k => v if v.versioning }
      bucket   = aws_s3_bucket.this[each.key].id
      versioning_configuration { status = "Enabled" }
    }
  5. 5

    How do modules work, and what makes a module well designed?

    medium

    A module is a directory of Terraform files that you call with a module block, passing inputs as variables and reading outputs. The root module is the directory you run in. Good modules do one coherent job such as a VPC or an ECS service, expose few well-documented and typed variables with sensible defaults and validation, output what callers need, pin provider requirements without configuring providers inside, and are versioned through Git tags or a registry. Avoid wrapping a single resource in a module with all its arguments re-exposed, which adds indirection without value. Test with terraform test or Terratest.

    hcl
    module "network" {
      source  = "git::https://github.com/acme/tf-modules.git//vpc?ref=v2.3.1"
      cidr    = "10.20.0.0/16"
      azs     = ["ap-south-1a", "ap-south-1b"]
    }
    
    resource "aws_instance" "app" {
      ami           = data.aws_ami.al2023.id
      instance_type = "t3.micro"
      subnet_id     = module.network.private_subnet_ids[0]
    }
  6. 6

    What is the difference between a resource and a data source?

    easy

    A resource block declares something Terraform creates, updates and destroys. A data block reads information about something that already exists, or that is computed, without managing it: the latest AMI, an existing VPC found by tag, the current AWS account ID, or an IAM policy document. Data sources are re-read on each plan, so a data source that returns a changing value, such as most_recent AMI, can cause diffs. Reading remote state from another configuration through terraform_remote_state is also a data source, though explicit outputs through a registry or parameter store are often more decoupled.

  7. 7

    How do you handle an existing resource that was created manually? Explain import and import blocks.

    medium

    Terraform must be told that a real object belongs to a resource address. The CLI command terraform import adds it to state but you must write the matching configuration yourself afterwards. Since Terraform 1.5 you can declare an import block in code, so the import goes through plan and review, and terraform plan -generate-config-out can draft the resource configuration. After import, run plan and iterate until it shows no changes. Importing does not create code for everything attached to the resource, such as separate security group rule resources, so check carefully.

    hcl
    import {
      to = aws_s3_bucket.legacy
      id = "acme-legacy-assets"
    }
    
    resource "aws_s3_bucket" "legacy" {
      bucket = "acme-legacy-assets"
    }
  8. 8

    What are lifecycle rules? When do you use prevent_destroy, create_before_destroy and ignore_changes?

    medium

    The lifecycle block changes how Terraform handles a resource. prevent_destroy makes any plan that would destroy it fail, a guard for databases and state buckets, although it does not stop someone deleting the block. create_before_destroy builds the replacement first and then removes the old one, needed where there must be no gap, such as certificates or launch templates, and requires that names do not collide. ignore_changes tells Terraform to disregard drift on specific attributes, for example a desired count managed by an autoscaler or tags added by another system. replace_triggered_by forces replacement when another resource changes.

    hcl
    resource "aws_db_instance" "main" {
      identifier          = "orders"
      engine              = "postgres"
      instance_class      = "db.t4g.medium"
      allocated_storage   = 50
      username            = "app"
      manage_master_user_password = true
    
      lifecycle {
        prevent_destroy = true
        ignore_changes  = [allocated_storage]
      }
    }
  9. 9

    How do you refactor Terraform code (rename a resource or move into a module) without destroying infrastructure?

    hard

    Changing a resource address makes Terraform see one destroy and one create. Tell it the object moved instead. A moved block records the old and new address in code, so teammates get the same move on their next plan and it is reviewable. The older imperative alternative is terraform state mv, which edits one state file and needs coordination. After adding the moved block, run plan and confirm it reports the move and no replacement. Leave moved blocks in place for a while for consumers of shared modules, then remove them.

    hcl
    moved {
      from = aws_vpc.main
      to   = module.network.aws_vpc.this
    }
  10. 10

    What is configuration drift and how does Terraform detect it?

    medium

    Drift is when real infrastructure differs from state and code because of manual changes or other tools. Every plan refreshes state from the provider APIs and shows the difference, so a plain terraform plan reveals drift; terraform plan -refresh-only shows only the changes to state without proposing config changes, and apply -refresh-only accepts them. Run a scheduled plan in CI and alert on a non-empty result. Resolve by deciding which side is correct: either re-apply to revert the manual change or update the code to match. Restrict console write access to reduce drift at the source.

  11. 11

    Workspaces versus separate directories versus separate state files for environments?

    medium

    CLI workspaces give multiple state files for one configuration and backend, convenient for short-lived copies such as per-branch environments, but they hide which environment you are in and share identical code and backend credentials. For long-lived dev, staging and production, most teams prefer separate directories or root modules per environment that call shared modules, each with its own backend key and credentials, sometimes generated with Terragrunt. This makes differences explicit, enables different access control per environment and limits blast radius. Terraform Cloud workspaces are a different concept, closer to separate state plus variables per environment.

  12. 12

    How do you manage secrets with Terraform?

    hard

    Assume anything Terraform handles can land in state in plain text. Avoid putting secrets in variables files in Git. Prefer letting the service generate and manage them, such as manage_master_user_password on RDS, then have the application read from Secrets Manager. Where you must read a secret, use a data source from a secrets manager and protect the state backend with encryption and tight access. Mark variables and outputs as sensitive to hide them in CLI output, understanding this does not remove them from state. Newer Terraform versions add ephemeral values and write-only attributes to keep some secrets out of state.

  13. 13

    What does terraform plan show for a replacement, and how do you read the symbols?

    easy

    A plus means create, a minus means destroy, a tilde means update in place, and minus slash plus (or plus slash minus with create_before_destroy) means replace, meaning destroy and recreate. The line marked with forces replacement tells you which changed attribute is immutable, for example an RDS identifier or an EC2 instance's subnet. Always read the summary line, such as 1 to add, 0 to change, 1 to destroy, and review any destroy of stateful resources. Plans are the unit of code review: post them to the pull request for approval.

  14. 14

    How do variables get values, and what is the precedence order?

    medium

    From lowest to highest precedence: the default in the variable block, environment variables named TF_VAR_name, terraform.tfvars, terraform.tfvars.json, files ending .auto.tfvars in alphabetical order, then -var-file and -var flags on the command line in the order given. Later sources override earlier ones. Add type constraints and validation blocks so bad input fails at plan time with a clear message, and use locals for computed values you reuse. Never rely on interactive prompts in CI.

    hcl
    variable "env" {
      type = string
      validation {
        condition     = contains(["dev", "staging", "prod"], var.env)
        error_message = "env must be dev, staging or prod."
      }
    }
    
    locals {
      name_prefix = "shop-${var.env}"
    }
  15. 15

    How do you structure a CI pipeline for Terraform?

    medium

    On pull requests run fmt check, validate, a static analysis tool such as tflint and a policy or security scanner such as Checkov or Trivy, then plan and post the plan as a comment. On merge to main, apply the saved plan from the same commit, ideally with a manual approval for production, using short-lived cloud credentials via OIDC. Serialise runs per state file to avoid lock contention, pin tool versions, and keep a separate, restricted role for apply versus plan. Tools such as Atlantis, Terraform Cloud and GitHub Actions workflows implement this pattern.

  16. 16

    What is the difference between Terraform and Ansible?

    easy

    Terraform is declarative infrastructure provisioning: it creates cloud resources, tracks them in state and computes a plan. Ansible is primarily configuration management and orchestration: it connects over SSH or APIs and runs idempotent tasks to configure software on machines, and it has no persistent state by default. They are complementary: Terraform builds the network, instances and databases, then Ansible, or better a prebuilt image from Packer, configures what runs on them. Both can do parts of the other's job, but forcing that tends to be awkward. See the Ansible questions.

Frequently asked questions

Terraform or OpenTofu: which should I learn?

They share the same HCL, workflow and most providers, so learning one transfers. Many job postings still say Terraform, so use it for practice and know that OpenTofu is the open-source fork with largely compatible commands.

Do I need to know a programming language for Terraform roles?

HCL is declarative, but scripting in Bash or Python for glue, testing and CI is expected. Some teams also use CDK for Terraform or Pulumi, which use general-purpose languages.

What happens if two people run apply at the same time?

With a backend that supports locking, the second run fails to acquire the lock and waits or exits. Without locking, the later write can overwrite state and cause orphaned or duplicated resources.

Is the HashiCorp Terraform Associate exam worth it?

It validates core knowledge in a multiple-choice format and can help you get past screening. It is a supplement to, not a replacement for, showing a real project with modules and remote state.

Related guides

More in Role-wise Interview Questions by Job and Tech Stack

See all in this section