Labs ICT
⭐ Pro Login

Terraform

Infrastructure as Code with HashiCorp Terraform

Terraform

Terraform by HashiCorp is the leading Infrastructure as Code tool. It uses a declarative language (HCL) to provision and manage resources across cloud providers.

Terraform Workflow


  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”
  β”‚  write  │───▢│  init   │───▢│  plan   │───▢│  apply  β”‚
  β”‚  config β”‚    β”‚         β”‚    β”‚         β”‚    β”‚         β”‚
  β”‚  (.tf)  β”‚    β”‚ Downloadβ”‚    β”‚ Preview β”‚    β”‚ Create/ β”‚
  β”‚         β”‚    β”‚ providersβ”‚   β”‚ changes β”‚    β”‚ update  β”‚
  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜    β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜    β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜    β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

  terraform init     β€” Initialize, download providers
  terraform plan     β€” Preview what will change
  terraform apply    β€” Execute the changes
  terraform destroy  β€” Tear down infrastructure

Terraform Example


  # main.tf
  provider "aws" {
    region = "us-east-1"
  }

  resource "aws_vpc" "main" {
    cidr_block = "10.0.0.0/16"
    tags = {
      Name = "production-vpc"
    }
  }

  resource "aws_subnet" "web" {
    vpc_id     = aws_vpc.main.id
    cidr_block = "10.0.1.0/24"
    tags = {
      Name = "web-subnet"
    }
  }

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

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

Terraform State


  State File (terraform.tfstate):
  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
  β”‚  Maps real-world resources to your  β”‚
  β”‚  configuration. Tracks metadata,   β”‚
  β”‚  dependencies, and IDs.            β”‚
  β”‚                                     β”‚
  β”‚  Best Practice: Use remote state    β”‚
  β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”    β”‚
  β”‚  β”‚ S3 + DynamoDB locking       β”‚    β”‚
  β”‚  β”‚ Terraform Cloud             β”‚    β”‚
  β”‚  β”‚ Consul                      β”‚    β”‚
  β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜    β”‚
  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

Key Concepts

  • Providers β€” Plugins for cloud platforms (AWS, GCP, Azure)
  • Resources β€” Infrastructure objects to create
  • Data Sources β€” Query existing resources
  • Modules β€” Reusable, composable Terraform packages
  • Workspaces β€” Manage multiple environments with the same config

πŸ§ͺ Quick Quiz

What does Terraform use to describe infrastructure?