json 使用地形访问元组中的第一个对象

ss2ws0br  于 2023-01-22  发布在  其他
关注(0)|答案(1)|浏览(135)

我正在尝试访问一个元组的第一个键,这个键的名字是动态的,可能会改变,所以不能用静态值来访问它,必须通过for循环或者使用terraform函数来完成。
我创建了一个小型本地资源,它输出以下部分

skip_empty_mails = { for key, value in local.j.settings.tasks : key => value.email_notifications if value.email_notifications != {} }

返回的输出为

{
  "3" = {
    "on_start" = [
      "foo1@aligntech.com",
      "foo2@aligntech.com",
      "foo3@aligntech.com",
      "foo4@aligntech.com",
    ]
  }
  "4" = {
    "no_alert_for_skipped_runs" = false
    "on_start" = [
      "foo21@aligntech.com",
      "foo22@aligntech.com",
      "foo23@aligntech.com",
      "foo24@aligntech.com",
    ]
    ]
    "on_start" = [
      "foo21@aligntech.com",
      "foo22@aligntech.com",
      "foo23@aligntech.com",
      "foo24@aligntech.com",
    ]
    "on_success" = [
      "foo21@aligntech.com",
      "foo22@aligntech.com",
      "foo23@aligntech.com",
      "foo24@aligntech.com",
    ]
  }
}

如上所述,需要以一种方式访问保存所有值的键,以便能够将其附加到字符串并使用string.on_start提取其值。
问题是我们的密钥名称是动态的,可能会发生变化。
我试过跟踪terraform function documentation,但没有找到任何可能在这种情况下有用的东西。

您可以使用以下代码进行复制

locals {
  json = {
      "3" = {
        "on_start" = [
          "foo1@aligntech.com",
          "foo2@aligntech.com",
          "foo3@aligntech.com",
          "foo4@aligntech.com",
        ]
      },
      "4" = {
        "no_alert_for_skipped_runs" = false
        "on_failure" = [
          "foo21@aligntech.com",
          "foo22@aligntech.com",
          "foo23@aligntech.com",
          "foo24@aligntech.com",
        ]
        "on_start" = [
          "foo21@aligntech.com",
          "foo22@aligntech.com",
          "foo23@aligntech.com",
          "foo24@aligntech.com",
        ]
        "on_success" = [
          "foo1@foo.com",
          "foo2@foo.com",
          "foo3@foo.com",
          "foo4@foo.com",
        ]
    }
  }
}
pxq42qpu

pxq42qpu1#

您可以尝试使用valueselementflatten的组合,请参阅文档:

以下是示例:

第一个密钥提取

locals {
  json = {
      "4" = {
        "no_alert_for_skipped_runs" = false
        "on_failure" = [
          "foo1@foo.com",
          "foo2@foo.com",
        ]
        "on_start" = [
          "foo1@foo.com",
          "foo2@foo.com",
        ]
    }
  }
}

output "data" {
    value = element(values(local.json), 1).on_start
}

Terraform计划将是:

Changes to Outputs:
  + data = [
      + "foo1@foo.com",
      + "foo2@foo.com",
    ]

从所有项目提取并合并on_start项目

locals {
  json = {
      "3" = {
        "on_start" = [
          "foo1@aligntech.com",
          "foo2@aligntech.com",
        ]
      },
      "4" = {
        "on_start" = [
          "foo1@foo.com",
          "foo2@foo.com",
        ]
    }
  }
}

output "data" {
    value = flatten(values(local.json)[*].on_start)
}

Terraform计划将是:

Changes to Outputs:
  + data = [
      + "foo1@aligntech.com",
      + "foo2@aligntech.com",
      + "foo1@foo.com",
      + "foo2@foo.com",
    ]

相关问题