Terraform
Infrastructure as Code

Terraform

A complete guide to Terraform: HCL syntax, providers, resources, the core workflow (init, plan, apply), state files, and remote locking.

Every major cloud provider offers its own native Infrastructure as Code service: AWS has CloudFormation, Google Cloud has Cloud Deployment Manager, and Microsoft Azure has ARM and Bicep. But what happens when an organization uses AWS for compute, Google Cloud for BigQuery analytics, Cloudflare for DNS, and Datadog for monitoring? Using only proprietary tools means learning four different languages, maintaining four separate deployment pipelines, and training engineers on different vendor tools. It also locks teams tightly into a single vendor's ecosystem. Created by HashiCorp in 2014, Terraform (along with its open-source fork OpenTofu) is the industry standard for multi-cloud infrastructure provisioning. Using a clean, readable language called HashiCorp Configuration Language (HCL), Terraform lets you provision and manage AWS, Azure, GCP, Kubernetes, GitHub, Cloudflare, and thousands of other services using a single, unified workflow and state engine.

Definition

Terraform is an open-source Infrastructure as Code tool that allows engineers to define, provision, and manage cloud and on-premises infrastructure resources safely and declaratively using HashiCorp Configuration Language (HCL).

Why It Matters

Terraform unifies infrastructure provisioning across different cloud vendors. Instead of maintaining separate bash scripts and vendor-specific templates, teams use one consistent tool and workflow everywhere. One of Terraform's greatest strengths is its execution plan (`terraform plan`). Before making any live changes to your cloud accounts, Terraform calculates and displays the exact list of resources it will create, modify, or destroy. This dry-run preview prevents accidental deletions and costly misconfigurations before they ever touch production.

How It Works

Terraform operates through a modular provider architecture and a state-driven reconciliation loop: 1. Core Engine and Providers: • Terraform Core: The main binary engine. It reads your HCL configuration files, manages variables, maintains the state database, and computes a Directed Acyclic Graph (DAG) of resource dependencies so resources are created in the right order. • Providers: Modular plugins (such as AWS, GCP, Azure, Kubernetes, Datadog) that translate Terraform resource declarations into cloud REST API calls. Providers handle authentication, API versions, and resource lifecycles. 2. The Core Four-Step Workflow: • `terraform init`: Initializes your project directory, downloads required provider plugins from the registry, and connects to your remote backend. • `terraform plan`: Performs a dry-run. It refreshes live state via cloud APIs, compares live state against your HCL code, and displays a color-coded diff showing what will be created (`+`), updated in place (`~`), or destroyed (`-`). • `terraform apply`: Executes the proposed changes by making the necessary API calls to cloud providers, then records the new resource IDs in the state file. • `terraform destroy`: Safely removes all resources defined in the configuration, which is especially useful for tearing down temporary test or development environments. 3. The State File (`terraform.tfstate`): Terraform is stateful. It maintains a JSON file that maps the names in your HCL code (such as `aws_instance.web`) to real-world cloud resource IDs (such as `i-0a82b4c12ef`). Without this state file, Terraform would not know which cloud resources it owns. 4. Remote State and Distributed Locking: In team environments, state files should never be kept on a local laptop or committed to Git. Instead, teams use Remote Backends, such as an encrypted AWS S3 bucket combined with an AWS DynamoDB table. DynamoDB provides distributed locking: when an engineer runs `terraform apply`, Terraform locks the state. If another team member tries to run `apply` at the exact same moment, Terraform blocks the second execution until the first completes, preventing conflicts and state corruption.

Terraform Execution Architecture & State Management

1. HCL Manifests
Declarative infrastructure code written in files like `main.tf`, `variables.tf`, and `outputs.tf`
2. terraform init
Downloads required provider plugins and establishes connection to the remote backend
3. terraform plan
Queries cloud APIs to calculate dependency graphs and preview exact changes against the state file
4. State Lock Acquisition
Acquires a distributed lock (such as in DynamoDB) to prevent concurrent team executions
5. terraform apply
Executes necessary API calls in parallel across cloud providers to reach the desired state
6. State File Update
Writes updated resource IDs and attributes to the remote encrypted state storage
7. Lock Release
Releases the remote lock and outputs important values like IP addresses and resource IDs

Key Points

  • Terraform is multi-cloud: manage AWS, Azure, GCP, Kubernetes, and SaaS platforms with one consistent tool.
  • The core workflow follows four clear steps: init, plan, apply, and destroy.
  • The state file (`terraform.tfstate`) tracks real-world cloud resource mappings and must be protected, encrypted, and locked.
  • Never commit state files to Git because they can contain sensitive resource metadata and credentials.
  • Use remote backends (like S3 with DynamoDB locking) to coordinate team deployments safely.
  • Organize reusable infrastructure patterns into Modules to keep configurations clean and DRY across environments.

Steps

  1. Install the Terraform CLI

    Install the official binary using a package manager (such as Homebrew or Chocolatey) or direct download, and verify with `terraform version`.

  2. Define Providers and Resources in HCL

    Create a `main.tf` file declaring the required providers (such as `hashicorp/aws`) and the resources you want to create (such as a VPC or subnet).

  3. Initialize the Directory (terraform init)

    Run `terraform init` to download provider plugins and configure remote backend storage.

  4. Inspect the Execution Plan (terraform plan)

    Run `terraform plan` to preview all additions, modifications, and deletions before applying them.

  5. Apply Configuration to Cloud (terraform apply)

    Run `terraform apply`, review the final prompt, type `yes`, and watch resources provision in real time.

Examples

The Universal Remote Control Analogy

Imagine your living room has a Samsung TV, a Sony Soundbar, an Apple TV, and smart lights. Operating them manually requires four different remote controls with different buttons. Terraform is like a programmable universal remote: it speaks to all four devices simultaneously. You press one button ('Movie Mode'), and it dims the lights, switches audio to the soundbar, and turns on the TV automatically.

Real-World Examples

Standardized Multi-Account Environments

Modern engineering organizations use modular Terraform configurations to provision isolated cloud accounts for different engineering teams. By using reusable modules, platform teams can spin up a fully compliant environment with VPC networking, logging, and security boundaries in under ten minutes.

Technical Examples

Production Terraform Configuration: Remote S3 and DynamoDB Backend with AWS VPChcl
# ─── 1. TERRAFORM CONFIGURATION & REMOTE BACKEND LOCKING ────────────
terraform {
  required_version = ">= 1.5.0"

  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 5.0"
    }
  }

  # Production Best Practice: Encrypted S3 backend with DynamoDB locking
  backend "s3" {
    bucket         = "myorg-terraform-state-prod"
    key            = "networking/vpc.tfstate"
    region         = "us-east-1"
    encrypt        = true
    dynamodb_table = "terraform-state-locks" # Prevents concurrent applies
  }
}

# ─── 2. PROVIDER DEFINITION ─────────────────────────────────────────
provider "aws" {
  region = var.aws_region

  default_tags {
    tags = {
      Environment = var.environment
      ManagedBy   = "Terraform"
      Project     = "KnowledgeSchool"
    }
  }
}

# ─── 3. VARIABLES ───────────────────────────────────────────────────
variable "aws_region" {
  type        = string
  default     = "us-east-1"
  description = "Target AWS deployment region"
}

variable "environment" {
  type        = string
  default     = "production"
  description = "Target deployment environment"
}

variable "vpc_cidr" {
  type        = string
  default     = "10.0.0.0/16"
  description = "CIDR block for the production VPC"
}

# ─── 4. RESOURCES ───────────────────────────────────────────────────
resource "aws_vpc" "main" {
  cidr_block           = var.vpc_cidr
  enable_dns_support   = true
  enable_dns_hostnames = true

  tags = {
    Name = "${var.environment}-vpc"
  }
}

resource "aws_subnet" "public_1" {
  vpc_id                  = aws_vpc.main.id
  cidr_block              = "10.0.1.0/24"
  availability_zone       = "${var.aws_region}a"
  map_public_ip_on_launch = true

  tags = {
    Name = "${var.environment}-public-subnet-1"
  }
}

# ─── 5. OUTPUTS ─────────────────────────────────────────────────────
output "vpc_id" {
  value       = aws_vpc.main.id
  description = "The ID of the provisioned VPC"
}
This configuration demonstrates production best practices: it configures an encrypted remote S3 backend with DynamoDB locking, attaches default governance tags, uses typed variables, provisions a VPC and Subnet, and exposes the VPC ID via outputs.

Terraform vs AWS CloudFormation

AspectTerraformAWS CloudFormation
Cloud EcosystemMulti-Cloud (AWS, Azure, GCP, Kubernetes, Cloudflare)AWS-centric (limited third-party support)
Configuration SyntaxClean, concise HCL (HashiCorp Configuration Language)Verbose JSON or YAML templates
Execution ModelClient-side graph calculation with fast planningServer-side stack management in AWS
State ManagementExplicit state file with flexible remote backendsManaged internally by the AWS CloudFormation service
Ecosystem & ModulesLarge public Terraform Registry with community modulesSmaller collection of CloudFormation templates

State Locking and Sensitive Data Governance

1. State Locking with DynamoDB: When you run `terraform apply`, Terraform creates a lock entry in DynamoDB. If another team member or CI runner attempts an apply at the same time, Terraform halts immediately with an error message indicating the lock is held, protecting your state file from race conditions. 2. Sensitive Data in State Files: Terraform state files record all managed resource attributes in plain text, which can include generated database passwords or TLS keys. To protect this data, always enable server-side encryption on your remote storage bucket, enforce strict least-privilege IAM permissions, and never commit state files or secret `.tfvars` files to Git.

Advantages

  • Multi-Cloud Support: Use one consistent language and workflow across AWS, GCP, Azure, and Kubernetes.
  • Predictable Previews: `terraform plan` lets you review exact changes before touching live cloud resources.
  • Modular Architecture: Terraform Modules encapsulate complex infrastructure patterns into reusable components.
  • Vibrant Ecosystem: Thousands of verified community providers and modules exist for almost any service.

Limitations

  • State Synchronization: If team members make manual changes in the cloud console, state drift can cause unexpected changes on the next apply.
  • State Refactoring: Renaming resources in code requires using `terraform state mv` so Terraform recognizes the rename instead of destroying and recreating the resource.

Interview Questions

Why is the Terraform state file necessary, and why is remote state locking important in teams?

The state file (`terraform.tfstate`) is the central ledger that maps declarative HCL resource names to real-world cloud resource IDs and attributes. It allows Terraform to calculate deltas during `plan`, manage dependencies, and track configuration drift. In team settings, remote state locking (such as using an S3 bucket with a DynamoDB table) is essential because it prevents two engineers or CI jobs from applying changes at the same time, which would corrupt the state file or cause conflicting cloud API updates.

Practice Questions

  1. Create a simple Terraform configuration using the `local_file` provider to generate a local text file and inspect the resulting `terraform.tfstate`.
  2. Explain how an S3 remote backend with DynamoDB locking prevents two team members from conflicting during an apply.