Terraform Language Patterns Cheat Sheet

High-value HCL patterns for variables, locals, outputs, loops, conditionals, dynamic blocks, and data shaping.

View
StandardDetailedCompact
Export
Copy the compact sheet, download it, or print it.
Download
`D` dense toggle · `C` copy all

Variables, Locals, Outputs

Common building blocks in Terraform language.

String variable

Declare a typed string variable.

hclANYterraformvariableshcl
hcl
variable "environment" {
  type        = string
  description = "Deployment environment"
}
Notes

Declare a typed string variable.

Object variable

Declare a typed object variable.

hclANYterraformvariablesobject
hcl
variable "subnet" {
  type = object({
    cidr = string
    az   = string
  })
}
Notes

Declare a typed object variable.

Locals block

Compute reusable values in locals.

hclANYterraformlocals
hcl
locals {
  common_tags = {
    app         = "web"
    environment = var.environment
  }
}
Notes

Compute reusable values in locals.

Sensitive output

Mark an output sensitive to reduce accidental display.

hclANYterraformoutputsensitive
hcl
output "db_password" {
  value     = random_password.db.result
  sensitive = true
}
Notes

Mark an output sensitive to reduce accidental display.

Meta-arguments

Count, for_each, depends_on, lifecycle, and providers.

Use count

Create multiple similar resources with count.

hclANYterraformcountmeta-arguments
hcl
resource "aws_instance" "web" {
  count = 2
  ami   = var.ami_id
  instance_type = "t3.micro"
}
Notes

Create multiple similar resources with count.

Use for_each

Create resources keyed by map/set members.

hclANYterraformfor_eachmeta-arguments
hcl
resource "aws_s3_bucket" "logs" {
  for_each = toset(["app","elb","audit"])
  bucket   = "${var.prefix}-${each.key}"
}
Notes

Create resources keyed by map/set members.

Explicit dependency

Force resource ordering when dependency is not inferred from arguments.

hclANYterraformdepends_on
hcl
resource "aws_instance" "web" {
  # ...
  depends_on = [aws_internet_gateway.this]
}
Notes

Force resource ordering when dependency is not inferred from arguments.

Lifecycle rules

Control replace/delete behavior and ignored drift.

hclANYterraformlifecycle
hcl
resource "aws_s3_bucket" "logs" {
  bucket = var.bucket_name
  lifecycle {
    prevent_destroy = true
    ignore_changes  = [tags]
  }
}
Notes

Control replace/delete behavior and ignored drift.

Expressions and Functions

Conditional logic, loops, and data transformations.

Conditional expression

Choose values conditionally.

hclANYterraformconditionalexpressions
hcl
instance_type = var.environment == "prod" ? "t3.large" : "t3.micro"
Notes

Choose values conditionally.

For expression

Transform collections with a for expression.

hclANYterraformfor-expression
hcl
locals {
  private_subnet_ids = [for s in aws_subnet.private : s.id]
}
Notes

Transform collections with a for expression.

Merge maps

Combine multiple maps into one.

hclANYterraformfunctionsmerge
hcl
locals {
  tags = merge(local.common_tags, { owner = "platform" })
}
Notes

Combine multiple maps into one.

try and can

Handle optional values and guard against invalid access.

hclANYterraformfunctionstrycan
hcl
locals {
  instance_arn = try(aws_instance.web.arn, null)
  has_name     = can(var.config.name)
}
Notes

Handle optional values and guard against invalid access.

templatefile function

Render a file template with variables.

hclANYterraformfunctionstemplatefile
hcl
user_data = templatefile("${path.module}/user-data.sh.tftpl", {
  environment = var.environment
})
Notes

Render a file template with variables.

Dynamic Blocks and Data Sources

Patterns for nested repeated blocks and lookup resources.

Dynamic block

Generate repeated nested blocks from input data.

hclANYterraformdynamic-block
hcl
dynamic "ingress" {
  for_each = var.ingress_rules
  content {
    from_port   = ingress.value.from_port
    to_port     = ingress.value.to_port
    protocol    = ingress.value.protocol
    cidr_blocks = ingress.value.cidr_blocks
  }
}
Notes

Generate repeated nested blocks from input data.

Data source example

Query existing infrastructure data for use in resources.

hclANYterraformdata-source
hcl
data "aws_ami" "ubuntu" {
  most_recent = true
  owners      = ["099720109477"]

  filter {
    name   = "name"
    values = ["ubuntu/images/hvm-ssd/ubuntu-jammy-22.04-amd64-server-*"]
  }
}
Notes

Query existing infrastructure data for use in resources.