Consul-template how to filters services where service name not contains specific string

Hi,
I’m trying to figure out how filter services which not contains specifix string in it’s name. I can do the opposite with contains function like:

{{ range services }}
  {{  if  .Name | contains "sidecar"  }}
    {{ .Name }}
  {{ end }}
{{ end }}

This will filter services which name contains “sidecar”. However there is no notcontains helper function so how can I filter services which names not contains sidecar?
Thank you in advance.

Hi @andriktr,

Consul template uses the Go template format which contains a built-in not function that you can use to achieve what you’re looking for.

Given the service output below:

$ consul catalog services
consul
counting
counting-sidecar-proxy
dashboard
dashboard-sidecar-proxy
hashicorp-consul-connect-injector-svc-consul
hashicorp-consul-dns-consul
hashicorp-consul-mesh-gateway-consul
hashicorp-consul-server-consul
hashicorp-consul-ui-consul
ingress-gateway
kubernetes-default
mesh-gateway
nginx
nginx-sidecar-proxy
nomad
nomad-client
terminating-gateway

I can use the following template to produce a list of service names, omitting those which contain the word “sidecar.”

# not-contains.ctmpl
{{- range services -}}
  {{-  if  .Name | contains "sidecar" | not }}
    {{ .Name -}}
  {{- end -}}
{{- end -}}
$ consul-template -template "not-contains.ctmpl:out.txt" -once -dry
> out.txt

    consul
    counting
    dashboard
    hashicorp-consul-connect-injector-svc-consul
    hashicorp-consul-dns-consul
    hashicorp-consul-mesh-gateway-consul
    hashicorp-consul-server-consul
    hashicorp-consul-ui-consul
    ingress-gateway
    kubernetes-default
    mesh-gateway
    nginx
    nomad
    nomad-client
    terminating-gateway
2 Likes

@blake Thanks for help.
I actually achieved the same with:

{{range services}}
 {{ if .Name | contains "sidecar" }}
 {{- else -}}
   {{ .Name -}}
   {{ range service .Name }}
     {{ .Address -}}
   {{- end -}}
 {{- end -}}
{{- end -}}

But your proposal is definitely is more accurate.
Thanks.

1 Like