Terrafrom FAQ

1. What is Terraform and why do we use it?
Interview Answer:
Terraform is an open-source Infrastructure as Code (IaC) tool developed by HashiCorp.
It allows us to define, provision, and manage infrastructure across cloud and on-prem platforms using declarative configuration files.
Why we use Terraform:
To automate infrastructure provisioning
To maintain consistent environments (dev, test, prod)
To enable version control of infrastructure
To manage multi-cloud infrastructure
To reduce manual errors and improve reliability
One-liner (if interviewer interrupts):
Terraform helps us manage infrastructure safely, repeatably, and at scale using code.
2. How is Terraform different from CloudFormation?
Interview Answer:
Terraform is a cloud-agnostic IaC tool, whereas CloudFormation is AWS-specific.
Key Differences:
| Terraform | CloudFormation |
| Multi-cloud (AWS, Azure, GCP, etc.) | AWS only |
| Uses HCL (HashiCorp Configuration Language) | Uses JSON or YAML |
| Has a state file to track resources | AWS manages state internally |
| Supports modules & providers | Uses stacks & nested stacks |
| Open source | AWS managed service |
When to choose Terraform?
Multi-cloud or hybrid environments
Standardized tooling across teams
When to choose CloudFormation?
Pure AWS ecosystem
Deep AWS integration
3. What is Infrastructure as Code (IaC)?
Interview Answer:
Infrastructure as Code (IaC) is the practice of managing infrastructure using code instead of manual processes.
Key benefits:
Automation – no manual setup
Consistency – same infra every time
Version control – track infra changes using Git
Scalability – easily replicate environments
Disaster recovery – recreate infra quickly
Example:
Creating an EC2 instance using Terraform instead of clicking in the AWS Console.
4. Explain Terraform workflow (init, plan, apply, destroy)
Interview Answer:
Terraform follows a four-step workflow:
1. terraform init
Initializes the working directory
Downloads required providers
Configures backend for state storage
2. terraform plan
Shows what changes Terraform will make
Compares desired state vs current state
Used for review and approval
3. terraform apply
Creates or updates infrastructure
Applies the execution plan
Updates the state file
4. terraform destroy
Destroys all managed infrastructure
Used for cleanup or cost control
Short version:
Init → Validate → Plan → Apply → Destroy
5. What is a Terraform provider?
Interview Answer:
A Terraform provider is a plugin that allows Terraform to interact with APIs of cloud platforms or services.
Examples:
aws– AWS resourcesazurerm– Azure resourcesgoogle– GCP resourceskubernetes– Kubernetes objects
What providers do:
Authenticate with the platform
Create, read, update, delete resources
Translate Terraform code into API calls
Example:
provider "aws" {
region = "ap-south-1"
}
Bonus Interview Tip (Very Important)
End your answers with real-world usage, for example:
“In my projects, I use Terraform with remote state in S3 and state locking via DynamoDB, and deploy infrastructure using GitHub Actions.”
This shows hands-on experience, not just theory.
6. What is a Terraform resource?
Interview Answer:
A Terraform resource is a block that defines an infrastructure component that Terraform will create, update, or delete.
Examples of resources:
EC2 instance
S3 bucket
VPC
Kubernetes Deployment
Example:
resource "aws_instance" "web" {
ami = "ami-0abcd1234"
instance_type = "t2.micro"
}
Key point:
Resources represent things Terraform manages.
7. What are Terraform data sources?
Interview Answer:
Terraform data sources are used to fetch and read existing infrastructure information without creating or modifying resources.
Use cases:
Fetch an existing VPC
Read an existing AMI
Get existing security group IDs
Reference infrastructure created outside Terraform
Example:
data "aws_ami" "ubuntu" {
most_recent = true
owners = ["099720109477"]
}
Key point:
Data sources are read-only.
8. Difference between resource and data source
Interview Answer:
| Resource | Data Source |
| Creates & manages infrastructure | Reads existing infrastructure |
| Terraform controls lifecycle | No lifecycle control |
| Supports create/update/delete | Read-only |
| Appears in state as managed | Appears as referenced data |
One-liner:
Resources build infrastructure, data sources look up existing infrastructure.
9. What is the Terraform state file?
Interview Answer:
The Terraform state file (
terraform.tfstate) is a file that tracks the current state of infrastructure managed by Terraform.
What it stores:
Resource IDs
Metadata
Dependencies
Mapping between Terraform code and real infrastructure
Purpose:
Terraform uses the state file to determine what already exists and what needs to change.
10. Why is the Terraform state file important?
Interview Answer:
The state file is critical because Terraform is a state-based tool.
Importance:
Tracks infrastructure accurately
Enables incremental changes
Prevents resource duplication
Improves performance (no full API scans)
Required for plan and apply operations
Enables team collaboration when stored remotely
Best practice:
Store state remotely in S3 with DynamoDB state locking.
backend "s3" {
bucket = "terraform-state-bucket"
key = "prod/terraform.tfstate"
region = "ap-south-1"
dynamodb_table = "terraform-locks"
}
Pro Interview Tip (Use This Line ⭐)
“In production, we never store state locally. We use remote state with locking to avoid conflicts and state corruption.”
This instantly boosts your seniority impression.
If you want next:
Questions 11–15 (modules, variables, outputs, tfvars)
Real-world Terraform scenarios
Tricky Terraform interview questions
Terraform for 5+ years DevOps role
11. What happens if the Terraform state file is deleted?
Interview Answer:
If the Terraform state file is deleted, Terraform loses track of existing infrastructure.
Impact:
Terraform thinks no resources exist
terraform planshows all resources as newRisk of duplicate resource creation
terraform destroycannot delete existing infraInfrastructure becomes orphaned
Recovery options:
Restore from state backup
Re-import resources using
terraform importRebuild infrastructure if no backup exists
Key line:
Terraform cannot safely manage infrastructure without state.
12. Where do you store Terraform state in production?
Interview Answer:
In production, Terraform state should always be stored in a remote backend, never locally.
Common production setups:
AWS: S3 + DynamoDB (state locking)
Azure: Azure Storage Account
GCP: Google Cloud Storage
Terraform Cloud / Enterprise
Example (AWS best practice):
backend "s3" {
bucket = "prod-terraform-state"
key = "eks/terraform.tfstate"
region = "ap-south-1"
dynamodb_table = "terraform-state-lock"
encrypt = true
}
13. What is a remote backend?
Interview Answer:
A remote backend is a Terraform backend that stores the state file outside the local system, typically in a shared and secure storage.
Benefits:
Centralized state management
Team collaboration
State locking support
Improved security
Enables CI/CD pipelines
Examples:
S3
Azure Blob Storage
GCS
Terraform Cloud
14. Difference between local backend and remote backend
Interview Answer:
| Local Backend | Remote Backend |
| State stored on local machine | State stored in remote storage |
| Not safe for teams | Team-friendly |
| No locking | Supports state locking |
| Risk of state loss | Highly durable |
| Suitable for learning/testing | Mandatory for production |
One-liner:
Local backend is for practice, remote backend is for production.
15. What is state locking and why is it needed?
Interview Answer:
State locking prevents multiple Terraform operations from modifying the same state file at the same time.
Why it’s needed:
Avoids race conditions
Prevents state corruption
Ensures consistency
Protects production infrastructure
How it works (AWS):
DynamoDB table acts as a lock
Only one
applyordestroycan run at a timeOthers must wait until the lock is released
Key line interviewers love:
State locking is critical in CI/CD and multi-engineer environments.
16. What is terraform.tfstate?
Interview Answer:
terraform.tfstateis the default state file used by Terraform to store the current state of managed infrastructure.
It contains:
Resource IDs (EC2 ID, VPC ID, etc.)
Resource attributes and metadata
Dependency mappings
Provider-specific information
Key point:
Terraform uses this file to map Terraform code to real infrastructure.
17. How do you secure the Terraform state file?
Interview Answer:
Securing the state file is critical because it may contain sensitive data like passwords, tokens, and private IPs.
Best practices:
Use remote backend
Enable encryption at rest
- AWS S3: SSE-S3 or SSE-KMS
Restrict access using IAM policies
Enable versioning for recovery
Avoid storing secrets in plain text
Use Vault / Secrets Manager for secrets
Enable logging and auditing
Key line:
State security is as important as application secrets.
18. How do you enable state locking in AWS?
Interview Answer:
State locking in AWS is enabled using DynamoDB along with an S3 remote backend.
Steps:
Create an S3 bucket for state
Create a DynamoDB table with:
- Partition key:
LockID(String)
- Partition key:
Configure backend:
backend "s3" {
bucket = "terraform-prod-state"
key = "prod/terraform.tfstate"
region = "ap-south-1"
dynamodb_table = "terraform-locks"
encrypt = true
}
Result:
Only one Terraform operation can modify the state at a time.
19. What is state drift?
Interview Answer:
State drift occurs when the actual infrastructure changes outside of Terraform, causing a mismatch between:
Terraform state
Terraform configuration
Real infrastructure
Common causes:
Manual changes in cloud console
Scripts modifying resources
Auto-scaling or external tools
Cloud provider changes
Example:
Someone manually changes EC2 instance type from the AWS Console.
20. How do you detect and fix drift?
Interview Answer:
Detect drift:
Run
terraform planTerraform compares:
Desired configuration
State file
Real infrastructure
Fix drift options:
Revert manual changes
terraform applyAccept changes
- Update Terraform code to match reality
Import missing resources
terraform importRefresh state (read-only)
terraform plan -refresh-only
Best practice:
Restrict manual changes and enforce IaC-only updates via CI/CD.
21. What is terraform refresh?
Interview Answer:
terraform refreshupdates the Terraform state file to match the real infrastructure, without making any changes to resources.
Key points:
Reads current infrastructure state
Updates only the state file
Does not modify infrastructure
Used to detect drift
⚠️ Note (important in interviews):
terraform refreshis deprecated in newer versions and replaced by:
terraform plan -refresh-only
22. What is terraform state list?
Interview Answer:
terraform state listdisplays all resources currently tracked in the Terraform state file.
Use cases:
Verify what Terraform is managing
Debug state issues
Check imported resources
Example:
terraform state list
23. What is terraform state mv?
Interview Answer:
terraform state mvis used to move or rename resources within the Terraform state file without recreating them.
Common use cases:
Refactoring Terraform code
Moving resources into modules
Renaming resource blocks
Example:
terraform state mv aws_instance.web aws_instance.app
Key benefit:
Prevents resource destruction during refactoring.
24. What is terraform state rm?
Interview Answer:
terraform state rmremoves a resource from Terraform state only, without deleting the actual infrastructure.
When to use:
Resource managed outside Terraform
Temporary removal from Terraform control
Cleanup incorrect state entries
Example:
terraform state rm aws_s3_bucket.logs
⚠️ Warning (interview gold):
After removal, Terraform no longer manages that resource.
25. When should you manually edit the state file (if ever)?
Interview Answer:
Manually editing the state file is strongly discouraged and should be done only as a last resort.
Acceptable scenarios (rare):
State corruption
Critical recovery when no backup exists
Directed by Terraform support
Best practices instead:
Use
terraform importUse
terraform state mvUse
terraform state rmRestore from versioned backups
Golden interview line:
In production, we never manually edit state unless it’s an emergency and fully backed up.
26. What are Terraform variables?
Interview Answer:
Terraform variables allow us to parameterize configurations, so the same code can be reused across different environments.
Benefits:
Reusability
Flexibility
Environment-specific values
Cleaner code
Example:
variable "instance_type" {
type = string
default = "t2.micro"
}
27. Types of variables in Terraform
Interview Answer:
Terraform supports:
Input variables – accept values from users
Local variables (locals) – computed values inside config
Output variables – expose values after apply
Input variable types:
string
number
bool
list
map
object
tuple
28. Difference between variable, locals, and output
| Variable | Locals | Output |
| Input to Terraform | Internal computed values | Exposes values |
| Can be overridden | Cannot be overridden | Read-only |
| Used for customization | Used to reduce duplication | Used by users or other modules |
One-liner:
Variables come in, locals are used inside, outputs go out.
29. What is terraform.tfvars?
Interview Answer:
terraform.tfvarsis a file used to assign values to input variables.
Example:
instance_type = "t3.medium"
region = "ap-south-1"
Key point:
Terraform automatically loads
terraform.tfvars.
30. Variable precedence order
Interview Answer (important):
Highest → Lowest priority:
-varcommand-line flag-var-fileEnvironment variables (
TF_VAR_*)terraform.tfvars*.auto.tfvarsDefault values in variable block
Interview gold line:
CLI values always override everything.
31. How do you pass variables at runtime?
Interview Answer:
- Command line:
terraform apply -var="instance_type=t3.large"
- Var file:
terraform apply -var-file=prod.tfvars
- Environment variables:
export TF_VAR_region=ap-south-1
32. How do you use environment variables in Terraform?
Interview Answer:
Terraform automatically reads environment variables prefixed with
TF_VAR_.
Example:
export TF_VAR_instance_type=t3.micro
Terraform variable:
variable "instance_type" {}
33. Sensitive variables – how do you handle secrets?
Interview Answer:
Secrets should never be hard-coded in Terraform files.
Best practices:
Use
sensitive = trueUse Secrets Manager / Vault
Pass secrets via environment variables
Encrypt remote state
Restrict IAM access
variable "db_password" {
type = string
sensitive = true
}
Key line:
Terraform should reference secrets, not store them.
34. What is a Terraform module?
Interview Answer:
A Terraform module is a collection of Terraform files that encapsulate a reusable infrastructure component.
Examples:
VPC module
EKS module
EC2 module
35. Why should we use modules?
Interview Answer:
Modules help with:
Code reuse
Standardization
Maintainability
Scalability
Reduced duplication
One-liner:
Modules make Terraform code clean, reusable, and scalable.
36. Difference between root module and child module
| Root Module | Child Module |
| Main working directory | Reusable sub-modules |
| Executed directly | Called by root |
| Environment-specific | Generic logic |
37. How do you structure Terraform modules in real projects?
Interview Answer:
terraform/
├── modules/
│ ├── vpc/
│ ├── ec2/
│ ├── eks/
├── envs/
│ ├── dev/
│ ├── stage/
│ ├── prod/
Each env has:
terraform.tfvars
38. How do you version Terraform modules?
Interview Answer:
Use Git tags
Reference version in module source
module "vpc" {
source = "git::https://github.com/org/vpc-module.git?ref=v1.2.0"
}
Best practice:
Never use
mainorlatestin production.
39. How do you reuse modules across environments?
Interview Answer:
Same module
Different
tfvarsfilesDifferent backend state
module "vpc" {
source = "../../modules/vpc"
cidr_block = var.vpc_cidr
}
40. What are public and private modules?
Interview Answer:
| Public Modules | Private Modules |
| Open-source | Organization-specific |
| Terraform Registry | GitHub / GitLab / Bitbucket |
| Community-maintained | Internally maintained |
Example:
source = "terraform-aws-modules/vpc/aws"
41. How do you pass variables between modules?
By using input variables in the child module and passing values from the root module.
module "vpc" {
source = "./modules/vpc"
cidr_block = var.vpc_cidr
}
42. What is module output and how do you use it?
Module outputs expose values from a module so other modules or root config can use them.
output "vpc_id" {
value = aws_vpc.main.id
}
Usage:
module.vpc.vpc_id
43. What is count?
countcreates multiple instances of a resource using an index.
count = 3
44. What is for_each?
for_eachcreates resources using a map or set, each with a unique key.
for_each = var.subnets
45. Difference between count and for_each
| count | for_each |
| Index-based | Key-based |
| List-based | Map / set |
| Less stable | More predictable |
Interview line:
Use
for_eachfor real-world resources.
46. What is depends_on?
Forces explicit resource dependency.
depends_on = [aws_iam_role.role]
47. What are dynamic blocks?
Used to generate nested blocks dynamically.
dynamic "ingress" {
for_each = var.rules
}
48. What are lifecycle rules?
Control how Terraform creates, updates, or destroys resources.
49. Explain create_before_destroy
Creates new resource before deleting the old one to avoid downtime.
create_before_destroy = true
50. What is ignore_changes?
Tells Terraform to ignore changes to specific attributes.
ignore_changes = [tags]
51. What are provisioners?
Used to execute scripts or commands on resources.
52. Types of provisioners
filelocal-execremote-exec
53. Why are provisioners discouraged?
They are imperative, fragile, and break idempotency.
Best practice:
Use cloud-init, AMIs, or configuration tools instead.
54. Difference between null_resource and provisioner
| null_resource | provisioner |
| Resource wrapper | Execution method |
| Used for orchestration | Executes commands |
55. What are Terraform functions?
Built-in helpers to transform and calculate values.
56. Commonly used Terraform functions
length()lookup()merge()flatten()contains()try()join()split()
57. Difference between lookup and map
lookup()safely retrieves values from a map with a default.
lookup(var.tags, "env", "dev")
58. What is merge function?
Combines multiple maps into one.
merge(map1, map2)
59. What is flatten?
Converts nested lists into a single list.
60. What is length?
Returns the number of elements.
length(var.subnets)
61. What is contains?
Checks if a value exists in a list.
contains(var.envs, "prod")
62. What is try() and why is it used?
Returns the first valid value, avoids failures.
try(var.a, var.b, "default")
63. What is conditional expression in Terraform?
condition ? true_value : false_value
Used for environment logic.
64. How do you manage multiple environments?
Using separate state files, tfvars, and CI pipelines.
65. Workspaces vs separate state files – which is better?
Separate state files are better for production.
66. What are Terraform workspaces?
Allow multiple states from the same config.
terraform workspace new dev
67. Limitations of workspaces
Shared backend
Risky for prod
Limited isolation
68. How do you promote code from dev to prod?
Same code → different tfvars → CI/CD approval → prod apply.
69. How do you avoid accidental deletion in prod?
prevent_destroyIAM restrictions
Manual approvals
Separate state
70. How do you create EC2 using Terraform?
resource "aws_instance" "ec2" {
ami = "ami-xyz"
instance_type = "t3.micro"
}
71. How do you create VPC using Terraform?
resource "aws_vpc" "main" {
cidr_block = "10.0.0.0/16"
}
72. How do you manage IAM roles and policies?
Using
aws_iam_role,aws_iam_policy, and attachments.
73. How do you create ALB + ASG?
Use:
ALB
Target Group
Launch Template
Auto Scaling Group
(Usually via modules)
74. How do you manage S3 bucket policies?
resource "aws_s3_bucket_policy" {}
75. How do you enable encryption in Terraform?
Enable encryption in resource config (S3, EBS, RDS, KMS).
76. How do you use Terraform with EKS?
Provision EKS infra + use Kubernetes & Helm providers.
77. How do you manage security groups efficiently?
Use modules, reusable rules, and variables.
78. How do you reference one resource from another?
aws_vpc.main.id
79. How do you handle AWS credentials in Terraform?
Use IAM roles, environment variables, or profiles
Never hard-code credentials
80. How do you integrate Terraform with Jenkins?
Jenkins pipeline stages:
terraform initterraform planApproval
terraform apply
81. What Terraform commands are used in CI/CD?
Common CI/CD commands:
terraform initterraform validateterraform fmt -checkterraform planterraform apply(after approval)terraform destroy(rare, controlled)
82. How do you prevent terraform apply without approval?
Use manual approval gates in CI/CD.
Ways:
Jenkins input step
GitHub Actions
environmentapprovalsSeparate
planandapplyjobsProtected branches
83. What is terraform plan used for in pipelines?
To preview infrastructure changes before applying.
Why it’s critical:
Detects drift
Shows add/change/destroy
Used for approval decisions
Prevents accidental deletions
84. How do you handle Terraform in GitHub Actions?
Using a workflow with separate plan and apply jobs.
Typical steps:
Checkout code
Setup Terraform
Configure AWS creds (OIDC)
Run
init,planApply only on approval / main branch
85. How do you avoid concurrent Terraform runs?
By using state locking and pipeline controls.
Best practices:
Remote backend with locking (S3 + DynamoDB)
One apply job per environment
Disable parallel prod applies
86. Common Terraform errors you faced
Examples:
State lock errors
Provider version conflicts
Dependency cycles
Resource already exists
Permission denied (IAM)
Invalid CIDR / AZ errors
87. Provider version conflict – how do you fix it?
By pinning provider versions.
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 5.0"
}
}
Then run:
terraform init -upgrade
88. Resource already exists error – what do you do?
Import the resource or update state.
Options:
terraform importUse
terraform state rm(carefully)Verify naming conflicts
89. How do you import existing resources into Terraform?
Define the resource in code, then import.
terraform import aws_instance.web i-123456
90. What is terraform import?
It adds existing infrastructure into Terraform state without creating it.
91. What is dependency cycle error?
Happens when resources depend on each other circularly.
Fix:
Redesign dependencies
Use
depends_oncarefullySplit resources/modules
92. How do you debug Terraform issues?
Techniques:
terraform planterraform validateEnable debug logs:
TF_LOG=DEBUG terraform apply
- Check state & provider docs
93. How do you rollback Terraform changes?
Terraform has no automatic rollback.
Rollback strategies:
Re-apply previous Git commit
Use versioned state
Restore from backups
Blue-green deployments
94. What happens if terraform apply fails midway?
Terraform:
Updates state only for successful resources
Leaves partial infrastructure
Lock is released
Action:
Fix issue → re-run apply
95. Terraform best practices you follow
Key practices:
Remote state + locking
Module-based design
Version pinning
No hard-coded secrets
CI/CD enforcement
Separate env states
Code reviews
96. How do you secure Terraform code?
By:
Remote encrypted state
IAM least privilege
Secrets outside code
Repo access controls
Static analysis (tfsec, checkov)
97. How do you manage secrets in Terraform?
Terraform references secrets, doesn’t store them.
Tools:
AWS Secrets Manager
Vault
Environment variables
Encrypted backends
98. Do you store credentials in Terraform files?
❌ Never.
Instead:
IAM roles
OIDC (GitHub Actions)
Env variables
AWS profiles
99. How do you prevent exposing secrets in logs?
By:
Using
sensitive = trueAvoiding outputs for secrets
Securing CI logs
Using secrets managers
100. How do you follow least privilege in Terraform?
By:
Minimal IAM policies
Environment-specific roles
Separate roles for plan/apply
No wildcard permissions
101. How would you migrate manually created AWS resources to Terraform?
Step-by-step:
Write Terraform resource blocks
Import existing resources
Run plan to verify
Commit to Git
Enforce IaC-only changes
102. How do you refactor Terraform code without downtime?
Use:
terraform state mvcreate_before_destroyBlue-green patterns
Modules refactoring
103. How do you handle large Terraform codebases?
By:
Splitting into modules
Environment directories
Clear ownership
CI validation
Documentation
104. How do you manage Terraform in a team?
Using:
Git workflows
Code reviews
Remote state
Locking
CI/CD pipelines
Access controls
105. How do you lock Terraform apply in production?
By:
Remote state locking
Manual approvals
IAM restrictions
Separate prod pipelines
106. How do you destroy only specific resources?
Use:
terraform destroy -target=aws_instance.web
⚠️ Use sparingly.
107. How do you handle blue-green deployment using Terraform?
Create parallel infrastructure, switch traffic (ALB/DNS), then destroy old infra.
108. How do you manage Terraform version upgrades?
Safely by:
Pinning Terraform version
Testing in lower envs
Reading changelogs
Upgrading providers carefully
CI validation
⭐ Final Interview Power Line
“We run Terraform through CI/CD with approvals, remote state locking, strict IAM, and zero manual changes in production.”

