AI Generate Terraform docs instantly

Terraform Cheat Sheet

Quick reference guide with copy-paste ready code snippets

Try DocuWriter Free

Getting Started

4 snippets

Basic Terraform configuration

Provider Configuration

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

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

Comments

# Single line comment

/*
Multi-line
comment
*/

Initialize Terraform

terraform init

Common Commands

terraform plan      # Preview changes
terraform apply     # Apply changes
terraform destroy   # Destroy resources
terraform validate  # Validate config
terraform fmt       # Format files

Variables

5 snippets

Input and output variables

Variable Declaration

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

Variable Types

variable "count" {
  type = number
}

variable "enabled" {
  type = bool
}

variable "tags" {
  type = map(string)
}

variable "subnets" {
  type = list(string)
}

Variable Usage

resource "aws_instance" "web" {
  instance_type = var.instance_type
  ami           = var.ami_id
}

Output Values

output "instance_ip" {
  description = "Public IP of EC2 instance"
  value       = aws_instance.web.public_ip
}

output "vpc_id" {
  value = aws_vpc.main.id
}

Local Values

locals {
  common_tags = {
    Environment = "production"
    ManagedBy   = "Terraform"
  }

  name_prefix = "${var.project}-${var.environment}"
}

Resources

5 snippets

Defining infrastructure resources

Basic Resource

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

  tags = {
    Name = "WebServer"
  }
}

Resource Dependencies

resource "aws_eip" "ip" {
  vpc      = true
  instance = aws_instance.web.id

  depends_on = [aws_internet_gateway.gw]
}

Count Meta-Argument

resource "aws_instance" "server" {
  count = 3

  ami           = "ami-0c55b159cbfafe1f0"
  instance_type = "t2.micro"

  tags = {
    Name = "Server-${count.index}"
  }
}

For_Each Meta-Argument

resource "aws_s3_bucket" "buckets" {
  for_each = toset(["logs", "data", "backups"])

  bucket = "${var.prefix}-${each.key}"
}

Lifecycle Rules

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

  lifecycle {
    create_before_destroy = true
    prevent_destroy       = true
    ignore_changes        = [tags]
  }
}

Tired of looking up syntax?

DocuWriter.ai generates documentation and explains code using AI.

Try Free

Data Sources

3 snippets

Reading existing resources

Data Source

data "aws_ami" "ubuntu" {
  most_recent = true

  filter {
    name   = "name"
    values = ["ubuntu/images/hvm-ssd/ubuntu-*"]
  }

  owners = ["099720109477"]  # Canonical
}

Use Data Source

resource "aws_instance" "web" {
  ami           = data.aws_ami.ubuntu.id
  instance_type = "t2.micro"
}

VPC Data Source

data "aws_vpc" "default" {
  default = true
}

data "aws_subnets" "default" {
  filter {
    name   = "vpc-id"
    values = [data.aws_vpc.default.id]
  }
}

Modules

4 snippets

Reusable configuration components

Module Definition

# modules/vpc/main.tf
variable "cidr_block" {
  type = string
}

resource "aws_vpc" "main" {
  cidr_block = var.cidr_block
}

output "vpc_id" {
  value = aws_vpc.main.id
}

Module Usage

module "vpc" {
  source = "./modules/vpc"

  cidr_block = "10.0.0.0/16"
}

Access Module Output

resource "aws_subnet" "public" {
  vpc_id     = module.vpc.vpc_id
  cidr_block = "10.0.1.0/24"
}

Remote Module

module "s3_bucket" {
  source  = "terraform-aws-modules/s3-bucket/aws"
  version = "3.15.0"

  bucket = "my-bucket"
  acl    = "private"
}

Built-in Functions

5 snippets

Common Terraform functions

String Functions

upper("hello")           # HELLO
lower("WORLD")           # world
format("server-%03d", 1) # server-001
join("-", ["a", "b"])    # a-b
split("-", "a-b-c")      # ["a", "b", "c"]

Collection Functions

length([1, 2, 3])        # 3
concat([1, 2], [3, 4])   # [1, 2, 3, 4]
contains(["a"], "a")     # true
merge({a=1}, {b=2})      # {a=1, b=2}

Type Conversions

tostring(42)             # "42"
tonumber("42")           # 42
tolist(["a", "b"])       # Convert to list
toset(["a", "a", "b"])   # ["a", "b"] (unique)

File Functions

file("path/to/file.txt")         # Read file
filebase64("path/to/file.bin")   # Base64 encode
jsonencode({key = "value"})      # JSON encode
jsondecode(file("data.json"))    # Parse JSON

IP Functions

cidrsubnet("10.0.0.0/16", 8, 1)  # 10.0.1.0/24
cidrhost("10.0.0.0/24", 5)       # 10.0.0.5

Expressions

5 snippets

Conditional and iteration expressions

Conditional Expression

variable "environment" {}

resource "aws_instance" "web" {
  instance_type = var.environment == "prod" ? "t2.large" : "t2.micro"
}

For Expression (List)

variable "users" {
  type = list(string)
}

locals {
  user_emails = [for user in var.users : "${user}@example.com"]
}

For Expression (Map)

variable "tags" {
  type = map(string)
}

locals {
  uppercase_tags = {
    for key, value in var.tags :
    upper(key) => upper(value)
  }
}

For with If

locals {
  even_numbers = [for n in [1, 2, 3, 4, 5] : n if n % 2 == 0]
  # Result: [2, 4]
}

Dynamic Blocks

resource "aws_security_group" "example" {
  name = "example"

  dynamic "ingress" {
    for_each = var.ingress_rules
    content {
      from_port   = ingress.value.port
      to_port     = ingress.value.port
      protocol    = "tcp"
      cidr_blocks = ingress.value.cidr_blocks
    }
  }
}

State Management

4 snippets

Managing Terraform state

S3 Backend

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

State Commands

terraform state list                    # List resources
terraform state show aws_instance.web  # Show resource
terraform state mv SOURCE DEST         # Move resource
terraform state rm aws_instance.web    # Remove from state

Import Existing Resource

# First, add resource to config
resource "aws_instance" "imported" {
  # ... configuration
}

# Then import
terraform import aws_instance.imported i-1234567890abcdef0

Workspace Commands

terraform workspace list         # List workspaces
terraform workspace new dev      # Create workspace
terraform workspace select prod  # Switch workspace
terraform workspace show         # Current workspace

More Cheat Sheets

FAQ

Frequently asked questions

What is a Terraform cheat sheet?

A Terraform cheat sheet is a quick reference guide containing the most commonly used syntax, functions, and patterns in Terraform. It helps developers quickly look up syntax without searching through documentation.

How do I learn Terraform quickly?

Start with the basics: variables, control flow, and functions. Use this cheat sheet as a reference while practicing. For faster learning, try DocuWriter.ai to automatically explain code and generate documentation as you learn.

What are the most important Terraform concepts?

Key Terraform concepts include variables and data types, control flow (if/else, loops), functions, error handling, and working with data structures like arrays and objects/dictionaries.

How can I document my Terraform code?

Use inline comments for complex logic, docstrings for functions and classes, and README files for projects. DocuWriter.ai can automatically generate professional documentation from your Terraform code using AI.

Code Conversion Tools

Convert Terraform to Other Languages

Easily translate your Terraform code to other programming languages with our AI-powered converters

Related resources

Stop memorizing. Start shipping.

Generate Terraform Docs with AI

DocuWriter.ai automatically generates comments, docstrings, and README files for your code.

Auto-generate comments
Create README files
Explain complex code
API documentation
Start Free - No Credit Card

Join 33,700+ developers saving hours every week