我将使用contains
和keys
进行以下操作>>
%{ for location in jsondecode(locations) }
location ${location.path} {
%{ if contains(keys(location), "proxy_set_header") }
proxy_set_header ${location.proxy_set_header};
%{ endif }
}
%{ endfor }
我正在尝试使用terraform模板语法检查模板文件上是否存在变量,但出现This object does not have an attribute named "proxy_set_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_set_header != ""
和if location.proxy_set_header
失败,]。>
如何检查字符串模板是否存在变量?
我正在尝试使用terraform模板语法检查模板文件上是否存在变量,但是我收到错误消息,该对象没有名为“ proxy_set_header。$ cat nginx.conf.tmpl ...]的属性。]] >
我将使用contains
和keys
进行以下操作>>
%{ 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本质上变成了map
,可以检查其关键内容。
我使用以下代码对此进行了测试
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 }
并且它具有以下输出
Outputs:
answer =
location foo {
proxy_set_header foohdr;
}
location bar {
}
如果使用的是Terraform 0.12.20或更高版本,则可以使用新功能can
简洁地编写如下支票:
can
%{ for location in jsondecode(locations) }
location ${location.path} {
%{ if can(location.proxy_set_header) }
proxy_set_header ${location.proxy_set_header};
%{ endif }
}
%{ endfor }
函数将返回true,如果给定表达式可以求值而没有错误。
[文档的确建议在大多数情况下更喜欢can
,但是在这种特殊情况下,您的目标是在不存在该属性的情况下完全不显示任何内容,因此,我认为try
的这种等效方法更难了解未来的读者:
try
以及在意图上(主观上)更加不透明,这忽略了
try
文档中关于仅将其与属性查找和类型转换表达式一起使用的建议。因此,我认为上述%{ for location in jsondecode(locations) } location ${location.path} { ${ try("proxy_set_header ${location.proxy_set_header};", "") } } %{ endfor }
用法由于其相对清晰而合理,但无论哪种方法都可以。
我将使用contains
和keys
进行以下操作>>
%{ for location in jsondecode(locations) }
location ${location.path} {
%{ if contains(keys(location), "proxy_set_header") }
proxy_set_header ${location.proxy_set_header};
%{ endif }
}
%{ endfor }
如果使用的是Terraform 0.12.20或更高版本,则可以使用新功能can
简洁地编写如下支票:
can
%{ for location in jsondecode(locations) }
location ${location.path} {
%{ if can(location.proxy_set_header) }
proxy_set_header ${location.proxy_set_header};
%{ endif }
}
%{ endfor }
函数将返回true,如果给定表达式可以求值而没有错误。