Jose Leon
Jose Leon

Reputation: 1651

How to concatenate Service metadata for consul-template with commas

Does anyone know how to concatenate strings from consul for consul-template?

If I have a service 'foo' registered in Consul

{
  "Node": "node1",
  "Address": "192.168.0.1",
  "Port": 3333
},
{
  "Node": "node2",
  "Address": "192.168.0.2",
  "Port": 4444
}

I would like consul-template to generate the following line:

servers=192.168.0.1:3333,192.168.0.2:4444/bogus

The following attempt does not work since it leaves a trailing comma ,

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

I know consul-template uses golang template syntax, but I simply cannot figure out the syntax to get this working. Its likely that I should use consul-template's join but how do I pass both .Address and .Port to join? This is just a trivial example, and I'm not using indexes intentionally since the number of services could be more than two. Any ideas?

Upvotes: 5

Views: 2503

Answers (2)

Frank Wong
Frank Wong

Reputation: 1826

This should work.

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

I was thinking if "join" can be used.

Note "{{-" means removing leading white spaces (such ' ', \t, \n).

Upvotes: 5

Brrrr
Brrrr

Reputation: 4598

You can use a custom plugin.

servers={{service "foo" | toJSON | plugin "path/to/plugin"}}

The plugin code:

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

Upvotes: 0

Related Questions