← Interview Questions
Terraform70+ Questions · Beginner to Expert
Terraform Interview Questions & Answers (2026)
70+ Terraform questions with expert-level answers. State management, modules, workspaces, lifecycle rules, testing with Terratest, import workflows, and HashiCorp Certified Terraform Associate exam prep.
Beginner
Q: What is Terraform and how does it work?
Terraform is an open-source Infrastructure as Code (IaC) tool created by HashiCorp that enables you to define, provision, and manage cloud and on-premises infrastructure using a declarative configuration language (HCL — HashiCorp Configuration Language).
**How it works — the core workflow:**
1. **Write:** You write HCL configuration files (.tf) that describe the desired state of your infrastructure — VMs, databases, networks, DNS records, Kubernetes clusters, etc.
2. **Plan (`terraform plan`):** Terraform reads your configuration, queries the current state of your infrastructure (from the state file), and produces an execution plan showing what changes it will make. No changes are applied yet.
3. **Apply (`terraform apply`):** Terraform executes the plan, making API calls to cloud providers (AWS, GCP, Azure, etc.) to create, update, or delete resources to match your declared configuration.
4. **State:** Terraform stores information about the resources it has created in a state file (terraform.tfstate). This file maps your configuration to real-world resources and is the source of truth for what Terraform manages.
**Declarative vs. Imperative:**
You declare WHAT you want (e.g., "I want 3 EC2 instances of type t3.medium") not HOW to create it. Terraform figures out the sequence of API calls needed. If the resource already exists in the desired state, Terraform does nothing.
**Provider ecosystem:**
Terraform uses "providers" (plugins) to interact with cloud platforms, SaaS services, and APIs. The Terraform Registry hosts 3,000+ providers: AWS, Google Cloud, Azure, Kubernetes, GitHub, Datadog, PagerDuty, and more.
Q: What is Terraform state and why is it important?
Terraform state is a JSON file (terraform.tfstate) that records what infrastructure Terraform currently manages. It maps your configuration resources to real-world resource IDs, attributes, and metadata.
**Why state is necessary:**
- Terraform needs to know what already exists before deciding what to create, modify, or destroy.
- Without state, Terraform would have no way to determine if a resource already exists or needs to be created.
- State enables Terraform to detect drift: if someone manually modified a resource outside Terraform, the next `terraform plan` will show the discrepancy.
**What state contains:**
- Resource addresses and their real-world IDs (e.g., `aws_instance.web → i-0abc1234def`)
- All attributes of managed resources (AMI, instance type, tags, etc.)
- Dependencies between resources
**Remote state (critical for teams):**
Local state files are dangerous for teams — simultaneous runs can corrupt state. Remote backends (S3, Terraform Cloud, GCS, Azure Blob) store state centrally:
```hcl
terraform {
backend "s3" {
bucket = "my-terraform-state"
key = "prod/network/terraform.tfstate"
region = "us-east-1"
dynamodb_table = "terraform-state-lock" # prevent concurrent modifications
encrypt = true
}
}
```
**State locking:** DynamoDB (for S3 backend) prevents two Terraform runs from modifying state simultaneously, preventing corruption.
**Never edit state manually** unless you know exactly what you are doing. Use `terraform state` commands for safe manipulation.
Q: What are Terraform modules and why should you use them?
A Terraform module is a collection of Terraform configuration files in a single directory that can be called from other configurations, similar to a function in programming.
**Why use modules:**
- **Reusability:** Write the infrastructure pattern once, use it many times with different parameters.
- **Encapsulation:** Hide implementation complexity — callers only need to know the inputs and outputs.
- **Consistency:** Enforce organizational standards — every VPC is created the same way, every EKS cluster follows the same security baseline.
- **Maintainability:** Fix a bug in the module once; all callers benefit.
**Module types:**
- **Root module:** The directory where you run Terraform commands. Every configuration is a module.
- **Child module:** A module called by another module via a `module` block.
- **Published modules:** Modules shared in the Terraform Registry (e.g., `terraform-aws-modules/vpc/aws`).
**Basic module structure:**
```
modules/
vpc/
main.tf # resource definitions
variables.tf # input variables
outputs.tf # output values
versions.tf # required providers
```
**Calling a module:**
```hcl
module "vpc" {
source = "terraform-aws-modules/vpc/aws"
version = "~> 5.0"
name = "production-vpc"
cidr = "10.0.0.0/16"
azs = ["us-east-1a", "us-east-1b", "us-east-1c"]
}
```
**Module versioning:** Pin module versions to prevent unexpected changes from upstream updates. Use semantic versioning constraints (`~> 5.0` allows patch updates, `>= 5.0, < 6.0` is explicit).
Intermediate
Q: What are Terraform workspaces and when should you use them?
Terraform workspaces allow multiple state files for the same configuration. Each workspace has its own isolated state.
**How they work:**
```bash
terraform workspace new staging
terraform workspace select staging
terraform plan # Uses staging.tfstate
```
**Built-in workspaces:** `default` (always exists), plus any workspaces you create.
**When workspaces are appropriate:**
- Creating multiple ephemeral environments from the same codebase (e.g., feature branches, pull request environments).
- Testing infrastructure changes in a staging workspace before applying to production.
**When workspaces are NOT appropriate (common mistake):**
Workspaces are NOT the recommended way to manage fundamentally different environments (dev, staging, prod) that have different configurations, different resource sizes, different team access controls, or different backends. Using workspaces for this leads to:
- A single state manipulation mistake can affect the wrong environment.
- No isolation between environment backends.
- Configuration becomes complex with lots of `terraform.workspace` conditionals.
**The recommended alternative for multiple environments:** Use separate Terraform configurations per environment (separate directories or separate Terragrunt HCL files) with separate state backends. This provides true isolation.
```
environments/
dev/
main.tf
terraform.tfvars
staging/
main.tf
terraform.tfvars
prod/
main.tf
terraform.tfvars
```
This is what Terragrunt facilitates with DRY patterns, calling shared modules with environment-specific inputs.
Q: Explain Terraform lifecycle rules: create_before_destroy, prevent_destroy, ignore_changes.
Lifecycle meta-arguments customize how Terraform handles specific resource behavior.
**create_before_destroy:**
By default, when a resource must be replaced (e.g., changing an immutable attribute), Terraform destroys the old resource first, then creates the new one. This causes downtime.
```hcl
resource "aws_launch_template" "app" {
# ...
lifecycle {
create_before_destroy = true
}
}
```
With `create_before_destroy = true`, Terraform creates the new resource first, then destroys the old one. Essential for zero-downtime updates to resources like launch templates, SSL certificates, and security groups.
**prevent_destroy:**
Prevents Terraform from destroying a resource even if the configuration change would require it. Acts as a safety guard for critical resources.
```hcl
resource "aws_rds_instance" "production_db" {
# ...
lifecycle {
prevent_destroy = true
}
}
```
Terraform will throw an error if a plan includes destroying this resource. You must explicitly remove this lifecycle rule to delete the resource.
**ignore_changes:**
Tells Terraform to ignore changes to specific attributes when detecting drift. Useful when external processes legitimately modify resource attributes outside Terraform.
```hcl
resource "aws_instance" "app" {
ami = var.ami_id
instance_type = "t3.medium"
lifecycle {
ignore_changes = [
ami, # Ignore AMI changes (managed by patching pipeline)
tags["LastModified"] # Ignore tag changes from external systems
]
}
}
```
**replace_triggered_by (Terraform 1.2+):**
Forces replacement of a resource when referenced resources change, even if the resource itself hasn't changed. Useful for ensuring a new EC2 instance is launched when a launch template changes.
Q: How do you handle Terraform state when importing existing infrastructure?
Terraform import brings existing, manually-created infrastructure under Terraform management. This is one of the most common and tricky operational challenges.
**The problem:**
If you have an existing EC2 instance (created manually) and you write a Terraform resource for it, running `terraform apply` would create a duplicate. Instead, you import the existing resource into Terraform state.
**Classic import workflow:**
1. Write the Terraform resource configuration matching the existing resource.
2. Run `terraform import`:
```bash
terraform import aws_instance.web i-0abc1234def56789
```
3. Run `terraform plan` to see if there are differences between your config and the actual resource.
4. Fix your configuration until `terraform plan` shows no changes.
**Challenges:**
- You must write the configuration before importing, which is tedious for complex resources.
- Computed attributes (created by AWS) must be excluded from your config.
- Some resources have complex import syntax (e.g., RDS multi-parameter import IDs).
**Terraform 1.5+ import blocks (declarative import):**
```hcl
import {
to = aws_instance.web
id = "i-0abc1234def56789"
}
resource "aws_instance" "web" {
# Terraform will generate this config for you
}
```
With `terraform plan -generate-config-out=generated.tf`, Terraform can generate the configuration for you — a major improvement over the manual approach.
**Terraformer / tf-aws-inventory:** Third-party tools that can scan existing AWS accounts and generate both Terraform state and configuration files in bulk. Useful for large-scale migrations.
**Best practice:** Import into a separate state file first (sandbox environment), test the round-trip (plan shows no diff), then migrate to the production state.
Advanced
Q: How do you test Terraform code, and what is Terratest?
Infrastructure testing is as important as application testing but less commonly practiced. Levels of Terraform testing:
**1. Static analysis (fastest, no cloud costs):**
- **tflint:** Lints Terraform code for errors, deprecated syntax, and best practice violations.
- **tfsec / Checkov:** Security static analysis — scans for misconfigured IAM policies, public S3 buckets, unencrypted resources, etc.
- **infracost:** Estimates the cost impact of Terraform changes.
- **terraform validate:** Checks configuration syntax and internal consistency.
**2. Plan-based tests (no infrastructure created):**
- `terraform plan` output can be parsed to verify expected changes.
- Tools like OPA (Open Policy Agent) can enforce policies on plan output.
**3. Integration testing with Terratest (deploys real infrastructure):**
Terratest is a Go library by Gruntwork that deploys real infrastructure, runs tests against it, and tears it down.
```go
func TestVPCModule(t *testing.T) {
opts := &terraform.Options{
TerraformDir: "../../modules/vpc",
Vars: map[string]interface{}{
"name": "test-vpc",
"cidr": "10.0.0.0/16",
},
}
defer terraform.Destroy(t, opts)
terraform.InitAndApply(t, opts)
vpcID := terraform.Output(t, opts, "vpc_id")
assert.NotEmpty(t, vpcID)
// Verify via AWS SDK
vpc := aws.GetVpcById(t, vpcID, "us-east-1")
assert.Equal(t, "10.0.0.0/16", vpc.CidrBlock)
}
```
**4. Terraform 1.6+ native testing framework:**
HashiCorp introduced a native `.tftest.hcl` testing framework that allows writing tests in HCL without Go:
```hcl
# vpc_test.tftest.hcl
run "creates_vpc_with_correct_cidr" {
variables {
name = "test-vpc"
cidr = "10.0.0.0/16"
}
assert {
condition = aws_vpc.main.cidr_block == "10.0.0.0/16"
error_message = "VPC CIDR does not match"
}
}
```
**Test strategy in CI:**
- Static analysis on every PR (fast, free).
- Terratest integration tests on main branch merges (slower, costs money — optimize with parallelism and cleanup).
Also Optimize Your Terraform Resume
Ensure your IaC skills shine through to ATS systems and hiring managers.