hashicorp / consul-template

Template rendering, notifier, and supervisor for @HashiCorp Consul and Vault data.
https://www.hashicorp.com/
Mozilla Public License 2.0
4.76k stars 783 forks source link

Defining consul-template based on hostname environment variable #1371

Open zefferno opened 4 years ago

zefferno commented 4 years ago

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.
thevilledev commented 1 year ago

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