Top Interview Questions
Terraform is a powerful open-source tool used for Infrastructure as Code (IaC), enabling developers and operations teams to define, provision, and manage infrastructure resources in a declarative and automated way. It has become a cornerstone technology in cloud computing, DevOps, and modern IT operations because it simplifies the management of infrastructure at scale across multiple cloud providers.
Terraform, developed by HashiCorp, allows organizations to automate infrastructure deployment using code rather than manual processes. By writing configuration files, you can define networks, servers, databases, storage, and other infrastructure components in a human-readable format.
Terraform works with multiple providers, including Amazon Web Services (AWS), Microsoft Azure, Google Cloud Platform (GCP), and even on-premises infrastructure like VMware.
Terraform allows you to define your infrastructure using declarative configuration files written in HashiCorp Configuration Language (HCL). This approach provides:
Version control for infrastructure
Reproducibility across environments
Collaboration between teams
Example snippet:
provider "aws" {
region = "us-east-1"
}
resource "aws_instance" "example" {
ami = "ami-0c94855ba95c71c99"
instance_type = "t2.micro"
}
This code provisions an AWS EC2 instance automatically.
Terraform is declarative, meaning you specify what resources you want rather than how to create them. Terraform calculates the necessary steps to achieve the desired state, which reduces errors and simplifies management.
Terraform supports multiple providers, allowing organizations to manage hybrid and multi-cloud environments consistently. Popular providers include:
AWS, Azure, GCP
Kubernetes
VMware vSphere
Cloudflare, Datadog, and many more
Terraform automatically understands resource dependencies and creates or destroys resources in the correct order. For example, a database must exist before an application server that connects to it can be deployed.
Terraform generates an execution plan that shows what changes will be made before applying them. This helps teams review and prevent unintended modifications.
Command example:
terraform plan
Terraform keeps track of infrastructure state using a state file, usually in JSON format. This file allows Terraform to detect changes and apply only what is necessary.
Local state: stored on your machine
Remote state: stored in cloud storage for collaboration
Terraform supports modules, which are reusable and shareable blocks of configuration. Modules promote consistency and reduce repetition.
Example:
A module to deploy a VPC network
A module to create a database cluster
Terraform workflow typically involves these steps:
Write Configuration
Define resources using HCL or JSON.
Initialize the Directory
terraform init
Installs necessary provider plugins.
Create Execution Plan
terraform plan
Shows changes that will be applied.
Apply Changes
terraform apply
Provisions or modifies resources.
Manage State
Terraform tracks resources to update or destroy them safely.
Terraform interacts with the real-world infrastructure through providers. A provider exposes resources, which are actual cloud or on-prem components.
Example:
AWS provider: EC2, S3, RDS
Azure provider: Virtual Machine, Storage Account
Kubernetes provider: Pods, Services, Deployments
Terraform supports hundreds of providers, making it highly flexible for different infrastructures.
Automated provisioning ensures the same environment is deployed every time, reducing configuration drift.
Teams can manage infrastructure as code using version control systems like Git.
Terraform eliminates manual intervention, accelerating deployment pipelines.
Terraform can manage small environments or large-scale infrastructures across multiple clouds.
Execution plans and state files allow teams to safely make changes and rollbacks.
Automated resource management prevents unnecessary resource consumption and helps control costs.
Cloud Infrastructure Deployment
Provisioning servers, networks, databases, and storage automatically.
Multi-Cloud Management
Managing hybrid deployments with consistent configuration.
Continuous Integration / Continuous Deployment (CI/CD)
Terraform integrates with pipelines to provision environments automatically for development, testing, and production.
Disaster Recovery and Infrastructure Replication
Quickly recreate infrastructure in another region using code.
Policy as Code
Enforce compliance and governance using tools like Terraform Sentinel.
| Feature | Terraform | Ansible | CloudFormation |
|---|---|---|---|
| Language | HCL | YAML/Playbooks | JSON/YAML |
| Cloud Support | Multi-cloud | Multi-cloud | AWS only |
| Declarative | Yes | Partially | Yes |
| State Management | Yes | No | Yes |
| Modularity | Yes (modules) | Roles | Nested stacks |
Terraform stands out for its multi-cloud support, declarative approach, and state management.
State Management Complexity
Managing remote state securely can be tricky for large teams.
Learning Curve
HCL and Terraform concepts can be challenging for beginners.
Provider Limitations
Some providers may not expose all features or lag in updates.
Debugging Errors
Complex infrastructures can produce hard-to-trace errors during provisioning.
Use remote state storage for team collaboration (e.g., S3, Terraform Cloud)
Modularize infrastructure for reusability
Use version control for configuration files
Apply changes in a staging environment before production
Maintain proper naming conventions and documentation
Terraform Cloud and Terraform Enterprise are commercial offerings from HashiCorp that provide:
Team collaboration features
Role-based access control
Remote state management
Policy enforcement
Private module registries
These tools help large organizations manage infrastructure at scale securely.
E-Commerce Platform
Automate provisioning of servers, databases, and load balancers for high-traffic online stores.
Financial Services
Deploy compliant, secure, and scalable infrastructure for banking applications.
Healthcare
Maintain HIPAA-compliant infrastructure for patient data storage and analytics.
DevOps Automation
Automate CI/CD environments, creating ephemeral environments for testing.
Terraform continues to evolve with trends like:
Improved multi-cloud orchestration
Integration with Kubernetes and serverless platforms
Enhanced policy-as-code governance
Better collaboration and versioning tools in Terraform Cloud
Terraform is becoming essential for modern DevOps and cloud-native practices, allowing organizations to manage complex, distributed infrastructures efficiently.
Terraform is a revolutionary tool that brings automation, consistency, and scalability to infrastructure management. By treating infrastructure as code, it allows teams to define, provision, and maintain resources in a repeatable and controlled manner.
Its support for multiple cloud providers, modular architecture, execution planning, and robust state management make Terraform indispensable for modern IT organizations. Whether for small startups or global enterprises, Terraform streamlines operations, reduces errors, and enables faster, safer deployment of infrastructure.
Organizations that embrace Terraform can achieve true DevOps agility, manage complex multi-cloud environments, and focus on innovation rather than manual infrastructure management.
Answer:
Terraform is an open-source Infrastructure as Code (IaC) tool by HashiCorp that allows you to define, provision, and manage cloud infrastructure declaratively using configuration files.
Example:
Provision AWS EC2, S3 bucket, or Azure VM using Terraform code.
Answer:
IaC is the practice of managing infrastructure through code instead of manual setup.
Benefits:
Version control
Repeatable deployments
Faster provisioning
| Feature | Terraform | CloudFormation |
|---|---|---|
| Multi-cloud | Yes | AWS only |
| Language | HCL | JSON/YAML |
| State Management | Local or remote | AWS managed |
Answer:
HCL (HashiCorp Configuration Language) is Terraform’s declarative language used to define resources.
Example:
resource "aws_instance" "my_ec2" {
ami = "ami-123456"
instance_type = "t2.micro"
}
Answer:
Declarative: Define desired state (Terraform)
Imperative: Define steps to achieve state (Ansible procedural style)
Answer:
Typical workflow:
Write configuration (.tf files)
Initialize directory (terraform init)
Plan changes (terraform plan)
Apply changes (terraform apply)
Destroy infrastructure (terraform destroy)
terraform init?Answer:
Initializes a Terraform project:
Downloads required providers
Sets up backend
Prepares workspace
terraform plan?Answer:
Shows what changes Terraform will make without applying them
Helps avoid unexpected modifications
terraform apply?Answer:
Applies the planned changes to create/update/destroy infrastructure.
terraform destroy?Answer:
Removes all resources created by Terraform.
terraform validate?Answer:
Checks configuration files for syntax errors and consistency.
terraform fmt?Answer:
Formats Terraform files according to standard style.
terraform show?Answer:
Displays Terraform state or plan output in a human-readable form.
terraform output?Answer:
Shows values of outputs defined in Terraform configuration.
Answer:
Terraform keeps a state file (terraform.tfstate) to track:
Resources created
Current infrastructure state
Dependencies between resources
| Type | Local | Remote |
|---|---|---|
| Storage | Local machine | S3, Terraform Cloud, GCS |
| Sharing | Single user | Multiple users & CI/CD |
| Locking | Not supported | Supported (prevents conflicts) |
Answer:
Prevents simultaneous apply operations that could corrupt the state.
Supported in backends like S3 with DynamoDB, Terraform Cloud
terraform refresh?Answer:
Updates the Terraform state file by querying the current infrastructure.
terraform plan and terraform refresh?| Feature | Plan | Refresh |
|---|---|---|
| Purpose | Shows changes to apply | Updates state only |
| Applies changes | No | No |
| Output | Plan summary | Updated state |
Answer:
Provider is a plugin that manages interactions with APIs of cloud platforms or services.
Example:
AWS → aws provider
Azure → azurerm provider
Answer:
A resource is an infrastructure component defined in Terraform.
Example:
resource "aws_s3_bucket" "my_bucket" {
bucket = "my-demo-bucket"
}
| Feature | Data Source | Resource |
|---|---|---|
| Purpose | Read existing infra | Create/update infra |
| Example | Fetch AMI ID | Launch EC2 |
count and for_each?Answer:
count → Create multiple identical resources
for_each → Create multiple resources with unique keys/values
Answer:
Variables make configurations dynamic and reusable.
Example:
variable "instance_type" {
default = "t2.micro"
}
Answer:
Outputs display useful information after terraform apply.
Example:
output "instance_ip" {
value = aws_instance.my_ec2.public_ip
}
Answer:
Modules are reusable Terraform configurations to organize code.
Example:
network module → VPC, subnets
compute module → EC2 instances
| Type | Root Module | Child Module |
|---|---|---|
| Definition | Main configuration directory | Imported/referenced module |
| Example | main.tf |
modules/network/main.tf |
Answer:
Modules can be versioned using Git tags or Terraform Registry versions.
Reference version in source URL:
module "vpc" {
source = "git::https://github.com/user/vpc.git?ref=v1.0.0"
}
Answer:
Workspaces allow multiple state environments in a single configuration.
Default workspace → production
New workspace → staging/test
terraform import?Answer:
Import existing infrastructure into Terraform state without recreating resources.
terraform taint?Answer:
Marks a resource for re-creation on next apply.
terraform graph?Answer:
Generates a graph of resources and dependencies. Useful for visualization.
Answer:
Controls resource behavior:
create_before_destroy → For zero downtime
prevent_destroy → Avoid accidental deletion
ignore_changes → Ignore specific attribute changes
Answer:
Use environment variables
Use Terraform Vault provider
Store sensitive data in remote backends
| Feature | Terraform | Ansible |
|---|---|---|
| IaC type | Declarative | Imperative |
| State management | Yes | No |
| Primary use | Infrastructure provisioning | Configuration management |
Answer:
Using count or for_each:
resource "aws_instance" "web" {
ami = "ami-123456"
instance_type = "t2.micro"
count = 3
}
Answer:
Use AWS VPC and subnet resources
Organize as a module for reusability
Answer:
Use remote backends like:
S3 + DynamoDB (AWS)
Terraform Cloud
Answer:
Use terraform plan to detect manual changes outside Terraform.
Apply changes to sync the state.
Answer:
Use separate workspaces or folders: dev/, staging/, prod/
Use variable files (.tfvars) for environment-specific values
Answer:
terraform destroy to remove resources
Apply previous configuration/state from version control
Answer:
Terraform automatically infers dependencies
Explicit dependency using depends_on:
resource "aws_eip" "ip" {
instance = aws_instance.web.id
depends_on = [aws_instance.web]
}
Answer:
Check release notes
Upgrade Terraform CLI
Use terraform init -upgrade for modules/providers
Answer:
Plugins that manage resources for a specific platform/service.
Examples: AWS, Azure, GCP, Kubernetes
| Feature | 0.11 | 0.12+ |
|---|---|---|
| Expressions | Limited | Full first-class expressions |
| For loops | Limited | Full for loops, conditionals |
| Maps & lists | Basic | Complex objects |
Explain concept first, then example
Mention real-world cloud use cases
Show familiarity with Terraform commands, HCL, and modules
Use AWS/Azure/GCP examples for clarity
Terraform workflow (init, plan, apply, destroy)
Providers, resources, data sources
Variables, outputs, modules
State management & backends
Workspaces, lifecycle, secrets
Commands: import, taint, refresh, graph
Drift detection & environment management
Answer:
Terraform is an open-source Infrastructure as Code (IaC) tool by HashiCorp.
Provision, manage, and version cloud infrastructure declaratively.
Supports multi-cloud (AWS, Azure, GCP, etc.) and on-premises resources.
Use cases: Provisioning VMs, networking, security policies, Kubernetes clusters, and multi-cloud orchestration.
| Feature | Terraform | CloudFormation |
|---|---|---|
| Multi-cloud | Yes | AWS only |
| Language | HCL | JSON/YAML |
| State management | Remote/local | Managed by AWS |
| Extensibility | Modules & providers | Limited |
Components:
Configuration files (.tf): Declarative resource definitions
Providers: Communicate with cloud platforms
State file (terraform.tfstate): Tracks current infra
Terraform CLI: Commands: init, plan, apply, destroy
Modules: Reusable code blocks
HashiCorp Configuration Language
Human-readable, supports interpolation, expressions, loops, and conditionals
Plugins to interact with APIs of cloud platforms or services
Examples: aws, azure, google, kubernetes
Declarative blocks defining infrastructure components
Example:
resource "aws_instance" "web" {
ami = "ami-0c55b159cbfafe1f0"
instance_type = "t2.micro"
}
Logical group of resources for reusability
Types:
Root module (main .tf files)
Child module (imported via module)
| Module | Resource |
|---|---|
| Group of resources | Single resource definition |
| Reusable | Atomic |
Tracks resources created in real-world infrastructure
Stored locally or remotely (S3, GCS, Terraform Cloud)
Essential for plan/apply/destroy consistency
State: Current infra snapshot
Plan: Proposed changes (diff)
Store state files remotely for team collaboration
Examples: S3 with DynamoDB for locking, Terraform Cloud, Azure Storage
Prevent multiple users from modifying the same infrastructure
AWS S3 + DynamoDB → DynamoDB table for lock management
Multiple environments using same configuration
Example: dev, staging, prod
Switch using terraform workspace select <name>
count and for_each| count | for_each |
|---|---|
| Index-based | Key-based (map or set) |
| Less readable for multiple unique resources | Supports complex data structures |
depends_on and implicit dependencyImplicit: Terraform detects based on references
Explicit (depends_on): Force ordering, even without references
terraform importImport existing infra into Terraform state
Example:
terraform import aws_instance.web i-0abcd1234efgh5678
terraform apply and terraform refreshApply: Create/update/destroy resources
Refresh: Update state file to reflect live infra without making changes
create_before_destroy: Avoid downtime when replacing resources
prevent_destroy: Protect critical resources
ignore_changes: Ignore specific attributes
locals and variables| locals | variables |
|---|---|
| Internal computation | User-provided input |
| Cannot be overridden externally | Can be set via CLI, env, tfvars |
data and resourceresource: Creates/updates infrastructure
data: Reads existing infra without creating
Recommended layout:
modules/
vpc/
main.tf
variables.tf
outputs.tf
ec2/
main.tf
variables.tf
outputs.tf
environments/
dev/
main.tf
prod/
main.tf
Input: variables.tf → parameterize module
Output: outputs.tf → expose values to parent modules
Public (Terraform Registry) and private module repositories
Example: terraform-aws-modules/vpc/aws
Pin versions for stability:
provider "aws" {
version = "~> 4.0"
}
module "vpc" {
source = "terraform-aws-modules/vpc/aws"
version = "3.11.0"
}
Use workspaces, variables, and separate state files for dev, staging, prod
Child module output → parent module → other modules
output "vpc_id" {
value = aws_vpc.main.id
}
Avoid hardcoding credentials
Use Vault, AWS Secrets Manager, or environment variables
output "db_password" {
value = aws_db_instance.db.password
sensitive = true
}
Remote backend (S3, Terraform Cloud)
Enable locking to prevent race conditions
Run terraform plan → detects infrastructure changes outside Terraform
Example: manual change in AWS Console
taint: Mark a resource for recreation
untaint: Remove tainted flag
Restore previous state file
Or destroy problematic resource and reapply
terraform destroy and terraform apply -destroyBoth remove resources
apply -destroy → declarative way
destroy → imperative deletion
Split resources into multiple modules
Use remote state references (terraform_remote_state)
Use parallelism flag for concurrent resource creation
Steps: init → fmt → validate → plan → apply
Tools: GitHub Actions, GitLab CI, Jenkins
Example: Auto-apply dev environment, manual approval for prod
| Feature | Terraform | Ansible |
|---|---|---|
| Type | Declarative | Procedural |
| State management | Tracks infra | No state tracking |
| Primary use | Provisioning | Configuration management |
local-exec, remote-exec
Runs scripts after resource creation
Best practice: Use sparingly; prefer configuration management tools
Static: Fixed attributes
Dynamic: Loops through maps/lists to generate blocks
Only imports existing resources
Cannot import multiple resources at once
Requires manual state file updates
Define multiple providers in same config
Use provider alias for different regions/accounts
provider "aws" {
region = "us-east-1"
}
provider "aws" {
alias = "us-west"
region = "us-west-2"
}
terraform graph → visualize dependency graph of resources
Helps debug dependencies and ordering
Use environment variables (AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY)
Avoid committing credentials to version control
prevent_destroy lifecycle meta-argument for critical resources
| Type | Features |
|---|---|
| OSS | Free, CLI only |
| Cloud | Remote state, collaboration, VCS integration |
| Enterprise | Governance, SSO, private module registry, audit logs |
terraform plan -out=tfplan → Save plan, then apply using terraform apply tfplan
Ensures no drift between plan and apply
Import: Bring existing resource into state
Data source: Read existing infra without managing it
Use variable files (dev.tfvars, prod.tfvars)
Or environment variable overrides
${var.name} → older style
var.name → modern style (Terraform 0.12+)
Supports loops, conditionals, concatenation
Use locals and for_each
Example: Auto-generate tags for all resources
Modules: vpc, subnet, security_group, ec2, rds
Remote state for collaboration
CI/CD: Auto-deploy dev, manual approval for prod
Outputs: Public IP, database endpoint
Understand state, modules, and backend management thoroughly
Show experience with multi-environment setups
Discuss drift detection, CI/CD, and best practices
Highlight Terraform vs other IaC tools
Be prepared for scenario-based questions: multi-cloud, scaling, rollback