terraform temporary/intermediate 循环中的变量?

terraform temporary/intermediate variables in loops?

我想知道是否可以在 for 循环中使用临时变量进行中间计算。如果是,使用它的语法是什么,简化示例只是为了说明问题。此示例代码有效。我已经评论了不起作用的部分,但想知道如何使用中间变量。谢谢!


locals {
  nestedmap = <<-EOT
  user-john:
    db:  "db34"
    tables:
      t1:
        rows: 4
      t2:
        rows: 8
  user-chris:
    db:  "db22"
    tables:
      t1:
        rows: 3
      t2:
        rows: 7
  user-mary:
    db:  "db78"
    tables:
      t1:
        rows: 2
      t2:
        rows: 10
  EOT

  flatlist = flatten([
    for ux_key, ux_val in yamldecode(local.nestedmap): [
      for tx_key, tx_val in ux_val.tables: {
        pfx = trimprefix(ux_key, "user-")
        #key = "${pfx}-${tx_key}"
        key = "${trimprefix(ux_key, "user-")}-${tx_key}"
        db = ux_val.db
        rows = tx_val.rows
      }
    ]
  ])
  flatmap = {for fx in local.flatlist:  fx.key => fx}
}

TF中没有中间变量。您只需 重复 trimprefix(ux_key, "user-"):

  flatlist = flatten([
    for ux_key, ux_val in yamldecode(local.nestedmap): [
      for tx_key, tx_val in ux_val.tables: {
        pfx = trimprefix(ux_key, "user-")
        key = "${trimprefix(ux_key, "user-")}-${tx_key}"
        db = ux_val.db
        rows = tx_val.rows
      }
    ]
  ])

有兴趣对此进行更多讨论的任何人,请查看 - https://www.reddit.com/r/Terraform/comments/t03nfr/terraform_temporaryintermediate_variables_in_loops/

在这里分享,对遇到类似问题的其他人有用