Cae*_*chi 4 terraform terraform-template-file
我正在尝试使用 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 }
Run Code Online (Sandbox Code Playgroud)
我尝试过if location.proxy_set_header != "",if location.proxy_set_header但没有成功。
如何检查字符串模板中是否存在变量?
如果您使用的是 Terraform 0.12.20 或更高版本,那么您可以使用新函数can来简洁地编写如下检查:
%{ for location in jsondecode(locations) }
location ${location.path} {
%{ if can(location.proxy_set_header) }
proxy_set_header ${location.proxy_set_header};
%{ endif }
}
%{ endfor }
Run Code Online (Sandbox Code Playgroud)
can如果给定的表达式可以计算而没有错误,则该函数返回 true。
文档确实建议try在大多数情况下更喜欢,但在这种特殊情况下,如果该属性不存在,您的目标是根本不显示任何内容,因此try我认为这种等效的方法对于未来的读者来说更难理解:
%{ for location in jsondecode(locations) }
location ${location.path} {
${ try("proxy_set_header ${location.proxy_set_header};", "") }
}
%{ endfor }
Run Code Online (Sandbox Code Playgroud)
除了(主观上)对意图更加不透明之外,这忽略了try文档中仅将其用于属性查找和类型转换表达式的建议。因此,我认为can上面的用法是合理的,因为它相对清晰,但无论哪种方式都应该可行。
| 归档时间: |
|
| 查看次数: |
5093 次 |
| 最近记录: |