Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

This is what you get if you want a declarative syntax. HCL doesn't have any concept of a for loop, and can't have any concept of a for loop— it's a data serialization format. Terraform can be transformed to and from JSON losslessly. The looping feature is implemented in Terraform.

Ansible's with_items: and loop: do the exact same thing with YAML.



Declarative languages can absolutely loop. Otherwise functional languages wouldn't be a thing.

HCL's looping and conditionals are a mess but they're wonderful in comparison to its facilities for defining and calling functions.


The concept of repeated operations executing with respect to some condition is always going to be a bit different in declarative / functional constructs than in imperative ones. A purely functional language is never going to have the equivalent of: for (...) a++;

Good functional languages like Clojure make something like this awkward and painful to do, because it doesn't really make sense in a functional context.


I think you missed the error message; I wasn't whining about for_each syntax masquerading as if it was a property of the resource, I was pointing out the moronic behavior of attempting to iterate over a list of strings and being given the finger

It is claiming the provided thing is not a set of strings it's a tuple

The fix is

    for_each = toset(var.my_list)
but who in their right mind would say "oh, I see you have a list of things, but I only accept unordered things"


It's not about them being ordered it's about them being unique. You're generating a resource for each element and that resource has a unique name. The stackoverflow way to iterate over a list is to use toset() but more often what people want is

    zipmap(range(length(var.my_list)), var.my_list)
where you get {0 => item, 1=>item} and your resources will be named .0, .1, .2. I get the annoyance about the type naming but in HCL lists and tuples are the same thing.


> It's not about them being ordered it's about them being unique

Ok, so which one of ["a", "b"] in my example isn't unique?

And I definitely, unquestionably, never want resources named foo.0 and foo.1 when the input was foo.alpha and foo.beta


I'm confused by your question, lists don't enforce uniqueness—you can do ["a", "a"] and it's perfectly valid. Sets and the key values of hash maps can't have repeating elements. You can for_each over lists that come from a data block so you can't statically know if a list is effectively a set.

If you don't want .0, .1 then you agree with Terraform's design because that's the only way you could for_each over an arbitrary list that might contain duplicate values. Terraform making you turn your lists into sets gets you what you want.




Consider applying for YC's Summer 2026 batch! Applications are open till May 4

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: