You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Terraform嵌套循环中获取各级循环的索引编号

Terraform循环中获取一级、二级索引的实现

在Terraform的for表达式里,针对map和列表两种集合类型,获取循环索引的方式如下:

  • 二级循环遍历的是列表,直接通过for 索引变量, 元素变量 in 列表的语法就能拿到索引
  • 一级循环遍历的是map,由于map本身无序,需先提取所有key的列表,再用index()函数定位当前key的位置(Terraform 0.12+会保留map定义时的key顺序,若依赖顺序需确保yaml结构稳定)

修改后的完整代码:

locals {
  config_path       = "file.yaml"
  file_content      = yamldecode(file(local.config_path))
  ou_contents       = local.file_content.org.ou
  ou_departments    = keys(local.ou_contents)
  flattened_content = flatten([
    for client_department, client_list in local.ou_contents : [
      for i, client in client_list : {
        client_department_name     = client_department
        client_name                = client
        1st_level_loop_index_number = index(local.ou_departments, client_department)
        2nd_level_loop_index_number = i
      }
    ]
  ])   
}

说明

  • 一级索引:通过keys()提取所有部门名称的列表,再用index()获取当前部门在列表中的位置,索引从0开始
  • 二级索引:遍历客户端列表时,直接声明索引变量i,即可拿到当前客户端的位置,索引从0开始

若需要索引从1开始,只需在对应字段后加1,例如:
1st_level_loop_index_number = index(local.ou_departments, client_department) + 1
2nd_level_loop_index_number = i + 1

内容的提问来源于stack exchange,提问作者Kim G.

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 12:48:29