basecamp / kamal

Deploy web apps anywhere.
https://kamal-deploy.org
MIT License
11.5k stars 457 forks source link

How to load dynamic traefik configuration file inside deploy.yml #705

Closed ghillahill closed 8 months ago

ghillahill commented 8 months ago

Hello I'am struggling with kamal and traefik for the following problem.

I was able to setup the deoploy.yml file for a main domain and x SANS domains and generate certificates with letsencrypt correctly too.

But the problem that I am facing is that I need to add a dynamic traefik configuration using an http provider that every 10s check if there are new domains and add them to the traefik configuration for my rails app.

I have setup the routes, and the traefik controller as follow:

TraefikController

class TraefikController < ApplicationController
  def config
    # Generate your Traefik configuration dynamically
    traefik_config = generate_traefik_config

    # Render the configuration as YAML
    render plain: traefik_config.to_yaml, content_type: 'text/yaml'
  end

  private

  def get_tracking_domains
    # Fetch the tracking domains from the database
    TrackingDomain.all.pluck(:name)
  end

  # EXPLAIN get_tracking_domains = ["example.com", "example.org", "example.net"]
  def generate_traefik_config(get_tracking_domains)
    routers = {}
    services = {}

    get_tracking_domains.each do |domain|
      router_name = service_name = domain

      routers[router_name] = {
        "rule" => "Host(`#{domain}`)",
        "service" => service_name,
        "tls" => { "certResolver" => "letsencrypt" }
      }

      services[service_name] = {
        "loadBalancer" => {
          "servers" => [
            { "url" => "my-server-url" }
          ]
        }
      }
    end

    {
      "http" => {
        "routers" => routers,
        "services" => services
      }
    }
  end
end

Routes snippet for traefik config # Traefik get '/traefik/config', to: 'traefik#config'

traefik.yml that read the HTTP provider

  http:
    endpoint:
      url: https://my-domain.com/traefik/config
      polling:
        interval: 10s

But I don't know how to proceed. It is possible to edit the deploy.yml to load the traefik configuration?

K4sku commented 8 months ago

You can configure traefik with "args". See "Traefik command arguments" header on https://kamal-deploy.org/docs/configuration

The quoted traefik.yml seems to be using incorrect structure - but I might be wrong. https://doc.traefik.io/traefik/providers/http/

I believe that in your case it will be:

traefik:
  args:
    providers:
      http:
        endpoint: https://my-domain.com/traefik/config
        pollInterval: 10s
ghillahill commented 8 months ago

Hello @K4sku thank you for the response. I managed to get it work.