DEV Community

Bartłomiej Danek
Bartłomiej Danek

Posted on • Originally published at bard.sh

HCL expressions: for, if, and combining them

for - transform a list or map

variable "names" {
  default = ["alice", "bob", "carol"]
}

locals {
  upper_names  = [for n in var.names : upper(n)]
  name_lengths = { for n in var.names : n => length(n) }
}

# upper_names  = ["ALICE", "BOB", "CAROL"]
# name_lengths = { alice = 5, bob = 3, carol = 5 }
Enter fullscreen mode Exit fullscreen mode

if - conditional value

variable "env" {
  default = "prod"
}

locals {
  instance_type = var.env == "prod" ? "t3.large" : "t3.micro"
}
Enter fullscreen mode Exit fullscreen mode

for + if - transform and filter together

variable "users" {
  default = [
    { name = "alice", active = true  },
    { name = "bob",   active = false },
    { name = "carol", active = true  },
  ]
}

locals {
  active_upper = [for u in var.users : upper(u.name) if u.active]
}

# active_upper = ["ALICE", "CAROL"]
Enter fullscreen mode Exit fullscreen mode

iterating over a map

variable "buckets" {
  default = {
    logs    = "us-east-1"
    backups = "eu-west-1"
  }
}

locals {
  bucket_arns = { for name, region in var.buckets : name => "arn:aws:s3:::${name}-${region}" }
}
Enter fullscreen mode Exit fullscreen mode

flattening with flatten()

When you have nested lists - e.g. multiple groups each with multiple ports - use flatten() with for:

locals {
  services = {
    api     = ["8080", "8443"]
    metrics = ["9090"]
  }

  all_ports = flatten([
    for svc, ports in local.services : [
      for port in ports : "${svc}:${port}"
    ]
  ])
  # all_ports = ["api:8080", "api:8443", "metrics:9090"]
}
Enter fullscreen mode Exit fullscreen mode

Originally published at https://bard.sh/posts/hcl_expressions/

Top comments (0)