Terraform

Getting Started with Terraform: Infrastructure as Code in Practice

Learn how to manage cloud infrastructure with Terraform, covering HCL syntax, state management, modular design, and best practices.

What is Infrastructure as Code?

Infrastructure as Code (IaC) is the practice of managing and provisioning infrastructure through code rather than manual processes. Terraform is one of the most popular IaC tools available today.

Terraform Core Concepts

Provider

A Provider is a plugin that allows Terraform to interact with cloud services. Each cloud platform has its own Provider.

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

provider "aws" {
  region = "us-east-1"
}

Resource

A Resource is an infrastructure component managed by Terraform.

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

  tags = {
    Name = "web-server"
  }
}

Variables and Outputs

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

output "instance_ip" {
  description = "The public IP of the instance"
  value       = aws_instance.web.public_ip
}

Workflow

The basic Terraform workflow consists of three steps:

# 1. Initialize - Download provider plugins
terraform init

# 2. Plan - Preview changes to be made
terraform plan

# 3. Apply - Execute the changes
terraform apply

State Management

Terraform uses a state file (terraform.tfstate) to track created resources. For team collaboration, use a remote backend:

terraform {
  backend "s3" {
    bucket         = "my-terraform-state"
    key            = "prod/terraform.tfstate"
    region         = "us-east-1"
    dynamodb_table = "terraform-locks"
    encrypt        = true
  }
}

Modularization

Breaking infrastructure into reusable modules is a best practice:

modules/
├── vpc/
│   ├── main.tf
│   ├── variables.tf
│   └── outputs.tf
├── ec2/
│   ├── main.tf
│   ├── variables.tf
│   └── outputs.tf
└── rds/
    ├── main.tf
    ├── variables.tf
    └── outputs.tf
module "vpc" {
  source = "./modules/vpc"

  cidr_block  = "10.0.0.0/16"
  environment = "production"
}

module "web_server" {
  source = "./modules/ec2"

  vpc_id        = module.vpc.vpc_id
  subnet_id     = module.vpc.public_subnet_ids[0]
  instance_type = "t3.micro"
}

Summary

Terraform makes infrastructure management predictable, repeatable, and version-controlled. With these fundamentals, you can start managing your cloud infrastructure as code.