Skip to main content

Terraform Reference

v1.0.0

Blocks, meta-arguments, built-in functions and expressions for Terraform HCL.

22 entries found

resourceBlock

resource "<TYPE>" "<NAME>" { ... }

Declares an infrastructure object managed by Terraform. The type maps to a provider resource (e.g. aws_instance). The name is a local identifier.

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

data "<TYPE>" "<NAME>" { ... }

Reads data from an existing resource or external source without creating it. Useful for referencing pre-existing infrastructure.

data "aws_ami" "ubuntu" {
  most_recent = true
  filter {
    name   = "name"
    values = ["ubuntu/images/*"]
  }
}
variableBlock

variable "<NAME>" { ... }

Declares an input variable. Can specify type, default value, description and validation rules.

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

output "<NAME>" { value = ... }

Exports a value from a module or root configuration. Outputs are printed after apply and can be passed between modules.

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

locals { <NAME> = <EXPR> ... }

Defines local values — named expressions you can reuse within a module to avoid repetition.

locals {
  env_prefix = "${var.environment}-${var.project}"
  tags = { Environment = var.environment }
}
moduleBlock

module "<NAME>" { source = "..." ... }

Calls a child module from a local path, Terraform Registry, or VCS. Passes input variables to the module.

module "vpc" {
  source  = "terraform-aws-modules/vpc/aws"
  version = "3.0.0"
  cidr    = "10.0.0.0/16"
}
providerBlock

provider "<NAME>" { ... }

Configures a provider plugin (e.g. AWS, Azure, GCP). Multiple configurations can be aliased.

provider "aws" {
  region  = "us-east-1"
  profile = "default"
}
terraformBlock

terraform { ... }

Configures global Terraform settings: required version, backend, required providers.

terraform {
  required_version = ">= 1.0"
  backend "s3" { bucket = "my-tfstate" }
  required_providers { aws = { source = "hashicorp/aws" } }
}
countMeta-arg

count = <NUMBER>

Creates multiple instances of a resource. Each instance is accessible via count.index (0-based).

resource "aws_instance" "server" {
  count         = 3
  ami           = "ami-abc123"
  instance_type = "t2.micro"
  tags = { Name = "server-${count.index}" }
}
for_eachMeta-arg

for_each = <MAP or SET>

Creates one instance per map key or set value. Prefer over count for named resources. Access via each.key and each.value.

resource "aws_iam_user" "user" {
  for_each = toset(["alice", "bob"])
  name     = each.value
}
depends_onMeta-arg

depends_on = [<RESOURCE>...]

Explicitly declares dependencies not inferrable from references. Use sparingly — usually Terraform infers dependencies automatically.

resource "aws_s3_bucket_policy" "example" {
  bucket     = aws_s3_bucket.b.id
  depends_on = [aws_s3_bucket_public_access_block.b]
}
lifecycleMeta-arg

lifecycle { create_before_destroy = bool ... }

Controls resource lifecycle behaviour. Options: create_before_destroy, prevent_destroy, ignore_changes, replace_triggered_by.

resource "aws_instance" "web" {
  lifecycle {
    create_before_destroy = true
    ignore_changes        = [tags]
  }
}
merge()Function

merge(map1, map2, ...)

Merges two or more maps. Later maps override keys from earlier maps.

locals {
  tags = merge(
    { Environment = "prod" },
    var.extra_tags
  )
}
toset()Function

toset(list)

Converts a list to a set, removing duplicates. Commonly used with for_each.

resource "aws_iam_user" "u" {
  for_each = toset(var.users)
  name     = each.value
}
lookup()Function

lookup(map, key, default)

Retrieves a value from a map by key, returning a default if the key does not exist.

locals {
  size = lookup(var.sizes, var.env, "medium")
}
flatten()Function

flatten(list_of_lists)

Flattens a list of lists into a single flat list.

locals {
  all_ids = flatten([
    aws_subnet.public[*].id,
    aws_subnet.private[*].id,
  ])
}
jsonencode()Function

jsonencode(value)

Encodes a Terraform value as a JSON string. Useful for policy documents or inline JSON config.

resource "aws_iam_role_policy" "p" {
  policy = jsonencode({
    Version   = "2012-10-17"
    Statement = [{ Effect = "Allow", Action = "*" }]
  })
}
coalesce()Function

coalesce(val1, val2, ...)

Returns the first non-null, non-empty string argument.

locals {
  name = coalesce(var.custom_name, var.default_name, "unnamed")
}
try()Function

try(expr1, expr2, ...)

Evaluates each expression in order, returning the result of the first one that evaluates without error.

locals {
  port = try(tonumber(var.port), 8080)
}
for expressionExpression

[for <ITEM> in <COLLECTION> : <VALUE> if <CONDITION>]

Creates a new list or map by transforming elements of a collection. The if clause is optional.

locals {
  public_ids = [for s in aws_subnet.all : s.id if s.map_public_ip_on_launch]
}
conditional (ternary)Expression

<CONDITION> ? <TRUE> : <FALSE>

Evaluates a condition and returns one of two values. Similar to ternary operators in other languages.

resource "aws_instance" "web" {
  instance_type = var.env == "prod" ? "m5.large" : "t2.micro"
}
splat expressionExpression

<RESOURCE>[*].<ATTR>

Collects attribute values from all instances of a resource created with count or for_each.

output "all_ips" {
  value = aws_instance.server[*].public_ip
}