Terraform cheatsheet - useful commands and examples

The list of all terraform commands

Page content

Here is a comprehensive Terraform cheatsheet with essential commands, configuration elements, resource management, modules, variables, state handling, and best practices.

Terraform is an open-source infrastructure-as-code (IaC) tool developed by HashiCorp, enabling users to define and provision infrastructure across multiple cloud providers (e.g., AWS, Azure, GCP) using declarative configuration files. Its primary purpose is to automate infrastructure provisioning, ensure consistency, and reduce manual errors. Terraform supports multi-cloud, modular, and state-driven workflows, making it a cornerstone of modern DevOps practices.

student using terraform

Key Terraform Benefits:

  • Declarative Syntax: Define desired infrastructure states in code.
  • Provider Agnosticism: Works with AWS, Azure, GCP, Kubernetes, and more.
  • State Management: Tracks infrastructure changes to avoid conflicts.

Installation and Setup Guide

https://developer.hashicorp.com/terraform/tutorials#get-started

The Terraform installation process is pretty simple.

  • Linux (Ubuntu/Debian):

    wget -O - https://apt.releases.hashicorp.com/gpg | sudo gpg --dearmor -o /usr/share/keyrings/hashicorp-archive-keyring.gpg
    echo "deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/hashicorp-archive-keyring.gpg] https://apt.releases.hashicorp.com $(grep -oP '(?<=UBUNTU_CODENAME=).*' /etc/os-release || lsb_release -cs) main" | sudo tee /etc/apt/sources.list.d/hashicorp.list
    sudo apt update && sudo apt install terraform
    
  • Windows (WSL):

    wget -O terraform.zip https://releases.hashicorp.com/terraform/1.5.5/terraform_1.5.5_windows_amd64.zip
    unzip terraform.zip
    
  • macOS (Homebrew):

    brew install terraform
    

Verification

terraform --version

Terraform CLI Commands

Here is the list of all Terraform commands:

Command Description
terraform init Initialize a new or existing Terraform configuration directory
terraform validate Check whether the configuration is valid
terraform plan Show execution plan without making changes
terraform apply Apply changes required to reach desired state
terraform destroy Destroy Terraform-managed infrastructure
terraform fmt Reformat configuration files in the standard style
terraform show Show current state or plan
terraform refresh Update state with real infrastructure
terraform providers Display providers used in the configuration
terraform graph Visualize resource dependencies as a graph
terraform workspace list List all available workspaces
terraform workspace new Create a new workspace
terraform workspace select Switch to a specified workspace
terraform workspace show Show the name of the current workspace
terraform workspace delete Delete a specified workspace
terraform output Show output values from the state file
terraform import Import existing resource into Terraform
terraform taint Mark a resource for recreation on next apply
terraform untaint Unmark a resource as tainted
terraform state list List resources in the state file
terraform state show Show attributes of a single resource in state

Configuration Essentials

File Extensions

  • .tf: Main configuration files (HCL syntax)
  • .tfvars: Variable values

Terraform Block Types

  • Provider Example
    provider "aws" {
      region = "us-east-1"
    }
    
  • Resource Example
    resource "aws_instance" "web" {
      ami           = "ami-0abcdef"
      instance_type = "t2.micro"
    }
    
  • Variable Example
    variable "instance_count" {
      type    = number
      default = 2
    }
    
  • Output Example
    output "instance_ip" {
      value = aws_instance.web.public_ip
    }
    
  • Module Example
    module "vpc" {
      source = "./modules/vpc"
      cidr_block = var.vpc_cidr
    }
    

Working with Variables

  • Declaring variables
    variable "region" {
      description = "AWS region"
      default     = "us-east-1"
    }
    
  • Assigning values
    • CLI: terraform apply -var="region=us-west-2"
    • tfvars file: terraform apply -var-file="prod.tfvars"
  • Types: string, number, bool, list, map, object

Managing State

  • State file: terraform.tfstate
  • Remote state (S3 Example)
    backend "s3" {
      bucket = "my-tf-state"
      key    = "state.tfstate"
      region = "us-east-1"
    }
    
  • View state:
    terraform show
    terraform state list

Loops and Conditionals

  • Count
    resource "aws_instance" "web" {
      count = 3
      ...
    }
    
  • For_each
    resource "aws_s3_bucket" "b" {
      for_each = var.bucket_names
      bucket   = each.value
    }
    
  • Conditionals
    instance_type = var.env == "prod" ? "t2.large" : "t2.micro"
    

Functions

  • String interpolation:
    resource "aws_s3_bucket" "example" { bucket = "my-bucket-${var.env}" }
  • List, Map examples:
    locals {
      my_map = { a = 1, b = 2 }
    }
    

Provisioners

Used for bootstrapping resources. Example:

resource "aws_instance" "web" {
  ...
  provisioner "local-exec" {
    command = "echo Instance created"
  }
}

Best Practices

  • Version control all .tf files
  • Lock provider versions to ensure consistent deployments
  • Remote backend for state management (S3, Azure Blob, etc.)
  • Encrypt state files in remote backends
  • Modularize infrastructure using reusable modules
  • Document your configurations
  • Test in staging before production

Additional References

  • Help: terraform --help or [command] --help for command-specific help
  • Debugging: Set TF_LOG=INFO or TF_LOG=DEBUG for verbose logs
  • Formatting: terraform fmt

This cheatsheet provides a quick-access reference for the most common and advanced aspects of Terraform usage - from commands to best practices - making it practical for both beginners and advanced users. Have a great day!