计算 Terraform 列表中的重复字符串出现次数

Count duplicate string occurances in Terraform list

我正在为 Terraform 中看似简单的任务而苦苦挣扎。我会很容易地用 Ruby/Python 和 for 循环内的局部变量来做到这一点,但 Terraform 没有这些。

这里有一个问题。

我有一个包含多个重复字符串的列表:
list = ["a","b","c","a","b","c","a"]

我想计算同一个字符串从头开始出现了多少次,但将计数保持在同一位置,因此结果列表将变成这样:

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

Terraform 可以吗?

我们可以做到以下几点:

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
}

index_list 的输出:

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

第一个 for 循环遍历列表。第二个 for 循环是此过滤列表的 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