Skip to main content
โšก Calmops

Infrastructure as Code: Terraform

Infrastructure as Code: Terraform

Infrastructure as Code enables reproducible infrastructure. This article covers Terraform fundamentals.

Introduction

Infrastructure as Code provides:

  • Reproducible infrastructure
  • Version control
  • Automation
  • Consistency
  • Scalability

Terraform Basics

Terraform Configuration

# โœ… Good: Terraform configuration
terraform {
  required_version = ">= 1.0"
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 4.0"
    }
  }
}

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

# โœ… Good: Create EC2 instance
resource "aws_instance" "app" {
  ami           = "ami-0c55b159cbfafe1f0"
  instance_type = "t2.micro"

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

# โœ… Good: Create security group
resource "aws_security_group" "app" {
  name = "app-sg"

  ingress {
    from_port   = 80
    to_port     = 80
    protocol    = "tcp"
    cidr_blocks = ["0.0.0.0/0"]
  }

  egress {
    from_port   = 0
    to_port     = 0
    protocol    = "-1"
    cidr_blocks = ["0.0.0.0/0"]
  }
}

# โœ… Good: Output values
output "instance_ip" {
  value = aws_instance.app.public_ip
}

Commands

Terraform Commands

# โœ… Good: Initialize Terraform
terraform init

# โœ… Good: Validate configuration
terraform validate

# โœ… Good: Plan changes
terraform plan

# โœ… Good: Apply changes
terraform apply

# โœ… Good: Destroy infrastructure
terraform destroy

# โœ… Good: Show state
terraform show

# โœ… Good: Format code
terraform fmt

Best Practices

  1. Use variables:

    # โœ… Good: Use variables
    variable "instance_type" {
      type    = string
      default = "t2.micro"
    }
    
    resource "aws_instance" "app" {
      instance_type = var.instance_type
    }
    
    # โŒ Bad: Hardcoded values
    resource "aws_instance" "app" {
      instance_type = "t2.micro"
    }
    
  2. Use modules:

    # โœ… Good: Use modules
    module "vpc" {
      source = "./modules/vpc"
      cidr   = "10.0.0.0/16"
    }
    
    # โŒ Bad: Inline configuration
    resource "aws_vpc" "main" {
      cidr_block = "10.0.0.0/16"
    }
    
  3. Use state files:

    # โœ… Good: Remote state
    terraform {
      backend "s3" {
        bucket = "terraform-state"
        key    = "prod/terraform.tfstate"
        region = "us-east-1"
      }
    }
    
    # โŒ Bad: Local state
    # Default local state
    

Summary

Infrastructure as Code is essential. Key takeaways:

  • Define infrastructure
  • Use variables
  • Create modules
  • Use remote state
  • Version control
  • Automate deployment
  • Manage resources
  • Follow best practices

Next Steps

Comments