谁知道如何将consul中的字符串连接成consul-template?
如果我在领事馆注册了服务'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?这只是一个微不足道的例子,我并不是故意使用索引,因为服务的数量可能超过两个。有什么想法吗?
发布于 2017-03-06 15:15:40
这应该是可行的。
{{$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)。
发布于 2016-07-26 15:14:43
您可以使用自定义插件。
servers={{service "foo" | toJSON | plugin "path/to/plugin"}}插件代码:
package main
import (
"encoding/json"
"fmt"
"os"
)
type InputEntry struct {
Node string
Address string
Port int
}
func main() {
arg := []byte(os.Args[1])
var input []InputEntry
if err := json.Unmarshal(arg, &input); err != nil {
fmt.Fprintln(os.Stderr, fmt.Sprintf("err: %s", err))
os.Exit(1)
}
var output string
for i, entry := range input {
output += fmt.Sprintf("%v:%v", entry.Address, entry.Port)
if i != len(input)-1 {
output += ","
}
}
fmt.Fprintln(os.Stdout, string(output))
os.Exit(0)
}https://stackoverflow.com/questions/38574399
复制相似问题