Format For Expressions and Comprehensions
Format Terraform for expressions including list comprehensions, map transformations, conditional filtering, and nested for expressions with proper line breaks.
Advanced Patterns
Detailed Explanation
Formatting For Expressions
Terraform's for expressions create lists and maps from existing collections. They can range from simple one-liners to complex multi-line expressions with filtering conditions.
Simple For Expressions
locals {
upper_names = [for name in var.names : upper(name)]
name_map = {
for name in var.names : name => upper(name)
}
filtered = [
for name in var.names : upper(name)
if length(name) > 3
]
}
Complex For Expressions
locals {
subnet_config = {
for idx, cidr in var.subnet_cidrs : "subnet-${idx}" => {
cidr_block = cidr
availability_zone = var.azs[idx % length(var.azs)]
is_public = idx < var.public_subnet_count
}
}
flattened_rules = flatten([
for sg_name, sg_rules in var.security_groups : [
for rule in sg_rules : {
sg_name = sg_name
from_port = rule.from_port
to_port = rule.to_port
protocol = rule.protocol
}
]
])
tagged_resources = {
for key, resource in local.all_resources : key => merge(
resource,
{
tags = merge(local.common_tags, resource.tags)
}
)
}
}
Formatting Rules
- Single-line: Simple for expressions that fit on one line stay inline:
[for x in list : transform(x)] - Multi-line with filter: When a
ifcondition is added, the filter goes on its own line - Nested for: Each nested
forgets its own indentation level - Map output:
key => valuepairs in map for expressions align their=>operators - Complex values: When the output value is an object, it gets its own indented block
Use Case
Transforming input variables into the data structures needed by resources, such as converting a list of CIDR blocks into a map of subnet configurations.