Count duplicate string occurances in Terraform list

Viewed 152

I am struggling with seemingly simple task in Terraform. I would easily do it with Ruby/Python with local variable inside the for loop, but Terraform doesn't have those.

Here is an issue.

I have a list with multiple duplicate string occurances:
list = ["a","b","c","a","b","c","a"]

I want to count how many times the same string occured from the beginning, but keep the count in the same location, so the resulting list would become this:

index_list = [1, 1, 1, 2, 2, 2, 3]

Is it possible with Terraform?

1 Answers

We can do the following:

locals {
  lst = ["a", "b", "c", "a", "b", "c", "a"]

  index_list = [for index, item in local.lst : length([for i in slice(local.lst, 0, index + 1) : i if i == item])]
}

output "index_list" {
  value = local.index_list
}

Output for index_list:

index_list = [
  1,
  1,
  1,
  2,
  2,
  2,
  3,
]

The first for loop iterates through the list. The second for loop is a slice combined with a filter. The slice function creates a sublist from the first element to the index if the current element. With the filter (if i == item) we filter out from this sublist all the elements which are equal to the current element. Last but not least, we get the length of this filtered list.

Related