如何在 consul-template 中使用多个标签过滤 consul 节点?
How can I filter consul nodes using multiple tags in consul-template?
我有一些 consul 节点看起来类似于:
[
{
"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 中的服务?
从 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
这就是我在 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 }}
我有一些 consul 节点看起来类似于:
[
{
"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 中的服务?
从 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
这就是我在 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 }}