nginxnginx-reverse-proxyconsulconsul-template

Consul Template - "If Service Exists" condition?


I've just inherited an Nginx proxy/app server setup that makes use of Consul and Consul Template for service discovery and registration. The Nginx proxy has a config file with an entry like this to register the downstream app servers:

<snip>

upstream appservers {
  {{ range service "my-app-servers" }}
     server {{ .Address }}.{{ .Port }};
  {{ end }}
}

<snip>

I have consul-template running in the background to catch any updates to my-app-servers, update the nginx.conf file appropriately, and then reload the nginx config. This all works great, and we're able to add and remove app servers from the mix as needed. That said, if there is a scenario where we have no app servers available, we end up with an empty upstream block and that causes nginx to fail the reload.

Is there a way in consul-template to have "if service my-app-servers exists, then..." and "if not, then..." logic? I'd like to be able to have my nginx.conf file have one configuration for scenarios where upstream servers exist, and another contingency setup that displays error pages when the upstream servers do not exist. I'm still getting up to speed on consul-template and haven't seen any examples that show the syntax for such logic. Any help?


Solution

  • You can achieve this by storing the result of the service lookup in a variable, then using a conditional that only outputs the upstream block if the variable is not empty.

    {{- $upstream_services := service "my-app-servers" -}}
    {{- if $upstream_services -}}
    upstream appservers {
      {{- range $upstream_services }}
         server {{ .Address }}.{{ .Port }};
      {{- end }}
    }
    {{- end }}