【问题标题】:terraform json map regex lookup and using loops properlyterraform json映射正则表达式查找和正确使用循环
【发布时间】:2022-07-28 07:40:57
【问题描述】:

所以我在下面有一个 json 文件,我绝对可以根据需要对其进行重组,但它是我开始的。它必须是任何类型的 terraform 的外部格式。我基于看似简单的兼容性选择了json。

我希望能够遍历下面 json 文件中的所有正则表达式模式(我截断了这个列表),如果正则表达式模式与 testcomputer 匹配,则将 ou 值返回给另一个局部变量。一个警告,我不确定我是否有问题,是 json 需要转义 \\ 。在命令式编程语言中,我只是用一个 switch/case 节或执行评估的方法来处理这个问题。不知道如何最好地使用 HCL 做到这一点。

ou.json:

{
  \"ProdInf\": {
    \"regex\": \"/^(?i)nyinf-p(\\\\d+)/\",
    \"ou\": \"OU=Inf,OU=Prod,OU=Servers,DC=example,DC=local\"
  },
  \"ProdHyperV\": {
    \"regex\": \"/^(?i)nyhyp-p(\\\\d+)/\",
    \"ou\": \"OU=HyperV,OU=Prod,OU=Servers,DC=example,DC=local\"
  },
  \"ProdRDS\": {
    \"regex\": \"/^(?i)nyrds-p(\\\\d+)/\",
    \"ou\": \"OU=RDS,OU=Prod,OU=Servers,DC=example,DC=local\"
  }
}

我有一些初始的 terraform 代码(人为并基于我的实际问题),但我无法弄清楚如何从这里开始。:

locals {
  testcomputer = \"nyhyp-p29\"
  map1 = jsondecode(file(\"./ou.json\"))
  # started to play with loops here, but not really sure how to do what I am want.
  oulist = [for ou in local.map1 : ou].*.ou
  regexlist = [for regex in local.map1 : regex].*.regex
  test_computer_ou = # this is the desired value I am trying to get
}

    标签: terraform terraform-provider-aws hcl


    【解决方案1】:

    您可能希望将 json 文件修改为如下所示:

    {
        "ProdInf": {
            "regex": "^(?i)nyinf-p(\\d+)$",
            "ou": "OU=Inf,OU=Prod,OU=Servers,DC=example,DC=local"
        },
        "ProdHyperV": {
            "regex": "^(?i)nyhyp-p(\\d+)$",
            "ou": "OU=HyperV,OU=Prod,OU=Servers,DC=example,DC=local"
        },
        "ProdRDS": {
            "regex": "^(?i)nyrds-p(\\d+)$",
            "ou": "OU=RDS,OU=Prod,OU=Servers,DC=example,DC=local"
        }
    }
    

    根据您的问题,我了解到您正在寻找完整的匹配项,因此我添加了正则表达式锚点。

    局部变量如下:

    locals {
      testcomputer = "nyhyp-p29"
      map1 = jsondecode(file("./ou.json"))
      oulist = [for ou in local.map1 : ou].*.ou
      regexlist = [for regex in local.map1 : regex].*.regex
      test_computer_ou = [for key, value in local.map1: value.ou if length(regexall(value.regex, local.testcomputer)) == 1]
    }
    

    test_computer_ou 的值将是:

    output "test_computer_ou" {
      value = local.test_computer_ou
    }
    

    产值:

    test_computer_ou = [
      "OU=HyperV,OU=Prod,OU=Servers,DC=example,DC=local",
    ]
    

    【讨论】:

    • 这完全符合预期。感谢您的快速响应并了解如何使用 length(regexall()) 来验证条件!特维姆!!!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-08-31
    • 1970-01-01
    • 1970-01-01
    • 2022-11-02
    • 2023-02-01
    • 1970-01-01
    • 2020-12-14
    相关资源
    最近更新 更多