Terraform Questions

DevOps and CloudOps | 50 questions | 2026

Terraform Interview Questions and Answers

State, locking, modules, for_each, workspaces, drift. Tap a question to open the model answer, most asked first.

Terraform interview questions for freshers 17

Q1FresherMost asked
Answer

What is the Terraform state file, and why does it matter?

The state file (terraform.tfstate) is Terraform's record of the real resources it manages. It links each resource block in your code to a real object (for example an instance ID) and stores its attributes. So when planning, Terraform can compare your code, the state and the real resources.

  • Without state, Terraform could not know what it already created.
  • It can contain secrets in plain text (passwords, keys), so it must be protected.
  • Never edit it by hand. Use terraform state subcommands.
  • Do not commit it to Git. Use a remote backend such as S3 with locking.

To keep it safe, do these things. Turn on versioning on the bucket, so you can recover from damage or a bad apply. Encrypt it with KMS. Limit access with IAM. Turn on locking. Keep one state for each environment or part, so a mistake affects only a small area.

What they are checking: Whether you know state links code to real resources, holds sensitive data, and needs a remote, locked and versioned home.

Q2FresherMost asked
Answer

What is Terraform and how do you use it?

Terraform is an open-source Infrastructure as Code tool. You describe cloud resources in config files (HCL), and Terraform creates, changes and deletes them in a repeatable way. The files say what you want, not how to do it (declarative).

  • You declare the desired end state, and Terraform works out the steps to reach it.
  • Providers (AWS, GCP, Azure, Kubernetes, Docker and so on) turn your code into API calls.
  • It keeps a state file that maps your code to real resources, so it can work out the differences.
  • Code lives in Git, is reviewed in pull requests, and the same code can build dev, staging and production.

Typical use: write main.tf with a provider and resources, run terraform init, plan to preview, then apply. In a team I store state remotely, run plan in CI on pull requests, and apply after approval.

provider "aws" { region = "ap-south-1" }

resource "aws_s3_bucket" "logs" {
  bucket = "my-team-logs-bucket"
}

What they are checking: Whether you understand declarative IaC and the basic plan and apply steps, not just the name of the tool.

Q3FresherMost asked
Answer

How do you create several similar resources, such as S3 buckets, Lambda functions or SQS queues, each with different settings?

Write the differences as data in a map. Then loop over it with for_each.

  • Define a variable of type map(object({...})) with one entry per resource.
  • for_each = var.buckets creates one resource for each key, and each.value holds the settings.
  • For Lambda, use the same zip file, but give each function its own name, handler or environment from the map.
  • For optional blocks like lifecycle rules, use dynamic blocks too.
  • Put it in a module if many teams repeat the pattern.
variable "queues" {
  type = map(object({ visibility = number, fifo = bool }))
}
resource "aws_sqs_queue" "q" {
  for_each                   = var.queues
  name                       = each.value.fifo ? "${each.key}.fifo" : each.key
  fifo_queue                 = each.value.fifo
  visibility_timeout_seconds = each.value.visibility
}

What they are checking: Whether you write differences as data and use for_each instead of copying blocks.

Q4FresherMost asked
Answer

What is the difference between count and for_each in Terraform?

Both create many copies of a resource or module, but they track the copies differently.

countfor_each
Inputa numbera map or set of strings
Addressaws_instance.web[0], [1]aws_instance.web["api"]
Remove a middle itemlater items shift and are rebuiltonly that item is destroyed
Per-item configcount.indexeach.key and each.value

Use count for identical copies or a simple on and off switch (count = var.enabled ? 1 : 0). Use for_each when items have different settings or fixed names. This is most real cases.

resource "aws_s3_bucket" "b" {
  for_each = toset(["logs", "backups", "assets"])
  bucket   = "acme-${each.key}"
}

What they are checking: Whether you know the problem with count, where numbers shift, and prefer for_each for fixed keys.

Q5FresherMost askedFree with sign-in
Answer

What are the main Terraform workflow commands, and how do you use variables?

The main commands are init, plan, apply and destroy.

Q6FresherFree with sign-in
Answer

How would you use Terraform to provision Docker resources?

Use the kreuzwerker/docker provider, which talks to the Docker daemon. You write images and containers as resources, and Terraform manages them with the usual steps.

Q7FresherFree with sign-in
Answer

What is Infrastructure as Code, and what benefits does Terraform bring?

Infrastructure as Code (IaC) means you describe servers, networks and databases in text files. The files have versions, are reviewed, and a tool applies them. You do not click in a console.

Q8FresherFree with sign-in
Answer

What are providers in Terraform, and how do they get installed?

A provider is a plugin that lets Terraform talk to an API such as AWS, Azure, Kubernetes or GitHub. It defines the resource types and data sources you can use.

You list the providers you need and their version rules. Then terraform init downloads them from the registry into the .terraform folder.

Q9FresherFree with sign-in
Answer

What do terraform init, plan, apply and destroy each do?

They are the main steps, run in this order:

Q10FresherFree with sign-in
Answer

What is a Terraform module and why would you use one?

A module is a folder of Terraform files that you use as one reusable unit. Every configuration is already a module (the root module). Other modules are called from it.

Use modules to avoid copy and paste. They also enforce rules (for example, every S3 bucket is encrypted). They hide complex parts behind a few inputs.

Q11FresherFree with sign-in
Answer

What is a Terraform backend, and how do you set up S3 with locking?

A backend decides where Terraform stores its state and how operations run. The default is a local file. Teams use a remote backend such as S3, so the state is shared, safe to keep and can be locked.

Q12FresherFree with sign-in
Answer

What is a data source in Terraform, and how is it different from a resource?

A data source reads information about something that already exists. A resource creates and manages something. Terraform never changes or destroys what a data source reads.

Q13FresherFree with sign-in
Answer

What are input variables, outputs and locals in Terraform?

They are three kinds of named values:

Q14FresherFree with sign-in
Answer

What is the .terraform.lock.hcl file, and should it be committed?

The lock file records the exact provider versions and checksums that terraform init picked. Yes, commit it to Git.

Q15FresherFree with sign-in
Answer

What do terraform fmt and terraform validate do, and where do they belong in CI?

terraform fmt rewrites files into the standard style (indentation, alignment). terraform validate checks that the config is written correctly and fits together (types, references). It does not contact any cloud API.

Q16FresherFree with sign-in
Answer

What are .tfvars files, and what is the order of variable precedence?

A .tfvars file holds values for input variables. The same code can then run with different settings for each environment, for example prod.tfvars.

Q17FresherFree with sign-in
Answer

What is idempotency in Terraform, and what happens if you run apply twice?

Idempotent means running the same operation again and again gives the same result. If you run terraform apply a second time with no code changes, Terraform sees that the real infrastructure already matches the config. It reports "No changes".

Terraform interview questions for experienced 21

Q18ExperiencedMost asked
Answer

Terraform or CloudFormation: which would you choose, and why?

For most teams I choose Terraform, but the right answer depends on context.

Terraform strengths:

  • Multi-cloud and many providers (Kubernetes, Cloudflare, Datadog, GitHub), one workflow.
  • Easy-to-read HCL, many ready-made modules, and plan shows the exact changes.
  • State gives you flexibility (import, move, run on one resource).
  • Loops and expressions are more powerful (for_each, dynamic).

CloudFormation strengths:

  • Made by AWS, with no state file to manage (AWS keeps it). It has automatic rollback on failure, drift detection (finding manual changes), and StackSets for many accounts.
  • New AWS features often arrive first, and it works closely with Service Catalog and SAM.

Downsides: with Terraform you must secure and lock the state yourself. With CloudFormation you are limited to AWS, and templates can be long.

My choice: Terraform for multi-cloud or platform work. CloudFormation or CDK when the company uses only AWS and wants built-in rollback and control.

What they are checking: Whether you can compare tools by their good and bad points, not just name a favorite.

Q19ExperiencedMost asked
Answer

How would you create 100 EC2 instances with unique names in Terraform?

Do not copy the resource block 100 times. Use count or for_each, and build the name from the index or a key.

  • Simple, identical servers: count = 100 with Name = "web-${count.index + 1}".
  • Servers with set names from a list or map: use for_each with the names as keys. Then removing one does not affect the others.
  • Use format("web-%03d", count.index + 1) for names with leading zeros.
  • Put shared settings (AMI, type, subnet, tags) in variables or locals. Put per-instance changes in a map.
  • Watch the API limits and quotas. In real work, a module or an Auto Scaling group is usually better than 100 separate instances.
resource "aws_instance" "web" {
  count         = 100
  ami           = var.ami_id
  instance_type = "t3.micro"
  tags = {
    Name = format("web-%03d", count.index + 1)
  }
}

What they are checking: Whether you use count or for_each, naming functions and variables instead of copy and paste, and think of ASGs.

Q20ExperiencedMost asked
Answer

How do you prevent state conflicts when several people run Terraform?

Use a remote backend with state locking, so only one apply can change the state at a time. Run applies from one controlled place.

  • Backend: S3 for storage. Terraform 1.10 and later can lock in S3 itself with use_lockfile = true. Older setups use a DynamoDB table with a LockID key.
  • Enable bucket versioning and encryption, and limit access with IAM.
  • Run plan on pull requests and apply from the CI pipeline after approval, not from laptops.
  • Split the state by environment and part, so people rarely work on the same state.
  • If a lock is stuck after a crashed run, check that nobody is running, then terraform force-unlock <LOCK_ID>.
terraform {
  backend "s3" {
    bucket       = "my-tfstate"
    key          = "prod/network/terraform.tfstate"
    region       = "ap-south-1"
    encrypt      = true
    use_lockfile = true
  }
}

What they are checking: Whether you understand locking and have worked in a team where applies at the same time would be dangerous.

Q21ExperiencedMost asked
Answer

What are dynamic blocks in Terraform, and when would you use them?

A dynamic block builds repeated inner blocks inside a resource from a list or map. You do not write each one by hand.

Use it when the number of inner blocks changes. Examples are security group ingress rules, lifecycle_rule blocks on a bucket, or setting blocks on an Elastic Beanstalk environment.

  • for_each gives the list or map.
  • content { } defines the block content, using <label>.value and <label>.key.
  • Do not overuse it. It makes code harder to read, so use plain blocks when the number is fixed.
resource "aws_security_group" "web" {
  name = "web"
  dynamic "ingress" {
    for_each = var.ports
    content {
      from_port   = ingress.value
      to_port     = ingress.value
      protocol    = "tcp"
      cidr_blocks = ["10.0.0.0/16"]
    }
  }
}

What they are checking: Whether you know the difference between loops on resources (count or for_each) and loops on inner blocks (dynamic).

Q22ExperiencedMost asked
Answer

How do you structure Terraform for multiple environments such as dev, staging and production?

Keep the logic in reusable modules. Give each environment its own config and its own state.

Common layout:

  • modules/ holds reusable code (network, compute, database).
  • envs/dev, envs/staging, envs/prod each call the modules with different variable values. Each environment has its own backend key.
  • You can also use a separate AWS account for each environment to keep them apart.
  • Version the modules with Git tags, so staging can try a new version before prod.
  • Pipeline: a pull request runs plan for the environment it changes. Apply goes to dev first, then staging, then prod after approval.

Workspaces are a lighter option. But they share one backend config, and it is easy to apply to the wrong environment. So many teams use directories (or Terragrunt) for production. Each directory has its own state, so you can update staging without touching production.

What they are checking: Whether you keep state and variables apart for each environment and move changes up step by step.

Q23ExperiencedMost askedFree with sign-in
Answer

How does Terraform handle resource dependencies, and what is depends_on?

Terraform builds a dependency graph by itself from references. If one resource uses an attribute of another (for example subnet_id = aws_subnet.a.id), that is an automatic dependency. Terraform creates the subnet first and destroys it last.

Q24ExperiencedMost askedFree with sign-in
Answer

What does a safe Terraform deployment workflow with approvals look like?

Changes go through Git and a pipeline, never from a laptop.

Q25ExperiencedMost askedFree with sign-in
Answer

How do you tag AWS resources consistently with Terraform?

Define tags once and use them everywhere. Do not repeat them on each resource.

Q26ExperiencedMost askedFree with sign-in
Answer

Is one big Terraform state file a good idea, and how do you manage state at scale?

No. One state for everything is risky. A mistake can hurt everything, plans are slow, teams block each other with locks, and one bad apply can damage all of it.

Split state by:

  • environment (dev, staging, prod),
  • layer or component (network, data, compute, apps),
  • and ownership (team or service).
Q27ExperiencedMost askedFree with sign-in
Answer

What is AWS CloudFormation, and what happens if someone manually deletes a resource it created?

CloudFormation is the IaC service made by AWS. You write a template (YAML or JSON) that describes resources, and create a stack. CloudFormation then creates the resources and handles order, updates and rollback.

Q28ExperiencedMost askedFree with sign-in
Answer

Which AWS resources have you provisioned with Terraform?

Answer in three parts: what you covered, examples, and what you learned. Sample answer:

Q29ExperiencedFree with sign-in
Answer

How do you configure providers for AWS in Terraform, including multiple regions or accounts?

A provider is the plugin that talks to an API. Declare it in required_providers with a version rule, and set it up in a provider block.

Q30ExperiencedFree with sign-in
Answer

How do you test Terraform code?

Use layers, from cheap and fast to slower and more realistic:

Q31ExperiencedFree with sign-in
Answer

What is Terragrunt, and what problems does it solve for Terraform?

Terragrunt is a small wrapper around Terraform (and OpenTofu). It keeps configs DRY (no repeated code) across many environments and states.

Q32ExperiencedFree with sign-in
Answer

What are Terraform workspaces, and when do you use them?

Workspaces let one configuration keep several separate state files. You pick one with terraform workspace select. The default workspace is default, and you read the current name with terraform.workspace.

Q33ExperiencedFree with sign-in
Answer

How do you write and share Terraform modules, and coordinate several engineers on one codebase?

A module is a folder of Terraform files with inputs (variables), outputs and resources. You call it with a module block. A good module does one job, has a few well-named inputs and sensible defaults, and has documented outputs.

Q34ExperiencedFree with sign-in
Answer

What are local-exec provisioners and user_data used for, and should you rely on them?

Both run commands, but at different places.

Q35ExperiencedFree with sign-in
Answer

How do you configure many EC2 instances identically, using AMIs, cloud-init and configuration management?

Pick the layer that fits how often the config changes.

Q36ExperiencedFree with sign-in
Answer

How do you provision EKS clusters and node groups with Terraform, and how do you upgrade them?

Use the community module terraform-aws-modules/eks/aws, or build it from aws_eks_cluster, IAM roles, aws_eks_node_group (or Karpenter), and VPC subnets tagged for load balancers.

Q37ExperiencedFree with sign-in
Answer

Which terraform state commands do you use for day-to-day work, and when is editing state justified?

The terraform state subcommands look at and edit the state without touching the infrastructure:

Q38ExperiencedFree with sign-in
Answer

What do Terraform Cloud, policy as code and approval gates add for a team?

They move Terraform from a command on a laptop to a controlled platform with records of every action.

Scenario based Terraform interview questions 12

Q39FresherMost askedScenario
Answer

How do you import a manually created resource into Terraform, and what do you do when a resource already exists?

Write the matching resource block. Then import the real object into state. Terraform will then manage it and not try to create a copy.

  • Classic way: terraform import aws_s3_bucket.logs my-existing-bucket.
  • Modern way (Terraform 1.5+): an import block, which you can review in a plan. It can also write the config for you with terraform plan -generate-config-out=generated.tf.
  • After importing, run plan and adjust the code until it shows no changes.
  • The classic import does not write code for you, and it imports only one resource at a time.
  • Use remote state with locking while doing this, so nobody changes the state at the same time.
import {
  to = aws_s3_bucket.logs
  id = "my-existing-bucket"
}
resource "aws_s3_bucket" "logs" {
  bucket = "my-existing-bucket"
}

What they are checking: Whether you can bring existing infrastructure under code safely, without rebuilding it.

Q40ExperiencedMost askedScenarioFree with sign-in
Answer

What happens in state if you remove one item from a looped resource list, and does it recreate stateful resources?

It depends on whether you used count or for_each.

Q41ExperiencedMost askedScenarioFree with sign-in
Answer

How do you delete one specific resource in Terraform without touching the rest?

The cleanest way is to remove the resource block from the code and apply. The plan then destroys only that resource, and the change is reviewed in Git.

Q42ExperiencedScenarioFree with sign-in
Answer

How would you recover a corrupted or lost Terraform state file?

Restore the last good copy first. Then check that it matches the real resources.

Q43ExperiencedScenarioFree with sign-in
Answer

How do you stop Terraform from destroying and rebuilding a resource such as an RDS instance? How do you protect a database from being deleted by mistake?

Use protection in Terraform and protection in AWS together.

Q44ExperiencedScenarioFree with sign-in
Answer

How do you detect and handle configuration drift, and how do you stop people making manual changes?

Drift is when real infrastructure is different from the code or state. It usually comes from manual changes in the console.

Detect:

  • terraform plan (or plan -refresh-only) shows differences.
  • Schedule a nightly plan in CI that alerts on any diff.
  • For CloudFormation, use stack drift detection.
Q45ExperiencedScenarioFree with sign-in
Answer

Your plan shows a resource will be destroyed and recreated, but you only changed a small setting. How do you find out why and avoid the replacement?

First, read the plan. Terraform marks the setting that forces the rebuild with # forces replacement. Then decide if the rebuild is really needed.

Q46ExperiencedScenarioFree with sign-in
Answer

Terraform apply fails with "Error acquiring the state lock". What do you do?

Do not force anything yet. First find out who or what holds the lock.

Q47ExperiencedScenarioFree with sign-in
Answer

An apply failed halfway and some resources were created. How do you recover?

Terraform saves each resource in state as soon as it is created. So after a half-finished apply, the state is usually correct for what worked. Recovery is mostly "fix the cause and run again".

Q48ExperiencedScenarioFree with sign-in
Answer

A secret such as a database password ended up in the Terraform state or in Git. What do you do, and how do you prevent it?

Treat it as leaked. Change the secret first, then clean up.

Immediate steps:

  1. Change the credential at the source (RDS master password, API key).
  2. If it was committed to Git, cleaning the history comes second. Changing the secret is what protects you.
  3. Restrict who can read the state bucket and check access logs.
Q49ExperiencedScenarioFree with sign-in
Answer

How do you refactor Terraform code (rename a resource, move it into a module) without destroying anything?

If you change a resource address, Terraform thinks the old one is deleted and a new one is needed. Tell it the object is the same. Then only the state changes, not the infrastructure.

Preferred way, which you can review: a moved block in code.

Q50ExperiencedScenarioFree with sign-in
Answer

How do you safely upgrade a Terraform provider or the Terraform version across many projects?

Upgrade on purpose, one small step at a time, and let plan show that it is safe.

Test yourself on TerraformQuick MCQs, right or wrong shown instantlyStart

More DevOps interview questions