在 terraform 中使用给定条件从 json 打印

print from json with a given condition in terraform

最近迷上了terraform世界,按要求学习。我对在给定条件下打印值有疑问

json 文件:

{
    "team1" : [
        {
            "engg_name" : "Alex",
            "guid" : 1001,
            "scope" : "QA"
        },        
        {
            "engg_name" : "Trex",
            "guid" : 1002,
            "scope" : "QA"
        },        
        {
            "engg_name" : "Jessica",
            "guid" : 1003,
            "scope" : "QA"
        },
        {
            "engg_name" : "Tom",
            "guid" : 1004,
            "scope" : "DEV"
        }
    ],
    "team2" : [
        {
            "engg_name" : "Roger",
            "guid" : 2001,
            "scope" : "DEV"
        },
        {
            "engg_name" : "Jhonny",
            "guid" : 2002,
            "scope" : "DEV"
        }
    ]
}

我在尝试什么:

打印 engg,其范围是 json 文件

中的 DEV
   locals {
     teams = jsondecode(file("${path.module}/teams_info.json"))
    
    engg_with_scope_dev =  flatten([for i in local.teams : i.teams if keys(local.teams).scope == "DEV"])
    
    }

错误:

    engg_with_scope_dev =  flatten([for i in local.teams : i.teams if keys(local.teams).scope == "DEV"])
    |----------------
    | local.teams is object with 2 attributes

This value does not have any attributes.

有人可以建议我根据条件打印的正确方法是什么吗?

输出必须如下:

engg_with_scope_dev = ["Tom", "Roger", "Jhonny"] 

为此您需要一个嵌入式 for 循环:

locals {
  teams = jsondecode(file("${path.module}/teams_info.json"))

  engg_with_scope_dev = flatten([for team in local.teams : [
    for engineer in team : engineer.engg_name if engineer.scope == "DEV"
  ]])
}

其他解决方案是使用带有 ellipsis 运算符的列表串联:

locals {
  teams = jsondecode(file("${path.module}/teams_info.json"))

  engg_with_scope_dev = ([
    for engineer in concat(values(local.teams)...) : engineer.engg_name if engineer.scope == "DEV"
  ])
}

而且,简单的 flatten with values 也可以:

locals {
  teams = jsondecode(file("${path.module}/teams_info.json"))

  engg_with_scope_dev = ([
    for engineer in flatten(values(local.teams)) : engineer.engg_name if engineer.scope == "DEV"
  ])
}