How to use environment variables in the dynamic configuration (using file provider)?

This is actually a follow up question of How to define an external service in a docker compose yaml file?

So I am using a file provider with following dynamic configuration (yaml file):

http:
  routers:
    pi3one:
      entryPoints:
        - "websecure"
      rule: "Host(`pi3one.mymachine.somewhere.com`)"
      middlewares:
        - traefik_auth@docker
        - add_ui_to_path
      tls:
        certResolver: mytlschallenge
      service: pi3one

Instead of hardcoding pi3one.mymachine.somewhere.com in the file I want to set this through an environment variable (e.g. $PI3ONE_HOSTNAME).

How can I do this ?

I have tried using sprig functions as is suggested in How to define an external service in a docker compose yaml file? but couldn't get this working.

A working example would help me a lot.

1 Like

Hello,

A simple example:

http:
  routers:
    pi3one:
      entryPoints:
        - "websecure"
      rule: "Host(`{{env "PI3ONE_HOSTNAME"}}`)"
      middlewares:
        - traefik_auth@docker
        - add_ui_to_path
      tls:
        certResolver: mytlschallenge
      service: pi3one

https://docs.traefik.io/v2.1/providers/file/#go-templating

6 Likes

Thanks it is working !!

  1. I have used a bit more complex example. So the environment variable WAN_HOSTNAME doesn't specify the full hostname but a part of it.
http:
  routers:
    pi3one:
      entryPoints:
        - "websecure"
      rule: "Host(`pi3one.{{env "WAN_HOSTNAME"}}`)"
      middlewares:
        - traefik_auth@docker
        - add_ui_to_path
      tls:
        certResolver: mytlschallenge
      service: pi3one
  1. In addition to the above you must also assure that the environment variable WAN_HOSTNAME is known in the traefik container. ( 2.1) For this I have defined the environment variable in the .env file (in same folder as my docker-compose.yml) and (2.2) I have added this environment variable to my traefik service definition in my docker-compose.yml as follows:
  traefik:
    build: traefik
    container_name: "traefik"
 ...
    environment:
      # WAN_HOSTNAME is used in traefik config.yml file !
      - WAN_HOSTNAME
    labels:
      - "traefik.enable=true"
...
4 Likes