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

问题描述 投票:0回答:2

我正在尝试使用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 ...]的属性。]] >

我将使用containskeys进行以下操作>>

%{ 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 } 用法由于其相对清晰而合理,但无论哪种方法都可以。

terraform terraform-template-file
2个回答
0
投票

我将使用containskeys进行以下操作>>

%{ for location in jsondecode(locations) }
location ${location.path} {
    %{ if contains(keys(location), "proxy_set_header") }
       proxy_set_header ${location.proxy_set_header};
    %{ endif }
}
%{ endfor }

0
投票

如果使用的是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,如果给定表达式可以求值而没有错误。

© www.soinside.com 2019 - 2024. All rights reserved.