0

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.)

Chapo
  • 2,563
  • 3
  • 30
  • 60

2 Answers2

1

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.

ponsfrilus
  • 1,010
  • 1
  • 17
  • 25
0

Not sure if it's directly supported from traefik product. I use file provider and in traefik.toml, I have:

  [providers.file]
    filename = "/etc/traefik/dynamic.config.toml"
    watch = true

And I use separate mechanism like envsubst to generate (or regenerate as needed) the dynamic.config.toml file. Since I've watch = true, it gets loaded with latest info by traefik

Basically, the snipped you shared in the question can be used as a template file. Then use envsubst or similar to generate dynamic.config.toml.

Q&A on envsubst that I found useful: How to substitute shell variables in complex text files

Hope that helps.

Phani Kandula
  • 387
  • 2
  • 3
  • thks - might try this if I'm really desperate (I have it working ok in the docker-compose environment where you can actually define environment variables). I was hoping for a 100% traefik solution. – Chapo May 18 '20 at 02:14