Skip to main content

Terraform

Terraform is an open-source Infrastructure as Code (IaC) tool created by HashiCorp that enables you to safely and predictably create, change, and improve infrastructure using a declarative configuration language.

Key Features

  • Declarative Configuration: Define what infrastructure you want, not how to create it
  • Multi-Cloud Support: Works with AWS, Azure, GCP, and 100+ other providers
  • State Management: Tracks infrastructure state to manage changes safely
  • Plan and Apply: Preview changes before applying them
  • Modularity: Reusable modules for common infrastructure patterns

Core Concepts

1. Providers

Providers are plugins that interact with APIs to manage resources:

provider "aws" {
region = "us-west-2"
}

2. Resources

Resources represent infrastructure components:

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

3. Variables

Make configurations reusable and configurable:

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

4. Outputs

Expose information about created resources:

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

Basic Workflow

  1. Initialize: terraform init - Downloads providers and modules
  2. Plan: terraform plan - Shows what changes will be made
  3. Apply: terraform apply - Creates or modifies infrastructure
  4. Destroy: terraform destroy - Removes infrastructure

State Management

Terraform maintains a state file that tracks the current state of your infrastructure:

  • Local State: Stored in terraform.tfstate file
  • Remote State: Stored in backends like S3, Azure Storage, or Terraform Cloud
  • State Locking: Prevents concurrent modifications

Best Practices

  • Use version control for all Terraform files
  • Store state remotely with locking
  • Use modules for reusable components
  • Implement proper variable validation
  • Use workspaces for environment separation
  • Follow naming conventions consistently

Common Use Cases

  • Multi-Cloud Deployments: Manage resources across different cloud providers
  • Environment Management: Create consistent dev, staging, and production environments
  • Disaster Recovery: Quickly recreate infrastructure in different regions
  • Compliance: Ensure infrastructure meets security and compliance requirements