【问题标题】:How to concatenate Service metadata for consul-template with commas如何用逗号连接领事模板的服务元数据
【发布时间】:2016-11-29 04:30:43
【问题描述】:

有谁知道如何将 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 模板语法,但我根本无法弄清楚使这个工作正常的语法。我可能应该使用领事模板的join,但我如何将.Address.Port 都传递给join?这只是一个简单的例子,我没有故意使用索引,因为服务的数量可能超过两个。有什么想法吗?

【问题讨论】:

    标签: templates go consul consul-template


    【解决方案1】:

    这应该可行。

    {{$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}}
    

    我在想是否可以使用“加入”。

    注意“{{-”表示删除前导空格(如''、\t、\n)。

    【讨论】:

      【解决方案2】:

      您可以使用自定义插件。

      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)
      }
      

      【讨论】:

        猜你喜欢
        • 2021-03-21
        • 1970-01-01
        • 2022-01-16
        • 2016-06-22
        • 2018-01-29
        • 2018-05-20
        • 1970-01-01
        • 2018-04-23
        • 1970-01-01
        相关资源
        最近更新 更多