Terraform template_file 空 Json 验证

Terraform template_file Empty Json validation

我的 Terrform 代码如下所示。这里我的参数文件有时有值,大多数时候是空的 JSON {}

resource "azurerm_policy_assignment" "example" {
  name                 = "example-policy-assignment"
  scope                = azurerm_resource_group.example.id
  policy_definition_id = azurerm_policy_definition.example.id
  description          = "Policy Assignment created via an Acceptance Test"
  display_name         = "My Example Policy Assignment"

  parameters           = "${data.template_file.policy_parameters_file.rendered}"

所以我需要做一些验证来检查我的参数文件是否为空 json 然后我需要分配一个空字符串。

我试过如下但它不起作用

"${data.template_file.policy_parameters_file.rendered}" == {} ? "" : "${data.template_file.policy_parameters_file.rendered}"

需要进行此验证,因为状态文件的参数值为“”。现在,如果我 运行 terraform 计划显示为

parameters           = jsonencode({}) # forces replacement 

强制置换

如果我将参数硬编码为“”,一切顺利。因此,为了处理这个问题,我需要找到一种方法来处理参数文件中空 json 的验证。如果 json 为空,我需要传递为 ""

听起来你有一个生成 JSON 的模板,但它有时会生成一个空的 JSON 对象,在这种特殊情况下你更愿意完全不设置这个参数而不是设置字面意思是 "{}".

如果是这样,我认为您尝试的问题是您将字符串 "{}" 与一个真正的空对象 {} 进行了比较,这将始终 return false 因为字符串和对象没有可比性。 (作为一般规则,对于不同类型的值,== 总是 returns false。)

如果你知道空对象大小写总是字面上的字符串 "{}",而不是任何其他等价物 JSON,例如 "{ }"(带有 space在大括号之间),那么你可以写一个与你写的非常相似的表达式,除了与那个字符串进行比较:

  parameters = (
    data.template_file.policy_parameters_file.rendered != "{}" ?
    data.template_file.policy_parameters_file.rendered :
    null
  )

如果你想变得更健壮一点并捕获 JSON 对象的任何有效编码,你可以编写一个稍微更复杂的表达式,如下所示:

  parameters = (
    length(jsondecode(data.template_file.policy_parameters_file.rendered)) > 0 ?
    data.template_file.policy_parameters_file.rendered :
    null
  )

这会将 JSON 再次解码回真实对象,然后测试它是否至少具有一个属性。


请注意,对于使用 Terraform v0.12.0 或更高版本的任何人,template_file 数据源已被弃用。虽然摆脱它并不是获得如上所述的工作结果所必需的,但我建议还计划在将来迁移到 the templatefile function,因为它将持续得到支持并且已集成正确地融入 Terraform 语言,这样它就可以避免来自外部插件中实现的 template_file 数据源的各种奇怪的怪癖。