Terraform Cheatsheet

A comprehensive reference for Terraform CLI commands, options, and examples.

Version: 1.5.0

String Functions

Functions for manipulating and working with strings

join
Combines a list of strings into a single string with a specified delimiter.

Examples:

join("-", ["app", "web", "db"])
# Result: "app-web-db"
split
Splits a string into a list of substrings based on a delimiter.

Examples:

split(",", "foo,bar,baz")
# Result: ["foo", "bar", "baz"]
replace
Replaces all occurrences of a substring within a string.

Examples:

replace("path/to/file.txt", "/", "\\")
# Result: "path\\to\\file.txt"
substr
Extracts a substring from a string starting at a specific offset and length.

Examples:

substr("i-1234567890abcdef0", 2, 8)
# Result: "12345678"
lower / upper
Converts a string to lowercase or uppercase.

Examples:

lower("Production")  # "production"
upper("Production")  # "PRODUCTION"
format
Creates a formatted string using printf-style syntax.

Examples:

format("Created %d instances", 5)
# Result: "Created 5 instances"
format("%04d", 42)
# Result: "0042"
regex
Applies a regular expression to a string and returns matched substrings.

Examples:

regex("v(\\d+)\\.(\\d+)\\.(\\d+)", "v1.2.3")
# Result: ["1", "2", "3"]
regexall
Finds all matches of a regular expression in a string.

Examples:

regexall("\\d+\\.\\d+\\.\\d+\\.\\d+", "IP: 192.168.1.1 and 10.0.0.1")
# Result: ["192.168.1.1", "10.0.0.1"]

Collection Functions

Functions for working with lists, sets, and maps

concat
Combines multiple lists into a single list.

Examples:

concat(["a", "b"], ["c", "d"])
# Result: ["a", "b", "c", "d"]
flatten
Flattens a list of lists into a single list.

Examples:

flatten([["a", "b"], ["c"], ["d", "e"]])
# Result: ["a", "b", "c", "d", "e"]
slice
Extracts a portion of a list between start and end indices.

Examples:

slice(["a", "b", "c", "d", "e"], 1, 4)
# Result: ["b", "c", "d"]
element
Retrieves an element from a list at a specific index (with wrapping).

Examples:

element(["a", "b", "c"], 1)  # "b"
element(["a", "b", "c"], 5)  # "c" (5 % 3 = 2)
index
Finds the index of a specific value in a list.

Examples:

index(["a", "b", "c"], "b")
# Result: 1
merge
Combines multiple maps into a single map, with later values overriding earlier ones.

Examples:

merge({ a = 1, b = 2 }, { b = 5, c = 3 })
# Result: { a = 1, b = 5, c = 3 }
keys / values
Extracts all keys or values from a map as a list.

Examples:

keys({ a = 1, b = 2, c = 3 })    # ["a", "b", "c"]
values({ a = 1, b = 2, c = 3 }) # [1, 2, 3]
lookup
Retrieves a value from a map for a specific key, with an optional default value.

Examples:

lookup({ "us-east-1" = "ami-123456" }, "us-east-1")  # "ami-123456"
lookup({ "us-east-1" = "ami-123456" }, "eu-west-1", "ami-default")
zipmap
Creates a map from a list of keys and a list of values.

Examples:

zipmap(["web", "app", "db"], ["i-123", "i-456", "i-789"])
# Result: { web = "i-123", app = "i-456", db = "i-789" }

Type Conversion

Functions for converting between different data types

tostring
Converts a value to a string.

Examples:

tostring(42)  # "42"
tostring(true)  # "true"
tonumber
Converts a value to a number.

Examples:

tonumber("42")  # 42
tonumber("3.14")  # 3.14
tobool
Converts a value to a boolean.

Examples:

tobool("true")  # true
tobool("false")  # false
tolist
Converts a value to a list.

Examples:

tolist(toset(["a", "b", "c"]))  # ["a", "b", "c"]
tolist(["a", 1, true])  # ["a", 1, true]
toset
Converts a value to a set, removing duplicates.

Examples:

toset(["a", "b", "a", "c", "b"])  # ["a", "b", "c"]
tomap
Converts a value to a map.

Examples:

tomap({ name = "example", id = 123 })  # { name = "example", id = 123 }

Core Workflow

Essential commands for working with Terraform configurations

terraform init
Initialize a Terraform working directory, downloading providers and modules.

Common Options:

-input=true - Ask for input if necessary
-lock=true - Lock the state file when locking is supported
-upgrade - Update modules and plugins

Examples:

terraform init
terraform init -upgrade
terraform plan
Create an execution plan to show what Terraform will do when you apply.

Common Options:

-out=path - Write a plan file to the given path
-var 'name=value' - Set a variable in the Terraform configuration
-var-file=filename - Set variables from a file

Examples:

terraform plan
terraform plan -out=tfplan
terraform plan -var 'region=us-west-2'
terraform plan -var-file=vars.tfvars
terraform apply
Apply the changes required to reach the desired state of the configuration.

Common Options:

-auto-approve - Skip interactive approval of plan before applying
-var 'name=value' - Set a variable in the Terraform configuration
-var-file=filename - Set variables from a file

Examples:

terraform apply
terraform apply tfplan
terraform apply -auto-approve
terraform destroy
Destroy the Terraform-managed infrastructure.

Common Options:

-auto-approve - Skip interactive approval before destroying
-target=resource - Target a specific resource for destruction

Examples:

terraform destroy
terraform destroy -auto-approve
terraform destroy -target=aws_instance.example

State Management

Commands for managing Terraform state

terraform state list
List resources in the Terraform state.

Common Options:

-state=path - Path to a state file

Examples:

terraform state list
terraform state list aws_instance.*
terraform state show
Show the attributes of a resource in the Terraform state.

Common Options:

-state=path - Path to a state file

Examples:

terraform state show aws_instance.example
terraform state mv
Move an item in the state, useful for module refactoring.

Common Options:

-state=path - Path to the source state file
-state-out=path - Path to the destination state file

Examples:

terraform state mv aws_instance.example module.app.aws_instance.example
terraform import
Import existing infrastructure into Terraform state.

Common Options:

-var 'name=value' - Set a variable in the Terraform configuration
-var-file=filename - Set variables from a file

Examples:

terraform import aws_instance.example i-abcd1234
terraform import 'aws_security_group.example' sg-123456

Workspace Management

Commands for managing Terraform workspaces

terraform workspace new
Create a new workspace.

Examples:

terraform workspace new dev
terraform workspace new prod
terraform workspace select
Select a workspace to use.

Examples:

terraform workspace select dev
terraform workspace select default
terraform workspace list
List available workspaces.

Examples:

terraform workspace list
terraform workspace delete
Delete a workspace.

Common Options:

-force - Delete even if workspace is not empty

Examples:

terraform workspace delete dev
terraform workspace delete -force old-workspace

Module Management

Commands for working with Terraform modules

terraform get
Download and update modules mentioned in the root module.

Common Options:

-update - Check for updates to modules

Examples:

terraform get
terraform get -update
terraform init -upgrade
Update modules and plugins.

Examples:

terraform init -upgrade

Utility Commands

Utility commands for working with Terraform configurations

terraform console
Interactive console for evaluating expressions.

Common Options:

-state=path - Path to state file
-var="key=value" - Set a variable in the Terraform configuration
-var-file=file.tfvars - Set variables from a file

Examples:

terraform console
terraform console -var="environment=prod"
terraform output
Extract output values from the state file.

Common Options:

-json - Print output in JSON format
-state=path - Path to state file

Examples:

terraform output
terraform output instance_ip
terraform output -json
terraform refresh
Update local state file against real resources.

Common Options:

-var 'name=value' - Set a variable in the Terraform configuration
-var-file=filename - Set variables from a file

Examples:

terraform refresh
terraform refresh -var-file=prod.tfvars
terraform validate
Validate the configuration files.

Common Options:

-json - Produce output in JSON format

Examples:

terraform validate
terraform validate -json
terraform fmt
Rewrites Terraform configuration files to a canonical format and style.

Common Options:

-recursive - Also process files in subdirectories
-check - Check if the input is formatted. Exit status will be 0 if all input is properly formatted
-write=false - Don't write to source files (always disabled if using -check)

Examples:

terraform fmt
terraform fmt -recursive
terraform fmt -check

Meta-Arguments

Special arguments that change behavior across resource types

depends_on
Explicitly declares dependencies between resources that are not automatically inferred by Terraform.

Examples:

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

  # This instance depends on the database being available first
  depends_on = [
    aws_db_instance.database
  ]
}
count
Creates multiple instances of a resource or module based on a single configuration block.

Examples:

resource "aws_instance" "server" {
  count = 4
  ami           = "ami-a1b2c3d4"
  instance_type = "t2.micro"
  tags = {
    Name = "Server ${count.index}"
  }
}
for_each
Creates multiple instances of a resource or module based on a map or set of strings.

Examples:

resource "aws_instance" "server" {
  for_each = {
    web = "t2.micro"
    app = "t2.medium"
    db  = "t2.large"
  }

  ami           = "ami-a1b2c3d4"
  instance_type = each.value
  tags = {
    Name = "${each.key}-server"
  }
}
provider
Specifies which provider configuration to use for a resource.

Examples:

# Define an alternate AWS provider for the us-west-2 region
provider "aws" {
  alias  = "west"
  region = "us-west-2"
}

# Use the alternate provider
resource "aws_instance" "web" {
  provider = aws.west
  ami           = "ami-0a1b2c3d4"  # AMI in us-west-2
  instance_type = "t2.micro"
}
lifecycle
Customizes the lifecycle behavior of resources.

Examples:

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

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

Providers

Configuration for provider plugins that interact with cloud providers, SaaS providers, and other APIs

Provider Configuration
Basic provider configuration with version constraints.

Examples:

provider "aws" {
  region  = "us-east-1"
  version = "~> 3.0"
}
Multiple Provider Configurations
Using multiple configurations of the same provider with aliases.

Examples:

# Default provider configuration
provider "aws" {
  region = "us-east-1"
}

# Additional provider configuration for west coast region
provider "aws" {
  alias  = "west"
  region = "us-west-2"
}
Provider Authentication
Different methods for authenticating with providers.

Examples:

# Static credentials (not recommended for production)
provider "aws" {
  region     = "us-east-1"
  access_key = "AKIAIOSFODNN7EXAMPLE"
  secret_key = "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY"
}

# Environment variables (recommended)
# Set AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY environment variables
provider "aws" {
  region = "us-east-1"
}

Provisioners

Mechanisms for executing commands on local or remote machines as part of resource creation or destruction

local-exec
Executes a command locally on the machine running Terraform.

Examples:

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

  provisioner "local-exec" {
    command = "echo ${self.private_ip} >> private_ips.txt"
  }
}
remote-exec
Executes a command on a remote resource after it is created.

Examples:

resource "aws_instance" "web" {
  ami           = "ami-a1b2c3d4"
  instance_type = "t2.micro"
  key_name      = "example-key"

  connection {
    type        = "ssh"
    user        = "ec2-user"
    private_key = file("~/.ssh/example-key.pem")
    host        = self.public_ip
  }

  provisioner "remote-exec" {
    inline = [
      "sudo yum update -y",
      "sudo yum install -y httpd",
      "sudo systemctl start httpd"
    ]
  }
}
file
Copies files or directories from the machine running Terraform to the remote resource.

Examples:

resource "aws_instance" "web" {
  ami           = "ami-a1b2c3d4"
  instance_type = "t2.micro"
  key_name      = "example-key"

  connection {
    type        = "ssh"
    user        = "ec2-user"
    private_key = file("~/.ssh/example-key.pem")
    host        = self.public_ip
  }

  provisioner "file" {
    source      = "app/index.html"
    destination = "/var/www/html/index.html"
  }
}

Terraform Functions

Built-in functions for transforming and combining values in Terraform

String Functions
Functions for manipulating strings.

Examples:

# String interpolation
name = "Hello, ${var.username}!"

# String manipulation
lower_name = lower(var.name)  # Convert to lowercase
upper_name = upper(var.name)  # Convert to uppercase
trimmed = trimspace(var.text)  # Remove whitespace from start and end
joined = join(", ", var.list)  # Join list elements with a delimiter
split_result = split(",", "a,b,c")  # Split string into list
Collection Functions
Functions for working with lists, maps, and sets.

Examples:

# List operations
first_item = element(var.list, 0)  # Get element at index
list_length = length(var.list)  # Get length of list
sliced = slice(var.list, 0, 2)  # Get a subset of list
contains_item = contains(var.list, "item")  # Check if list contains value

# Map operations
keys = keys(var.map)  # Get all keys from map
values = values(var.map)  # Get all values from map
lookup_value = lookup(var.map, "key", "default")  # Get value with default

# Merging
merged_map = merge(var.map1, var.map2)  # Merge maps
Type Conversion
Functions for converting between types.

Examples:

# Type conversion
str_to_num = tonumber("123")  # Convert string to number
num_to_str = tostring(123)  # Convert number to string
to_list = tolist(["a", "b", "c"])  # Convert to list
to_map = tomap({key = "value"})  # Convert to map
to_set = toset(["a", "b", "c"])  # Convert to set