DEV Community

Bartłomiej Danek
Bartłomiej Danek

Posted on • Originally published at bard.sh

HCL expressions: for, if, and combining them

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:

d 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"]
}




---
*Originally published at [https://bard.sh/posts/hcl-expressions/](https://bard.sh/posts/hcl-expressions/)*
Enter fullscreen mode Exit fullscreen mode

Top comments (0)