Create Terraform Array In a Loop
The other day, I needed to create a multi-SAN TLS certificate in Terraform. The DNS names ended in a number sequence, so you could easily create them in a loop. Now, Terraform has count & for_each loop to create multiple resources. But what if you want to create a variable in a loop? (I am sure some people are screaming Pulumi now.)
Luckily, Terraform has null_resource available, which is exactly what I needed. It creates a virtual resource with a map of strings. So, you can define it in a loop and then use the result to declare a variable.
Here’s example code:
locals { dns_sans = null_resource.dns_sans[*].triggers.dns_name } resource "null_resource" "dns_sans" { count = var.replicas triggers = { dns_name = "service-${count.index}.service-internal" } }
This made my life easier. Maybe it will make yours too.