templates - 在 consul-template 的循环中覆盖变量

标签 templates go consul consul-template

我在领事模板中使用以下模板:

{{ range services }}
  {{ $server_name := .Name | replaceAll "_" "." }}
  {{ range .Tags }}
    {{ if . | regexMatch "server_name=" }}
      # found matching server_name in {{ . }}
      {{ $server_name := . | regexReplaceAll ".*=" "" }}
    {{ end }}
  {{ end }}
  # server_name = {{ $server_name }}
        acl host_{{ .Name }} hdr(host) -i {{ $server_name }}
        use_backend {{ .Name }}_backend if host_{{ .Name }}
{{ end }}

产生

  # found matching server_name in server_name=geoserver.hello.org






  # server_name = geoserver.dev.hello.org
        acl host_geoserver_dev_hello_org hdr(host) -i geoserver.dev.hello.org
        use_backend geoserver_dev_hello_org_backend if host_geoserver_dev_hello_org

其中 .Namegeoserver_dev_hello_org 并且有一个 server_name=geoserver.hello.org 标签。我希望在 .Tags 范围循环结束时,$server_name 应该有值 geoserver.hello.org,但它仍然有它的值geoserver.dev.hello.org 的原始值。

我怎样才能使循环覆盖 $server_name(并在找到值时退出循环)?

最佳答案

consul-template 模板中,您可以使用 the scratch - 在模板的整个生命周期内可用的临时键值存储。

您的代码如下所示:

{{ range services }}
  {{ $server_name := .Name | replaceAll "_" "." }}
  {{ scratch.Set "server_name" $server_name }}
  {{ range .Tags }}
    {{ if . | regexMatch "server_name=" }}
      # found matching server_name in {{ . }}
      {{ $server_name := . | regexReplaceAll ".*=" "" }}
      {{ scratch.Set "server_name" $server_name }}
    {{ end }}
  {{ end }}
  # server_name = {{ scratch.Get "server_name" }}
        acl host_{{ .Name }} hdr(host) -i {{ $server_name }}
        use_backend {{ .Name }}_backend if host_{{ .Name }}
{{ end }}

关于templates - 在 consul-template 的循环中覆盖变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34761716/

相关文章:

amazon-web-services - 在创建打包程序 Ubuntu 镜像时无法查明错误

consul - 如何使用 consul http api 获得 consul kv get -recurse 的相同结果?

c++ - 为使用数组、 vector 、结构等传递给可变参数函数或可变参数模板函数的所有参数指定一种类型?

Go GORM Preload & Select only items 匹配预加载表条件

go - 为什么我的 golang 模板没有选择外部 javascript 文件?

postgresql - 将数组插入 Postgresql 数据库

docker - 如何使其他微服务知道领事馆的IP地址以进行服务注册

c++ - 无权访问模板模板参数

c++ - 模板化静态成员函数所需的语法帮助

c++ - 模拟模板参数的参数相关查找