Module 4: Terraform Configuration

Lesson 4.5: Expressions, Functions, and the Console

for expressions

HCL
locals {
  upper_names = [for n in var.users : upper(n)]                              # list → list
  by_name     = { for n in var.users : n => length(n) }                      # list → map
  medium_only = { for k, v in var.servers : k => v if v.size == "medium" }   # filter with if
  by_size     = { for k, v in var.servers : v.size => k... }                 # grouping: values become lists
}
  • Brackets decide the result type: [ ] produces a tuple or list, and { } produces an object or map.
  • In a map result, duplicate keys are an error unless you use the grouping ... operator.

Splat

var.list[*].id is shorthand for [for o in var.list : o.id]. It works on lists, not maps.

Conditional

condition ? true_value : false_value. Both results must convert to a common type.

The common pattern for optional resources is count = var.enabled ? 1 : 0.

dynamic blocks

A dynamic block generates repeated nested blocks from a collection:

HCL
variable "port_map" {
  type    = map(number)
  default = { "80" = 8080, "443" = 8443 }
}

resource "docker_container" "web" {
  name  = "web"
  image = docker_image.nginx.image_id

  dynamic "ports" {           # the label = the nested block type
    for_each = var.port_map
    content {
      internal = tonumber(ports.key)  # iterator name defaults to the block label
      external = ports.value
    }
  }
}

Use iterator = p to rename the iterator. Use dynamic blocks sparingly, because they reduce readability.

Locals

locals hold named intermediate values, referenced as local.<name>. They aren't inputs, so they can't be set from outside the module.

Functions

  • Terraform has no user-defined functions.
  • There are many built-in functions.
  • Since 1.8, providers can ship provider-defined functions, called as provider::<name>::<function>(...).
Category Functions to know
Collections length, lookup(map, key, default), merge, concat, flatten, keys, values, contains, distinct, element, zipmap, range, sort
Strings format, join, split, replace, lower/upper, trimspace, strcontains
Type and error handling try, can, coalesce, tostring, tolist, toset, tomap
Encoding and files jsonencode, yamlencode, file, templatefile
Network cidrsubnet, cidrhost
Sensitivity sensitive(), nonsensitive()

terraform console

terraform console opens an interactive prompt where you can evaluate expressions against your configuration and current state. It holds a state lock while it's open. Type exit or press Ctrl-D to quit.