<< back to Guides

โš™๏ธ Terraform Quick Guide

Terraform is an open-source tool for provisioning and managing infrastructure as code (IaC). It enables you to define cloud and on-prem resources using a declarative configuration language called HCL (HashiCorp Configuration Language).


๐Ÿงฑ Core Concepts


๐Ÿ“ Typical Project Structure

.
โ”œโ”€โ”€ main.tf        # Main config
โ”œโ”€โ”€ variables.tf   # Input variables
โ”œโ”€โ”€ outputs.tf     # Output values
โ”œโ”€โ”€ terraform.tfvars  # Default values for variables

๐Ÿš€ Basic Workflow

# 1. Initialize project (download provider plugins)
terraform init

# 2. Preview changes
terraform plan

# 3. Apply changes
terraform apply

# 4. Destroy infrastructure
terraform destroy

๐Ÿงพ Example: Provisioning an AWS EC2 Instance

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

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

  tags = {
    Name = "MyInstance"
  }
}

๐Ÿ“ฅ Input Variables

Define variables in variables.tf:

variable "region" {
  description = "AWS region"
  default     = "us-east-1"
}

Use them in config:

provider "aws" {
  region = var.region
}

Pass them with terraform.tfvars:

region = "us-west-2"

๐Ÿ“ค Output Values

Define outputs in outputs.tf:

output "instance_id" {
  value = aws_instance.example.id
}

๐Ÿ—‚ Remote State (Example with S3)

terraform {
  backend "s3" {
    bucket = "my-tf-state-bucket"
    key    = "state.tfstate"
    region = "us-east-1"
  }
}

๐Ÿ” Best Practices


๐Ÿงฉ Useful Commands

terraform validate     # Validate syntax
terraform fmt          # Format code
terraform output       # Show outputs
terraform taint        # Force resource recreation
terraform show         # Show current state
terraform graph        # Generate a dependency graph

<< back to Guides