Terraform & IaC Interview Questions and Answers

Providers, state, modules, workspaces and drift management.

Practise 10 random 8 peer-reviewed questions
Terraform & IaC Interview Syllabus & Preparation Strategy

Whether you are preparing for entry-level Terraform & IaC interview questions for freshers or senior software engineer interview questions addressing concurrency, scalability, and system architecture, this track provides peer-reviewed model answers with syntax walkthroughs, edge cases, and practical interview tips.

1 What is Terraform state and why should it be remote? Easy

Terraform state is a JSON file that maps your configuration to real infrastructure. It stores resource IDs, attribute values, and dependency metadata so Terraform knows what exists and how to change it.

Why remote state:

  • Team collaboration: everyone reads and writes the same state instead of overwriting each other.
  • Locking: backends such as S3 with DynamoDB, Azure Blob, or Terraform Cloud lock state during operations, preventing concurrent corruption.
  • Durability and security: state often contains secrets, so store it in encrypted, access-controlled storage with versioning.
  • CI/CD: pipelines can use the same state from any runner.
terraform {
  backend "s3" {
    bucket         = "my-tf-state"
    key            = "app/terraform.tfstate"
    region         = "us-east-1"
    dynamodb_table = "tf-locks"
    encrypt        = true
  }
}

Never commit state to Git. Back it up and treat it as sensitive.

2 What is the difference between count and for_each? Easy

Both create multiple instances of a resource, but they track them differently.

  • count takes a number and identifies instances by index, such as resource[0] and resource[1]. Removing an item from the middle shifts indexes and causes Terraform to recreate or destroy the wrong resources.
  • for_each takes a map or set and identifies instances by stable keys, such as resource["web"] and resource["api"]. Adding or removing one key only affects that instance.
resource "aws_instance" "app" {
  for_each      = toset(["web", "api"])
  ami           = "ami-12345678"
  instance_type = "t3.micro"
  tags          = { Name = each.key }
}

Use for_each when identity matters, such as per-environment or per-name resources. Use count for identical, interchangeable resources or simple conditional creation with count = var.enabled ? 1 : 0. Note that for_each keys must be known at plan time.

3 Explain providers and the terraform init workflow. Medium

A provider is a plugin that lets Terraform talk to an API, such as AWS, Azure, or Kubernetes.

  • Declare required providers and versions so builds are reproducible.
  • terraform init downloads providers, initialises the backend, and installs modules. Run it first in any working directory.
terraform {
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 5.0"
    }
  }
}
provider "aws" { region = "us-east-1" }

The core workflow is init, plan, apply, and destroy. Providers are versioned independently of Terraform core, so pin versions and commit the lock file .terraform.lock.hcl to keep CI consistent. Use provider aliases and multiple provider blocks when you work across regions or accounts. Run terraform init -upgrade to move to newer allowed versions deliberately.

4 What are Terraform modules and when would you use them? Medium

A module is a reusable package of Terraform configuration. Every configuration is a root module, and it can call child modules.

Benefits:

  • Encapsulation: expose a small set of input variables and outputs, and hide the complexity.
  • Consistency: standardise how a database or VPC is provisioned across teams.
  • Reuse: avoid copy-pasting the same blocks.
module "vpc" {
  source  = "terraform-aws-modules/vpc/aws"
  version = "5.5.0"
  name    = "app-vpc"
  cidr    = "10.0.0.0/16"
  azs     = ["us-east-1a", "us-east-1b"]
}

Use the public registry or a private module registry with version pins. Pass data in through variables and expose needed values via outputs. Avoid deep nesting and over-abstraction; a module should have a clear single purpose. Test modules with tools such as Terratest, and document inputs and outputs.

5 What is the difference between terraform plan and apply? Medium

plan is a dry run; apply makes changes.

  • terraform plan refreshes state, compares configuration to reality, and shows what will be created, updated, or destroyed. It does not change infrastructure. Use -out to save the plan.
  • terraform apply executes the proposed actions and calls provider APIs. With a saved plan it applies exactly what you reviewed.
terraform plan -out=tfplan
terraform apply tfplan
terraform plan -detailed-exitcode

The detailed exit code helps CI: 0 means no changes, 1 is an error, and 2 means changes are present. Review plans carefully, especially destroys and replacements marked -/+. A resource that changes a force-new attribute is destroyed and recreated, which can cause downtime. Use -target only for emergencies, since it can leave state inconsistent. In automation, always apply the reviewed plan file.

6 How do Terraform workspaces work and when should you use them? Medium

Workspaces let one configuration manage multiple, separate states. terraform.workspace is a variable naming the active workspace, and the default workspace always exists.

terraform workspace new dev
terraform workspace new prod
terraform workspace select prod
terraform workspace list

Each workspace has its own state, so resources are isolated. With the S3 backend, state goes to different keys per workspace.

Use cases:

  • Ephemeral environments for testing or feature branches.
  • Lightweight separation of dev, staging, and prod from one codebase.

Cautions:

  • Workspaces share the same configuration and variables, so environment differences must be parameterised.
  • They are easy to confuse, and a wrong selection can target production.
  • They do not provide strong isolation or separate credentials.

For serious environments, prefer separate directories or repositories with distinct backends and accounts. Use workspaces for temporary or closely related environments.

7 How do you manage infrastructure drift in Terraform? Hard

Drift is a difference between real infrastructure and Terraform state, usually caused by manual changes.

Detect:

  • terraform plan refreshes state and shows differences.
  • terraform plan -refresh-only shows drift without proposing configuration changes.
  • Scheduled CI plans on a branch detect drift automatically.

Respond:

  1. Decide whether the manual change is desired.
  2. If it should be reverted, run terraform apply to bring reality back to configuration.
  3. If the change is wanted, update code, then apply. Use terraform state mv or import to reconcile.
  4. Use terraform refresh or apply -refresh-only to update state from reality.
terraform plan -refresh-only
terraform import aws_s3_bucket.logs my-bucket

Prevent drift with policy: require all changes through CI, use read-only roles for humans, and enable AWS Config or Azure Policy alerts. Do not use terraform state rm to hide drift.

8 Explain Terraform lifecycle meta-arguments. Hard

The lifecycle block controls how Terraform creates, updates, and destroys a resource.

  • create_before_destroy: create the replacement before destroying the old one, reducing downtime for resources that must be replaced.
  • prevent_destroy: fails the plan if the resource would be destroyed. Useful for databases and state buckets.
  • ignore_changes: ignores changes to listed attributes, useful when an external system or autoscaler modifies them.
  • replace_triggered_by: forces replacement when a referenced resource or attribute changes.
  • precondition and postcondition: validate assumptions before or after an operation.
resource "aws_db_instance" "db" {
  lifecycle {
    prevent_destroy = true
    ignore_changes  = [tags["LastModified"]]
  }
}

Caveats: prevent_destroy does not protect against state removal or CLI deletes. ignore_changes can hide real drift. create_before_destroy requires no name conflicts. Use these deliberately and document why.

Frequently Asked Questions About Terraform & IaC Interviews

What do hiring managers evaluate in Terraform & IaC technical rounds?

Technical interviewers look for foundational fluency, idiomatic syntax, clarity when communicating complex logic, and awareness of performance trade-offs (e.g. memory footprint, render performance, and network latency) in production environments.

What are the best interview tips for practicing Terraform & IaC questions?

Use active recall: summarize each answer in your own words before revealing the model solution. Focus on explaining why a certain approach is chosen rather than just memorizing code syntax.