Terraform 检查变量是否存在-地形模板语法

Terraform 检查变量是否存在-地形模板语法,terraform,terraform-template-file,Terraform,Terraform Template File,我试图使用terraform模板语法检查模板文件中是否存在变量,但我得到错误信息,即此对象没有名为“proxy\u set\u header”的属性 $ cat nginx.conf.tmpl %{ for location in jsondecode(locations) } location ${location.path} { %{ if location.proxy_set_header } proxy_set_header ${location.proxy_se

我试图使用terraform模板语法检查模板文件中是否存在变量,但我得到错误信息,即
此对象没有名为“proxy\u set\u header”的属性

$ cat nginx.conf.tmpl

%{ for location in jsondecode(locations) }
location ${location.path} {
    %{ if location.proxy_set_header }
       proxy_set_header ${location.proxy_set_header};
    %{ endif }
}
%{ endfor }
我尝试了
if location.proxy\u set\u header!=“
if location.proxy\u set\u header
,但没有成功


如何检查字符串模板中是否存在变量?

我将使用
contains
键执行以下操作

%{ for location in jsondecode(locations) }
location ${location.path} {
    %{ if contains(keys(location), "proxy_set_header") }
       proxy_set_header ${location.proxy_set_header};
    %{ endif }
}
%{ endfor }
解析后的JSON本质上变成了一个
映射
,可以检查其关键内容

我用以下代码对此进行了测试

data "template_file" "init" {
  template = file("${path.module}/file.template")
  vars = {
    locations = <<DOC
[
  {
    "path": "foo",
    "proxy_set_header": "foohdr"
  },
  {
    "path": "bar"
  }
]
DOC
  }
}

output "answer" {
  value = data.template_file.init.rendered
}

如果您正在使用Terraform 0.12.20或更高版本,则可以使用新功能简洁地编写如下检查:

%{ for location in jsondecode(locations) }
location ${location.path} {
    %{ if can(location.proxy_set_header) }
       proxy_set_header ${location.proxy_set_header};
    %{ endif }
}
%{ endfor }
如果给定表达式的计算结果没有错误,
can
函数将返回true


文档确实建议在大多数情况下优先使用,但在这种特殊情况下,如果该属性不存在,您的目标是什么也不显示,因此我认为,对于未来的读者来说,使用
try
的等效方法更难理解:

%{ for location in jsondecode(locations) }
location ${location.path} {
    ${ try("proxy_set_header ${location.proxy_set_header};", "") }
}
%{ endfor }
除了(主观上)更加不透明的意图之外,这忽略了
try
文档中关于仅将其用于属性查找和类型转换表达式的建议。因此,我认为上面的
can
用法是合理的,因为它相对清晰,但任何一种方法都应该有效

%{ for location in jsondecode(locations) }
location ${location.path} {
    ${ try("proxy_set_header ${location.proxy_set_header};", "") }
}
%{ endfor }