有谁知道如何将 consul 的字符串连接到 consul-template?
如果我在 Consul 中注册了一个服务 'foo'
{
"Node": "node1",
"Address": "192.168.0.1",
"Port": 3333
},
{
"Node": "node2",
"Address": "192.168.0.2",
"Port": 4444
}
我希望 consul-template 生成以下行:
servers=192.168.0.1:3333,192.168.0.2:4444/bogus
以下尝试无效,因为它留下了尾随逗号 ,
servers={{range service "foo"}}{{.Address}}{{.Port}},{{end}}/bogus
# renders
servers=192.168.0.1:3333,192.168.0.2:4444,/bogus
# What I actually want
servers=192.168.0.1:3333,192.168.0.2:4444/bogus
我知道 consul-template 使用 golang 模板语法,但我就是想不出使它正常工作的语法。我很可能应该使用 consul-template 的 join
但我如何将 .Address
和 .Port
传递给 join
?这只是一个微不足道的例子,我并没有故意使用索引,因为服务的数量可能超过两个。有什么想法吗?
最佳答案
这应该有效。
{{$foo_srv := service "foo"}}
{{if $foo_srv}}
{{$last := len $foo_srv | subtract 1}}
servers=
{{- range $i := loop $last}}
{{- with index $foo_srv $i}}{{.Address}}{{.Port}},{{end}}
{{- end}}
{{- with index $foo_srv last}}{{.Address}}{{.Port}}{{end}}/bogus
{{end}}
我在想是否可以使用“join”。
注意“{{-”表示删除前导空格(如 ' '、\t、\n)。
关于templates - 如何用逗号连接领事模板的服务元数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38574399/