consul-template
consul-template copied to clipboard
Defining consul-template based on hostname environment variable
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
- Write block with the template lines above in consul template file.
- Run consul-template.
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 }}