Consul-template: Add contains(All|Any|None|Notall) functions

Created on 11 Dec 2016  路  3Comments  路  Source: hashicorp/consul-template

These functions allow selection based on multiple tags without having to write templates such as

{{ if (contains $tag1 .Tags) and (contains $tag2 .Tags) }}
# ...
{{ end }}

or without having to resort to nested range constructs if the number of tags to match is not known a priori.

containsAll

Returns true if all needles are within an iterable element,
or false otherwise.
Returns true if the list of needles is empty.

{{ if containsAll $requiredTags .Tags }}
# ...
{{ end }}

containsAny

Returns true if any needle is within an iterable element,
or false otherwise.
Returns false if the list of needles is empty.

{{ if containsAny $acceptableTags .Tags }}
# ...
{{ end }}

containsNone

Returns true if no needles are within an iterable element,
or false otherwise.
Returns true if the list of needles is empty.

{{ if containsNone $forbiddenTags .Tags }}
# ...
{{ end }}

containsNotall

Returns true if some needle is not within an iterable element,
or false otherwise.
Returns false if the list of needles is empty.

{{ if containsNotall $excludingTags .Tags }}
# ...
{{ end }}

Most helpful comment

@rickardrosen The bigger issue with using these functions is that the go-template language does not support arrays as literals. But, with consul-template, parseJSON may help you.

Here is a simple example:

{{- $requiredTags := parseJSON `["production","backend"]` -}}

{{- range service "pg" -}}
{{- if .Tags | containsAll $requiredTags -}}

{{ .Name }} {{ .Address }}:{{ .Port }}

{{ end }}{{ end -}}

All 3 comments

This has been merged. Thanks!

@aferreira: I'm trying to figure out how to consume these functions, but TBH, the needle, haystack and iterable elements are confusing me, most likely due to my lacking knowledge of go.

The only reference I could find pointed me to the go-template source code, which gave me a 404.

I'd like to be able to require tags "production" and "backend". Perhaps you could throw in an example regarding how to end up with an iterable "$requiredTags" in a template?

@rickardrosen The bigger issue with using these functions is that the go-template language does not support arrays as literals. But, with consul-template, parseJSON may help you.

Here is a simple example:

{{- $requiredTags := parseJSON `["production","backend"]` -}}

{{- range service "pg" -}}
{{- if .Tags | containsAll $requiredTags -}}

{{ .Name }} {{ .Address }}:{{ .Port }}

{{ end }}{{ end -}}
Was this page helpful?
0 / 5 - 0 ratings