Terraform Expressions
Terraform Expressions
They can be categorised into three segments:
Conditional expressions
Dynamic blocks
Splat expressions
Conditional Expressions
Conditional expressions in Terraform use a ternary-like syntax: condition ? true_value : false_value. This is useful for setting resource attributes, variables, or outputs based on conditions.
Example:
# first we check var.environment is "dev" if yes we assign textbucket_name to "dev-bucket" # else we store "prod-bucket" textbucket_name = var.environment == "dev" ? "dev-bucket" : "prod-bucket"You can combine conditions using logical operators (
&&,||,!).Conditional expressions are often used with
count,for_each, modules, locals, and outputs to control resource creation or attribute values.
Dynamic Blocks
Dynamic blocks allow you to generate repeated nested blocks (like security_rule in Azure or ingress in AWS) based on lists or maps. This avoids duplicating configuration.
Syntax:
textdynamic "block_name" { for_each = local.list_of_rules content { name = block_name.value.name priority = block_name.value.priority # ... other attributes } }Useful for managing multiple similar blocks, such as security rules, tags, or network settings.
Splat Expressions
Splat expressions ([*]) simplify extracting attributes from lists of objects.
Example:
If you have a list of objects:textlocals { users = [ { name = "Alice", role = "admin" }, { name = "Bob", role = "user" } ] }You can extract all names with:
textlocal.names = local.users[*].nameSplat expressions work with both lists and maps, and can be used in
for_eachor as arguments.
These expressions make Terraform configurations more flexible, reusable, and easier to maintain, especially when dealing with variable environments or complex resource structures.
Check out more examples here.
Arigato!