consul-template icon indicating copy to clipboard operation
consul-template copied to clipboard

Defining consul-template based on hostname environment variable

Open zefferno opened this issue 5 years ago • 1 comments

Consul Template version

consul-template v0.16.0

Configuration

    {{ $host := env "HOSTNAME" }}
    {{ $regex := "^b" }}
    {{ if $host | regexMatch "^a" }}{{ $regex := "^a" }}{{ end }}
    {{ range service "service-name" }}
    {{- if .Node | regexMatch $regex -}}server {{.Node}} {{.Address}}:{{.Port}}
    {{ end }}{{ end }}

Expected behavior

Since hostname starts with "a" - I expect to get nodes which match regex "^a".

Actual behavior

Consul-template renders nodes which match regex "^b".

Steps to reproduce

  1. Write block with the template lines above in consul template file.
  2. Run consul-template.

zefferno avatar Apr 21 '20 19:04 zefferno

Modifying template variables by assignments has been possible since Go 1.11. The given configuration overrides regex in another scope, rendering it useless outside of the if block. Should be like this:

    {{ if $host | regexMatch "^a" }}{{ $regex = "^a" }}{{ end }}

For more complex cases you could also use a scratch set like this:

{{ $host := env "HOSTNAME" }}
{{ scratch.Set "regex" "^b" }}
{{ if $host | regexMatch "^a" }}{{ scratch.Set "regex" "^a" }}{{ end }}
{{ $regex := scratch.Get "regex" }}
{{ range service "service-name" }}
{{- if .Node | regexMatch $regex -}}server {{.Node}} {{.Address}}:{{.Port}}
{{ end }}{{ end }}

thevilledev avatar Dec 03 '22 16:12 thevilledev