How to reuse code in Caddyfiles?

For example, I currently have a massive list of:

one.example.com {
    proxy / https://one.example.com:9000 {
        transparent
    }
    log /var/log/caddy/access.one.example.com.log
    errors /var/log/caddy/error.one.example.com.log
}

two.example.com {
    proxy / https://two.example.com:9000 {
        transparent
    }
    log /var/log/caddy/access.two.example.com.log
    errors /var/log/caddy/error.two.example.com.log
}

three.example.com {
    proxy / https://three.example.com:9000 {
        transparent
    }
    log /var/log/caddy/access.three.example.com.log
    errors /var/log/caddy/error.three.example.com.log
}

I couldn’t see how snippets could work for me here. If they could, I think the docs could cement with clearer examples.

I want to describe my caddyfile something like this:

  • modules/template1
  • Caddyfile

modules/template1:

{$domain} {
    proxy / https://{$domain}:9000 {
        transparent
    }
    log /var/log/caddy/access.{$domain}.log
    errors /var/log/caddy/error.{$domain}.log
}

Caddyfile:

from modules import template1

template1 {
    domain one.example.com
}
template1 {
    domain two.example.com
}
template1 {
    domain three.example.com
}

I hope the above conveys the point. Is there a way to define a function with input variables?

Hi @dnk8n, the Caddyfile doesn’t have any syntax like this. Snippets are the closest thing.

You might want to look at using some templating tools to generate your Caddyfile.

Caddy 2 may also be of interest here, since its configuration is designed to be programmable.

I think this request would solve part of your issue, if the Endian problem were addressed…

@matt, any chance of this making it into caddy?

Caddy 2 adopts that endianness. (0 == right-most label)

1 Like

The direction of the label placeholders isn’t a concern in this case.

It’s possible to get the domain name from the {hostname} placeholder.

However, the proxy target can’t be dynamic, and the Caddyfile doesn’t “template” itself out in a way such as to allow this kind of repetition with minor changes. All individual proxies with distinct upstreams would have to be enumerated.