Workflow for dynamically generating and loading a configuration

Caddy version (caddy version): 2.3.0

(resources I’ve looked at linked below)

I’ve been using caddy for some time now and up until this point I’ve used a Caddyfile for configuration. However, I’m currently working on a project in which I want to set headers on groups of path matchers dynamically.

Rather than try to type each path out in a list and wrap them in a named matcher, I’ve started looking into JSON and the API for configuration so that I can generate an array of paths and then load the directives I want to apply programmatically. In the process of my research, I came across @matt’s article (linked below) on writing a JSON config from scratch. I’m now wondering whether I should craft a boilerplate JSON config to load is the right approach, then apply changes programmatically on an as-need basis via the API. Alternatively, I could generate a JSON config dynamically to load all in one go. I could also continue to maintain a Caddyfile as a base configuration that I could supplement with API calls for my dynamic paths, but given that I don’t have fine-grained control over the loaded configuration when using an adapter this doesn’t seem like the right approach.

Any advice for a recommended approach? Curious to hear what others implementations look like and how others are creating configurations dynamically.


Related resources I found

I tend to recommend using the caddy adapt command to get the JSON for your Caddyfile, then piping it through jq to make any config changes, when needing to do something that’s unsupported by the Caddyfile.

Ultimately, the approach you take entirely depends on how you plan to run Caddy, whether it’s a single instance of as a cluster, how often you need to change it, etc.

It might even be easier, if you primarily need to just add more paths to match, to write a Caddy plugin that can dynamically match based on some external factor, a database, or whatever.

2 Likes

Thanks @francislavoie. I think I found another way that works for me that is a little more straightforward than modifying the JSON. I wrote a small utility script that I can call that generates a list of the paths I need to match that I can then dump to a plain text file that Caddy can use once the site gets pushed live, would only need to have Caddy reload itself. Barring more complex configuration workflows and considering that this is my only running caddy instance at the moment, its probably best for me to stick to the syntax of the Caddyfile since it’s more human readable. Thanks again for all your help!

1 Like

This topic was automatically closed after 30 days. New replies are no longer allowed.