【问题标题】:Iterate over list of list of maps in terraform遍历 terraform 中的地图列表列表
【发布时间】:2019-08-24 13:24:25
【问题描述】:

假设我有一个变量,它是地图列表的列表。

例子:

    processes = [
      [
       {start_cmd: "a-server-start", attribute2:"type_a"}, 
       {start_cmd: "a-worker-start", attribute2:"type_b"}
       {start_cmd: "a--different-worker-start", attribute2:"type_c"}
      ],
      [
       {start_cmd: "b-server-start", attribute2:"type_a"},
       {start_cmd: "b-worker-start", attribute2:"type_b"}
      ]
    ]

在每次迭代中,我需要取出地图数组,然后遍历该数组并取出地图的值。如何在 terraform 中实现这一点?

我考虑过两次计数并做一些算术来欺骗 terraform 执行相似的嵌套迭代 Check reference here。但在我们的例子中,内部数组中的地图数量可能会有所不同。

此外,我们目前正在使用 0.11 terraform 版本,但如果可以在该版本中实现这一点,请不要介意使用 terraform 的 alpha 0.12 版本。

编辑:

添加了我将如何使用这个变量:

resource “create_application” “applications” {
  // Create a resource for every array in the variable processes. 2 in this case
  name        = ""              
  migration_command = "" 

  proc {                
    // For every map create this attribute for the resource.
    name    = ““                
    init_command   = “a-server-start”                   
    type   = “server”                
  }                                    
}                                      

不确定这是否能满足要求。如果还不清楚,请询问。

【问题讨论】:

  • 你想在这里看到什么输出?
  • 我添加了一个编辑来解决这个问题
  • 如果我从发行说明中没记错的话,这是第一次包含在 0.12 中。
  • 我们查看了 0.12-beta 版本,但无法找到解决方法。如果可能的话,您能否展示一种使用 0.12 测试版进行嵌套迭代的工作方式?

标签: nested iteration terraform


【解决方案1】:

使用 terraform 0.12.x

locals {
  processes = [
    [
      { start_cmd: "a-server-start", type: "type_a", name: "inglorious bastards" },
      { start_cmd: "a-worker-start", type: "type_b", name: "kill bill" },
      { start_cmd: "a--different-worker-start", type: "type_c", name: "pulp fiction" },
    ],
    [
      { start_cmd: "b-server-start", type: "type_a", name: "inglorious bastards" },
      { start_cmd: "b-worker-start", type: "type_b", name: "kill bill" },
    ]
  ]
}

# just an example
data "archive_file" "applications" {
  count = length(local.processes)

  type = "zip"

  output_path = "applications.zip"

  dynamic "source" {
    for_each = local.processes[count.index]

    content {
      content  = source.value.type
      filename = source.value.name
    }
  }
}
$ terraform apply
data.archive_file.applications[0]: Refreshing state...
data.archive_file.applications[1]: Refreshing state...

Apply complete! Resources: 0 added, 0 changed, 0 destroyed.

如果存在create_application 资源,则可以这样建模

resource "create_application" "applications" {
  count             = length(local.processes)
  name              = ""
  migration_command = "" 

  dynamic "proc" {
    for_each = local.processes[count.index]

    content {
      name         = proc.value.name
      init_command = proc.value.start_cmd
      type         = proc.value.type
    }
  }
}

【讨论】:

    猜你喜欢
    • 2017-07-23
    • 2019-03-21
    • 2019-07-23
    • 2020-05-18
    • 2022-01-13
    • 1970-01-01
    • 2022-07-06
    • 1970-01-01
    相关资源
    最近更新 更多