How to do macro-like templating with parameters in dynamic configuration?

I think I figured this out on my own. The StackOverflow answer I referenced requires outside code, but this dict function is actually provided by the Sprig functions which are included by Traefik. So this playground works:

(Note you can use this to play with Traefik template style, however backticks are not allowed or escapable within a go raw string literal so either remove them or use the hacky workaround shown in the playground example.)

My understanding of how the "pipeline" works when providing an argument to {{template}} is that this argument by definition has to be anonymous/unnamed. So if you want to call something by name within your {{define}}d template, you have two options:

  1. Give the pipeline value a name within the {{define}} block
{{define "proxrouter"}}
    {{ $name := . }}
    prox-{{ $name }}:
      rule: Host(`prox.{{ env "DNS_ZONE" }}`) && PathPrefix(`/{{ $name }}`)
      middlewares:
        - proxyChain
      service: svcprox-{{ $name }}
{{end}}

http:
  routers:
{{template "proxrouter" "pipeline_value"}}
  1. Use the dict Sprig function
{{define "proxrouter"}}
    prox-{{ .Name }}:
      rule: Host(`prox.{{ env "DNS_ZONE" }}`) && PathPrefix(`/{{ .Name }}`)
      middlewares:
        - proxyChain
      service: svcprox-{{ .Name }}
{{end}}

http:
  routers:
{{template "proxrouter" dict "Name" "dict_value"}}

Multiple parameters are accomplished simply by adding further name-value pairs as arguments to dict per the docs:

1 Like