Terraform

Terraform

Top Interview Questions

About Terraform

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.


What is Terraform?

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.


Key Features of Terraform

1. Infrastructure as Code (IaC)

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.


2. Declarative Configuration

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.


3. Multi-Cloud and Provider Support

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


4. Dependency Management

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.


5. Execution Plans

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

6. State Management

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


7. Modularity and Reusability

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


How Terraform Works

Terraform workflow typically involves these steps:

  1. Write Configuration
    Define resources using HCL or JSON.

  2. Initialize the Directory

    terraform init
    

    Installs necessary provider plugins.

  3. Create Execution Plan

    terraform plan
    

    Shows changes that will be applied.

  4. Apply Changes

    terraform apply
    

    Provisions or modifies resources.

  5. Manage State
    Terraform tracks resources to update or destroy them safely.


Terraform Providers and Resources

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.


Advantages of Terraform

1. Consistency

Automated provisioning ensures the same environment is deployed every time, reducing configuration drift.

2. Collaboration

Teams can manage infrastructure as code using version control systems like Git.

3. Automation

Terraform eliminates manual intervention, accelerating deployment pipelines.

4. Scalability

Terraform can manage small environments or large-scale infrastructures across multiple clouds.

5. Change Management

Execution plans and state files allow teams to safely make changes and rollbacks.

6. Cost Optimization

Automated resource management prevents unnecessary resource consumption and helps control costs.


Use Cases of Terraform

  1. Cloud Infrastructure Deployment
    Provisioning servers, networks, databases, and storage automatically.

  2. Multi-Cloud Management
    Managing hybrid deployments with consistent configuration.

  3. Continuous Integration / Continuous Deployment (CI/CD)
    Terraform integrates with pipelines to provision environments automatically for development, testing, and production.

  4. Disaster Recovery and Infrastructure Replication
    Quickly recreate infrastructure in another region using code.

  5. Policy as Code
    Enforce compliance and governance using tools like Terraform Sentinel.


Terraform vs Other IaC Tools

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.


Challenges of Terraform

  1. State Management Complexity
    Managing remote state securely can be tricky for large teams.

  2. Learning Curve
    HCL and Terraform concepts can be challenging for beginners.

  3. Provider Limitations
    Some providers may not expose all features or lag in updates.

  4. Debugging Errors
    Complex infrastructures can produce hard-to-trace errors during provisioning.


Terraform Best Practices

  • 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 Enterprise

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.


Terraform in Real-World Scenarios

  1. E-Commerce Platform
    Automate provisioning of servers, databases, and load balancers for high-traffic online stores.

  2. Financial Services
    Deploy compliant, secure, and scalable infrastructure for banking applications.

  3. Healthcare
    Maintain HIPAA-compliant infrastructure for patient data storage and analytics.

  4. DevOps Automation
    Automate CI/CD environments, creating ephemeral environments for testing.


Future of Terraform

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.


Conclusion

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.

Fresher Interview Questions

 

🧠 PART 1: Basics of Terraform

1. What is Terraform?

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.


2. What is Infrastructure as Code (IaC)?

Answer:
IaC is the practice of managing infrastructure through code instead of manual setup.

Benefits:

  • Version control

  • Repeatable deployments

  • Faster provisioning


3. Difference between Terraform and CloudFormation?

Feature Terraform CloudFormation
Multi-cloud Yes AWS only
Language HCL JSON/YAML
State Management Local or remote AWS managed

4. What is HCL?

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"
}

5. What is the difference between declarative and imperative IaC?

Answer:

  • Declarative: Define desired state (Terraform)

  • Imperative: Define steps to achieve state (Ansible procedural style)


πŸ”§ PART 2: Terraform Workflow & Commands

6. Explain Terraform workflow.

Answer:
Typical workflow:

  1. Write configuration (.tf files)

  2. Initialize directory (terraform init)

  3. Plan changes (terraform plan)

  4. Apply changes (terraform apply)

  5. Destroy infrastructure (terraform destroy)


7. What is terraform init?

Answer:
Initializes a Terraform project:

  • Downloads required providers

  • Sets up backend

  • Prepares workspace


8. What is terraform plan?

Answer:

  • Shows what changes Terraform will make without applying them

  • Helps avoid unexpected modifications


9. What is terraform apply?

Answer:
Applies the planned changes to create/update/destroy infrastructure.


10. What is terraform destroy?

Answer:
Removes all resources created by Terraform.


11. What is terraform validate?

Answer:
Checks configuration files for syntax errors and consistency.


12. What is terraform fmt?

Answer:
Formats Terraform files according to standard style.


13. What is terraform show?

Answer:
Displays Terraform state or plan output in a human-readable form.


14. What is terraform output?

Answer:
Shows values of outputs defined in Terraform configuration.


πŸ—„οΈ PART 3: Terraform State & Backends

15. What is Terraform state?

Answer:
Terraform keeps a state file (terraform.tfstate) to track:

  • Resources created

  • Current infrastructure state

  • Dependencies between resources


16. Difference between local and remote state?

Type Local Remote
Storage Local machine S3, Terraform Cloud, GCS
Sharing Single user Multiple users & CI/CD
Locking Not supported Supported (prevents conflicts)

17. What is state locking?

Answer:
Prevents simultaneous apply operations that could corrupt the state.

  • Supported in backends like S3 with DynamoDB, Terraform Cloud


18. What is terraform refresh?

Answer:
Updates the Terraform state file by querying the current infrastructure.


19. Difference between 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

πŸ”Œ PART 4: Terraform Providers & Resources

20. What is a provider in Terraform?

Answer:
Provider is a plugin that manages interactions with APIs of cloud platforms or services.

Example:

  • AWS → aws provider

  • Azure → azurerm provider


21. What is a resource in Terraform?

Answer:
A resource is an infrastructure component defined in Terraform.

Example:

resource "aws_s3_bucket" "my_bucket" {
  bucket = "my-demo-bucket"
}

22. Difference between data sources and resources?

Feature Data Source Resource
Purpose Read existing infra Create/update infra
Example Fetch AMI ID Launch EC2

23. What is the difference between count and for_each?

Answer:

  • count → Create multiple identical resources

  • for_each → Create multiple resources with unique keys/values


24. What are variables in Terraform?

Answer:
Variables make configurations dynamic and reusable.

Example:

variable "instance_type" {
  default = "t2.micro"
}

25. What are outputs in Terraform?

Answer:
Outputs display useful information after terraform apply.

Example:

output "instance_ip" {
  value = aws_instance.my_ec2.public_ip
}

26. What is a module in Terraform?

Answer:
Modules are reusable Terraform configurations to organize code.

Example:

  • network module → VPC, subnets

  • compute module → EC2 instances


27. What is the difference between root module and child module?

Type Root Module Child Module
Definition Main configuration directory Imported/referenced module
Example main.tf modules/network/main.tf

28. How do you version a module?

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"
}

πŸ”„ PART 5: Terraform Advanced Concepts

29. What are workspaces?

Answer:
Workspaces allow multiple state environments in a single configuration.

  • Default workspace → production

  • New workspace → staging/test


30. What is terraform import?

Answer:
Import existing infrastructure into Terraform state without recreating resources.


31. What is terraform taint?

Answer:
Marks a resource for re-creation on next apply.


32. What is terraform graph?

Answer:
Generates a graph of resources and dependencies. Useful for visualization.


33. What is lifecycle meta-argument?

Answer:
Controls resource behavior:

  • create_before_destroy → For zero downtime

  • prevent_destroy → Avoid accidental deletion

  • ignore_changes → Ignore specific attribute changes


34. How do you handle secrets in Terraform?

Answer:

  • Use environment variables

  • Use Terraform Vault provider

  • Store sensitive data in remote backends


35. Difference between Terraform and Ansible?

Feature Terraform Ansible
IaC type Declarative Imperative
State management Yes No
Primary use Infrastructure provisioning Configuration management

πŸ§ͺ PART 6: Practical Scenarios

36. How to create multiple EC2 instances?

Answer:
Using count or for_each:

resource "aws_instance" "web" {
  ami           = "ami-123456"
  instance_type = "t2.micro"
  count         = 3
}

37. How to provision a VPC and subnets?

Answer:

  • Use AWS VPC and subnet resources

  • Organize as a module for reusability


38. How to share Terraform state across team?

Answer:
Use remote backends like:

  • S3 + DynamoDB (AWS)

  • Terraform Cloud


39. How to handle drift detection?

Answer:

  • Use terraform plan to detect manual changes outside Terraform.

  • Apply changes to sync the state.


40. How to structure Terraform code for multiple environments?

Answer:

  • Use separate workspaces or folders: dev/, staging/, prod/

  • Use variable files (.tfvars) for environment-specific values


41. How do you roll back changes in Terraform?

Answer:

  • terraform destroy to remove resources

  • Apply previous configuration/state from version control


42. How to handle dependencies between resources?

Answer:

  • Terraform automatically infers dependencies

  • Explicit dependency using depends_on:

resource "aws_eip" "ip" {
  instance = aws_instance.web.id
  depends_on = [aws_instance.web]
}

43. How to upgrade Terraform version safely?

Answer:

  • Check release notes

  • Upgrade Terraform CLI

  • Use terraform init -upgrade for modules/providers


44. What are Terraform providers?

Answer:
Plugins that manage resources for a specific platform/service.

Examples: AWS, Azure, GCP, Kubernetes


45. Difference between Terraform 0.11 and 0.12+?

Feature 0.11 0.12+
Expressions Limited Full first-class expressions
For loops Limited Full for loops, conditionals
Maps & lists Basic Complex objects

🎯 How to Answer in Interviews

  • 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


πŸ’‘ Cheat Sheet Topics

  • 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

Experienced Interview Questions

 

πŸ”· SECTION 1: FUNDAMENTALS OF TERRAFORM


1. What is Terraform and its use case?

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.


2. Difference between Terraform and CloudFormation

Feature Terraform CloudFormation
Multi-cloud Yes AWS only
Language HCL JSON/YAML
State management Remote/local Managed by AWS
Extensibility Modules & providers Limited

3. Explain Terraform architecture

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


4. What is HCL?

  • HashiCorp Configuration Language

  • Human-readable, supports interpolation, expressions, loops, and conditionals


5. What are Terraform providers?

  • Plugins to interact with APIs of cloud platforms or services

  • Examples: aws, azure, google, kubernetes


6. What are resources in Terraform?

  • Declarative blocks defining infrastructure components

  • Example:

resource "aws_instance" "web" {
  ami           = "ami-0c55b159cbfafe1f0"
  instance_type = "t2.micro"
}

7. What is a Terraform module?

  • Logical group of resources for reusability

  • Types:

    • Root module (main .tf files)

    • Child module (imported via module)


8. Difference between module and resource

Module Resource
Group of resources Single resource definition
Reusable Atomic

9. Terraform State

  • Tracks resources created in real-world infrastructure

  • Stored locally or remotely (S3, GCS, Terraform Cloud)

  • Essential for plan/apply/destroy consistency


10. Difference between Terraform state and plan

  • State: Current infra snapshot

  • Plan: Proposed changes (diff)


πŸ”· SECTION 2: ADVANCED TERRAFORM CONCEPTS


11. Remote state and backend

  • Store state files remotely for team collaboration

  • Examples: S3 with DynamoDB for locking, Terraform Cloud, Azure Storage


12. Locking in Terraform

  • Prevent multiple users from modifying the same infrastructure

  • AWS S3 + DynamoDB → DynamoDB table for lock management


13. Terraform Workspaces

  • Multiple environments using same configuration

  • Example: dev, staging, prod

  • Switch using terraform workspace select <name>


14. Difference between count and for_each

count for_each
Index-based Key-based (map or set)
Less readable for multiple unique resources Supports complex data structures

15. Difference between depends_on and implicit dependency

  • Implicit: Terraform detects based on references

  • Explicit (depends_on): Force ordering, even without references


16. Explain terraform import

  • Import existing infra into Terraform state

  • Example:

terraform import aws_instance.web i-0abcd1234efgh5678

17. Difference between terraform apply and terraform refresh

  • Apply: Create/update/destroy resources

  • Refresh: Update state file to reflect live infra without making changes


18. Terraform lifecycle meta-arguments

  • create_before_destroy: Avoid downtime when replacing resources

  • prevent_destroy: Protect critical resources

  • ignore_changes: Ignore specific attributes


19. Difference between locals and variables

locals variables
Internal computation User-provided input
Cannot be overridden externally Can be set via CLI, env, tfvars

20. Difference between data and resource

  • resource: Creates/updates infrastructure

  • data: Reads existing infra without creating


πŸ”· SECTION 3: TERRAFORM MODULES & BEST PRACTICES


21. How do you structure Terraform modules?

  • Recommended layout:

modules/
   vpc/
       main.tf
       variables.tf
       outputs.tf
   ec2/
       main.tf
       variables.tf
       outputs.tf
environments/
   dev/
       main.tf
   prod/
       main.tf

22. Input and output variables in modules

  • Input: variables.tf → parameterize module

  • Output: outputs.tf → expose values to parent modules


23. What are Terraform registries?

  • Public (Terraform Registry) and private module repositories

  • Example: terraform-aws-modules/vpc/aws


24. How do you version modules and providers?

  • Pin versions for stability:

provider "aws" {
  version = "~> 4.0"
}
module "vpc" {
  source  = "terraform-aws-modules/vpc/aws"
  version = "3.11.0"
}

25. Terraform environment management

  • Use workspaces, variables, and separate state files for dev, staging, prod


26. How to share outputs between modules?

  • Child module output → parent module → other modules

output "vpc_id" {
  value = aws_vpc.main.id
}

27. How to handle secrets in Terraform?

  • Avoid hardcoding credentials

  • Use Vault, AWS Secrets Manager, or environment variables


28. How to handle sensitive outputs?

output "db_password" {
  value     = aws_db_instance.db.password
  sensitive = true
}

πŸ”· SECTION 4: TERRAFORM STATE & DEPLOYMENT STRATEGIES


29. How to manage Terraform state in a team?

  • Remote backend (S3, Terraform Cloud)

  • Enable locking to prevent race conditions


30. Terraform drift detection

  • Run terraform plan → detects infrastructure changes outside Terraform

  • Example: manual change in AWS Console


31. Terraform taint and untaint

  • taint: Mark a resource for recreation

  • untaint: Remove tainted flag


32. How to rollback Terraform changes?

  • Restore previous state file

  • Or destroy problematic resource and reapply


33. Difference between terraform destroy and terraform apply -destroy

  • Both remove resources

  • apply -destroy → declarative way

  • destroy → imperative deletion


34. How to handle large Terraform deployments?

  • Split resources into multiple modules

  • Use remote state references (terraform_remote_state)

  • Use parallelism flag for concurrent resource creation


35. How do you use Terraform in CI/CD?

  • Steps: initfmtvalidateplanapply

  • Tools: GitHub Actions, GitLab CI, Jenkins

  • Example: Auto-apply dev environment, manual approval for prod


πŸ”· SECTION 5: TERRAFORM INTEGRATION & ADVANCED CONCEPTS


36. Terraform vs Ansible

Feature Terraform Ansible
Type Declarative Procedural
State management Tracks infra No state tracking
Primary use Provisioning Configuration management

37. Terraform provisioners

  • local-exec, remote-exec

  • Runs scripts after resource creation

  • Best practice: Use sparingly; prefer configuration management tools


38. Difference between static and dynamic blocks

  • Static: Fixed attributes

  • Dynamic: Loops through maps/lists to generate blocks


39. Terraform import limitations

  • Only imports existing resources

  • Cannot import multiple resources at once

  • Requires manual state file updates


40. How to manage multiple cloud providers?

  • 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"
}

41. Terraform graph command

  • terraform graph → visualize dependency graph of resources

  • Helps debug dependencies and ordering


42. Handling sensitive provider data

  • Use environment variables (AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY)

  • Avoid committing credentials to version control


43. Terraform destroy protection

  • prevent_destroy lifecycle meta-argument for critical resources


44. Difference between Terraform Cloud, Enterprise, and OSS

Type Features
OSS Free, CLI only
Cloud Remote state, collaboration, VCS integration
Enterprise Governance, SSO, private module registry, audit logs

45. Terraform plan output file

  • terraform plan -out=tfplan → Save plan, then apply using terraform apply tfplan

  • Ensures no drift between plan and apply


46. Terraform import vs data sources

  • Import: Bring existing resource into state

  • Data source: Read existing infra without managing it


47. How to handle region or account-specific variables?

  • Use variable files (dev.tfvars, prod.tfvars)

  • Or environment variable overrides


48. Terraform interpolation vs expressions

  • ${var.name} → older style

  • var.name → modern style (Terraform 0.12+)

  • Supports loops, conditionals, concatenation


49. How to manage tagging and naming standards?

  • Use locals and for_each

  • Example: Auto-generate tags for all resources


50. Real-world scenario: Multi-tier web application deployment

  • 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


πŸ”₯ Tips for 4+ Years Experience Terraform Interviews:

  • 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