我正在尝试使用 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 != ""
and if location.proxy_set_header
没有成功。
如何使用字符串模板检查变量是否存在?
如果您使用 Terraform 0.12.20 或更高版本,则可以使用新功能can https://www.terraform.io/docs/configuration/functions/can.html简洁地写出这样的支票:
%{ for location in jsondecode(locations) }
location ${location.path} {
%{ if can(location.proxy_set_header) }
proxy_set_header ${location.proxy_set_header};
%{ endif }
}
%{ endfor }
The can
如果给定的表达式可以无错误地计算,则函数返回 true。
该文档确实建议首选try https://www.terraform.io/docs/configuration/functions/try.html在大多数情况下,但在这种特殊情况下,如果该属性不存在,您的目标是根本不显示任何内容,因此这种等效方法try
我认为对于未来的读者来说更难理解:
%{ for location in jsondecode(locations) }
location ${location.path} {
${ try("proxy_set_header ${location.proxy_set_header};", "") }
}
%{ endfor }
除了(主观上)对于意图更加不透明之外,这还忽略了try
仅将其与属性查找和类型转换表达式一起使用的文档。因此我认为can
由于其相对清晰,上述用法是合理的,但无论哪种方式都应该有效。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)