Wednesday, 18 June 2025

Terraform Comprehensive Guide with Modules & Interview Q&A

 



1. What is Terraform?

Terraform is an open-source Infrastructure as Code (IaC) tool by HashiCorp that lets you define, provision, and manage infrastructure using configuration files.


2. Key Benefits of Terraform

  • Platform-agnostic (AWS, Azure, GCP, etc.)

  • Declarative language (HCL)

  • Infrastructure automation

  • State management and dependency graph

  • Modular and reusable code


3. Terraform Components

Providers & Backend


terraform { backend "s3" { bucket = "my-tf-state" key = "env/terraform.tfstate" region = "us-east-1" dynamodb_table = "tf-lock" encrypt = true } } provider "aws" { region = var.aws_region }

Resources


resource "aws_instance" "example" { ami = var.ami_id instance_type = var.instance_type count = 2 }

Variables


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

Map Variables & Data Sources Example


variable "vpc_ids" { type = map(string) default = { dev = "vpc-12345" prod = "vpc-67890" } } resource "aws_subnet" "example" { vpc_id = var.vpc_ids[terraform.workspace] cidr_block = "10.0.1.0/24" availability_zone = "us-east-1a" } data "aws_kms_key" "example" { key_id = "alias/my-key" } output "kms_key_arn" { value = data.aws_kms_key.example.arn }

Outputs


output "instance_ip" { value = aws_instance.example[0].public_ip }

4. Terraform Project Structure

Flat structure


terraform-flat/ ├── main.tf ├── variables.tf ├── outputs.tf ├── terraform.tfvars

Modular structure


terraform-modular/ ├── main.tf ├── variables.tf ├── terraform.tfvars ├── modules/ │ ├── vpc/ │ ├── s3/ │ └── ec2/

Environment-specific (dev/prod)


terraform-project/ ├── modules/ │ ├── vpc/ │ ├── s3/ │ └── ec2/ ├── envs/ │ ├── dev/ │ │ ├── main.tf │ │ ├── variables.tf │ │ ├── terraform.tfvars │ │ └── backend.tf │ └── prod/ │ ├── main.tf │ ├── variables.tf │ ├── terraform.tfvars │ └── backend.tf

5. Terraform Modules: Create & Use

What is a Module?

  • A container for multiple resources grouped together.

  • Promotes code reuse and maintainability.


Example: Creating a Simple VPC Module

Folder: modules/vpc/

main.tf

resource "aws_vpc" "this" {
cidr_block = var.vpc_cidr tags = { Name = var.vpc_name } }

variables.tf

variable "vpc_cidr" {
type = string } variable "vpc_name" { type = string }

outputs.tf

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

Using the Module in Root Configuration

main.tf

module "vpc" {
source = "./modules/vpc" vpc_cidr = "10.0.0.0/16" vpc_name = "my-vpc" } output "vpc_id" { value = module.vpc.vpc_id }

Benefits of Modules

  • Reusability across projects/environments

  • Cleaner codebase

  • Easier maintenance and upgrades


6. Locals and Variable Precedence

locals {
environment = "dev" app_name = "myapp" full_name = "${local.app_name}-${local.environment}" }

Variable precedence order (high to low):

  1. CLI flags (-var)

  2. Environment variables

  3. terraform.tfvars

  4. *.auto.tfvars

  5. Default values in variable blocks


7. Terraform Commands Cheat Sheet

CommandPurpose
terraform initInitialize the project
terraform planPreview changes
terraform applyApply infrastructure changes
terraform destroyDelete all resources
terraform validateValidate configuration
terraform fmtFormat configuration files

8. Terraform Variable Types

TypeDescriptionExample
stringText valuetype = string
numberNumeric valuetype = number
boolBoolean true/falsetype = bool
listOrdered listtype = list(string)
mapKey-value pairstype = map(string)
objectComplex structured datatype = object({name=string, age=number})
anyAny typetype = any

9. Terraform Interview Questions & Answers (50)


Basics

1. What is Terraform?
Terraform is an open-source Infrastructure as Code tool for defining and provisioning cloud and on-prem infrastructure using configuration files.

2. What are Terraform providers?
Providers are plugins that allow Terraform to interact with APIs of cloud providers or services (AWS, Azure, GCP, etc.).

3. What is the purpose of the Terraform backend?
It defines where and how Terraform stores its state file and enables state locking.

4. What is Terraform state?
A snapshot of the infrastructure Terraform manages, used to map resources in config to real-world objects.

5. How do you handle multiple environments in Terraform?
By using workspaces, separate directories, or different variable files per environment.


Intermediate

6. What are modules in Terraform?
Modules are containers for multiple resources that promote reusability and better organization.

7. How do you pass variables to Terraform?
Through terraform.tfvars, CLI flags, environment variables, or default values.

8. What is the difference between count and for_each?
count creates multiple instances indexed by number, for_each creates resources from keys in a map or set.

9. How do you manage secrets in Terraform?
Use environment variables, encrypted backends, or secret managers. Avoid hardcoding secrets.

10. What are provisioners?
Provisioners execute scripts or commands on a resource after creation or before destruction.


Advanced

11. What is a Terraform workspace?
An isolated state environment to manage multiple distinct states within the same configuration.

12. How do you import existing infrastructure into Terraform?
With terraform import command to bring existing resources under Terraform management.

13. What are data sources in Terraform?
They allow Terraform to query existing infrastructure or external data for use in configuration.

14. What is a lifecycle meta-argument?
Controls create/update/delete behavior of resources (e.g., prevent destroy).

15. How do you enforce resource dependencies?
Implicit via resource references, or explicit using depends_on.


Expert

16. How do you handle provider versioning?
Specify required_providers block with version constraints in Terraform configuration.

17. What is remote state locking?
Prevents multiple concurrent Terraform executions from corrupting the state.

18. How do you test Terraform configurations?
Using terraform validate, terraform fmt, and external tools like Terratest.

19. What are dynamic blocks?
Blocks that generate nested repeated blocks dynamically based on variables.

20. How can you structure Terraform code for large projects?
Use modules, environment folders, remote backends, and versioned modules.


More Questions

21. What is the difference between declarative and imperative IaC?
Terraform is declarative — you describe what you want, not how to do it.

22. How can Terraform automate infrastructure rollbacks?
By applying previous versions of state or configurations.

23. What happens when you run terraform apply without changes?
Terraform detects no changes and does nothing.

24. How to handle cross-account AWS resources?
Use multiple provider aliases with different credentials.

25. How do you secure Terraform state?
Use encrypted remote backends with strict access controls.


Additional Questions

26. What is the purpose of terraform fmt?
To format Terraform configuration files according to canonical style.

27. How can you split Terraform configurations for team collaboration?
By using modules and separating state files via workspaces or backend configs.

28. What is the difference between terraform plan and terraform apply?
plan shows proposed changes, apply executes them.

29. Can Terraform be used with on-prem resources?
Yes, providers exist for many on-prem technologies.

30. How do you use output values?
To expose resource attributes after apply for other configs or scripts.


More Advanced Questions

31. What are meta-arguments in Terraform?
Special arguments like count, depends_on, lifecycle, which modify resource behavior.

32. How does Terraform handle drift detection?
By comparing real infrastructure with state during plan.

33. How do you upgrade Terraform versions safely?
Test with terraform validate and in isolated environments before production.

34. How do you manage secrets with Terraform Cloud?
Use Terraform Cloud’s variable sets with sensitive flag.

35. What is the purpose of terraform taint?
Marks a resource for forced recreation on next apply.


Final Questions

36. How do locals differ from variables?
Locals are constants within a module, variables are inputs.

37. Can Terraform manage Kubernetes resources?
Yes, using Kubernetes provider.

38. What is a provider alias?
Allows multiple configurations of the same provider.

39. How do you debug Terraform?
Use TF_LOG=DEBUG environment variable.

40. What are dynamic blocks useful for?
Generating repetitive nested blocks conditionally or from lists/maps.

41. How can you reduce code duplication in Terraform?
Use modules and for_each with maps or lists.

42. How does Terraform handle dependencies between resources?
Automatically detects from resource references; explicit dependencies via depends_on.

43. What is the difference between local-exec and remote-exec provisioners?
local-exec runs locally; remote-exec runs commands on the provisioned resource.

44. How do you lock Terraform state?
Using backends like S3 with DynamoDB or Terraform Cloud.

45. Can Terraform be integrated into CI/CD pipelines?
Yes, commonly integrated for automated infrastructure deployment.

46. What is the use of terraform state commands?
To inspect or modify the Terraform state file.

47. How can you output multiple values from a module?
Define multiple outputs in the module.

48. What is the significance of terraform validate?
Checks syntax and internal consistency without contacting providers.

49. How do you handle version control for Terraform state?
Keep state remote and avoid manual edits; use locking and encryption.

50. Can Terraform manage secrets directly?
No, best practice is to use external secret managers or environment variables.




How Provisioners Work

  • They run on the target resource after resource creation (create provisioner) or before resource destruction (destroy provisioner).

  • Most common provisioners are local-exec (runs commands locally where Terraform is running) and remote-exec (runs commands on the remote resource via SSH or WinRM).


Types of Provisioners

ProvisionerDescriptionExample Use Case
local-execRuns commands locally on your machineGenerate config files, trigger local scripts
remote-execRuns commands on remote machine over SSH/WinRMInstall software, configure services
fileCopies files from local machine to remote resourceUpload config files or scripts

Example of remote-exec Provisioner with AWS EC2


resource "aws_instance" "web" { ami = "ami-123456" instance_type = "t2.micro" provisioner "remote-exec" { inline = [ "sudo yum update -y", "sudo yum install -y httpd", "sudo systemctl start httpd", "sudo systemctl enable httpd" ] connection { type = "ssh" user = "ec2-user" private_key = file("~/.ssh/mykey.pem") host = self.public_ip } } }

Explanation:

  • After EC2 is created, the remote-exec provisioner connects via SSH.

  • Runs commands to update OS, install Apache HTTP server, start and enable it.

  • Uses SSH private key and public IP of the instance to connect.


Example of local-exec Provisioner


resource "aws_instance" "web" { ami = "ami-123456" instance_type = "t2.micro" provisioner "local-exec" { command = "echo ${self.public_ip} >> ip_list.txt" } }

Explanation:

  • After EC2 instance is created, runs a local command.

  • Appends the new instance’s public IP to a local file called ip_list.txt.



How does terraform import work?

  • It links an existing real-world resource to a resource block in your Terraform configuration.

  • The resource must already exist.

  • You need to write the resource block in your .tf files matching the resource type.

  • Then run terraform import specifying the resource and its real ID.


How to import

Basic Syntax


terraform import [options] ADDRESS ID
  • ADDRESS: The Terraform resource address (e.g., aws_instance.my_ec2).

  • ID: The provider-specific identifier of the resource (e.g., instance ID for AWS: i-0abcd1234efgh5678).


Example: Importing an existing AWS EC2 instance

  1. Write resource block in Terraform config:


resource "aws_instance" "my_ec2" { # Configuration can be empty initially }
  1. Run import command:


terraform import aws_instance.my_ec2 i-0abcd1234efgh5678
  1. Terraform imports the state and links it with the resource block.

  2. Run terraform plan to see the current state and update the config to match actual resource properties (add missing arguments).


Important Notes

  • Import does not create or modify resources. It only updates Terraform’s state.

  • After import, the resource configuration must be updated to reflect the real resource’s attributes. Otherwise, Terraform might want to modify or destroy resources on next apply.

  • You can import multiple resources by running multiple import commands.

  • Not all resources support import (check Terraform provider docs).

  • Import only affects Terraform state; it does not generate .tf files for you.


Use Case Example: Importing an existing S3 bucket

Terraform config:


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

Import command:



terraform import aws_s3_bucket.my_bucket my-existing-bucket


🗂 Terraform State File Overview

Terraform keeps track of your infrastructure in a state file (terraform.tfstate). This file maps your Terraform code to real infrastructure. Managing state is crucial for team collaboration, resource tracking, and applying changes.


📘 Common terraform state Commands with Use Cases

CommandDescriptionUse CaseExample
terraform state listLists all resources in the state fileUnderstand what resources Terraform is managingterraform state list
terraform state showShows attributes of a resource in stateDebug or inspect a specific resourceterraform state show aws_instance.my_ec2
terraform state rmRemoves a resource from the state file (without destroying it)Terraform is managing a resource you no longer want to controlterraform state rm aws_s3_bucket.my_bucket
terraform state mvMoves items in the state file (rename or refactor)You renamed a resource or moved it to a moduleterraform state mv aws_instance.old_name aws_instance.new_name
terraform state pullDownloads the current stateBackup or inspect current stateterraform state pull > backup.tfstate
terraform state pushUploads a modified state fileRare—used to push manually edited stateterraform state push fixed.tfstate

💡 Real-World Use Case Examples

1. Refactor: Move Resource to a Module

You moved aws_instance.my_ec2 into a module called compute.


terraform state mv aws_instance.my_ec2 module.compute.aws_instance.my_ec2

2. Remove Orphaned Resource

Terraform is managing a resource (e.g., old S3 bucket) that should no longer be part of automation:


terraform state rm aws_s3_bucket.old_bucket

⚠️ The resource is not deleted in the cloud provider—only removed from Terraform state tracking.

3. Import External Resource

You manually created an EC2 instance and want Terraform to manage it:

resource "aws_instance" "external" {
ami = "ami-123456" instance_type = "t2.micro" }

terraform import aws_instance.external i-0abcd1234efgh5678

Then check state:

terraform state show aws_instance.external


No comments:

Post a Comment