Search code examples
environment-variablestraefik

define environment variable in traefik2 to be used in the file provider


How would one define environment variables for traefik2 so that they could be used within the dynamic file configuration ? e.g:

[http.routers]
  [http.routers.the-rtr]
    entrypoints = https
    rule = Host(`rtr.$DOMAINNAME`)

where DOMAINNAME would have been defined somewhere (in a file, CLI arguments etc.)


Solution

  • Traefik's dynamic configuration does accept Go templating:

    Traefik supports using Go templating to automatically generate repetitive portions of configuration files. These sections must be valid Go templates, augmented with the Sprig template functions.

    See https://doc.traefik.io/traefik/providers/file/#go-templating

    Note that Go Templating only works with dedicated dynamic configuration files. Templating does not work in the Traefik main static configuration file.

    For example, if $DOMAINNAME is set as an environment variable, you can do

    rule: Host(`{{ env "DOMAINNAME" | trimAll "\"" }}`)
    

    Note: due to "env" quoting, the trimAll is needed — it might be better solution, but it's the better I've found so far.