如何在consul-template中使用多个标签过滤consul节点?

时间:2015-12-09 21:14:54

标签: nginx consul go-templates

我有许多看起来类似于以下的领事节点:

 [
    {
        "Address": "127.0.0.1",
        "Node": "foo",
        "ServiceAddress": "",
        "ServiceName": "api",
        "ServicePort": 8100,
        "ServiceTags": [
            "production",
            "blocking"
        ]
    },
    {
        "Address": "127.0.0.1",
        "Node": "foo",
        "ServiceAddress": "",
        "ServiceName": "api",
        "ServicePort": 8101,
        "ServiceTags": [
            "production",
            "nonblocking"
        ]
    }
]

通过一个标签过滤很简单:

{{range service "production.api"}}
{{.Address}}
{{end}}

但是如何一次用两个标签过滤我的consul-template中的服务?

2 个答案:

答案 0 :(得分:2)

从consul-template v0.11.1开始,您可以使用contains运算符执行以下操作:

{{range service "production.api"}}
{{if .Tags | contains "nonblocking"}}
{{.Address}}
{{end}}
{{end}}

如果您使用的是旧版本,则可以使用Go:

{{range service "api"}}
{{if and (.Tags.Contains "nonblocking") (.Tags.Contains "production")}}
{{end}}
{{end}}

另见:https://github.com/hashicorp/consul-template/issues/260

答案 1 :(得分:0)

这就是我在haproxy中使用服务标签的方式,因此可以在nginx中进行类似的

{{ range $tag, $services := service "some-service" | byTag }}
backend some-service-{{ $tag }}

   {{ if eq $tag "some_tag" }}
   ....
   {{ end }}
   ...

   {{ range $services }}
   server {{.Address}}-{{.Port}} {{.Address}}:{{.Port}} check downinter 3s inter 2000 fall 3 maxconn 100 check cookie {{.ID}} weight 1
   {{ end }}
{{ end }}