After migrating from Traefik v1 to v2, I also had to re-adjust my certificate export script. The export script enabled me to re-use the certificates obtained from Let’s Encrypt in other (not web-related) services.
A web search revealed several tools that would already accomplish this task, but most of them were way too complex for my usecase (I don’t need the kitchen-sink, just exported certificates!). Nevertheless, you might find them useful:
- https://github.com/ldez/traefik-certs-dumper (Go)
- https://github.com/koshatul/traefik-acme (Go)
- https://gist.github.com/dmnt3d/a9696d1590df0a1410be8954df15f59c (Python)
- https://r4uch.com/export-traefik-certificates/ (Bash)
Also, lots of the tools online (usually those that don’t explicitly mention “v2”) are written for Traefik v1, but the ACME storage formats for Traefik v1 and Traefik v2 are slightly different: “let’s break stuff because we’re awesome” – Traefik developers.
In any case, based on the tools mentioned above and the new format, I adjusted my old script and extended it with the following features:
- only update certificates if necessary (you can attach an inotify handler to the files to listen for updates)
- safe (more checks and error handling)
- secure (i.e. an attacker cannot read secret contents through race conditions)
The script only requires a POSIX-compatible shell and the
jq command-line utility.
At the top of the script, you need to specify three variables: the path to Traefik’s ACME storage file, the output directory and the name of the certifcate resolver. I’m using “le” as the name, but depending on your Traefik configuration it might be called “letsencrypt” or similar.
When you call the script with
./export-traefik-v2-certificate.sh example.com, it will create a file called
example.com.crt (containing the certificate chain) and another file called
example.com.key (containing the private key) in the output directory.
The script does this by first creating new files (with random file names) and assigning strict permissions to them. Then, it exports the certificate and private key into those files. Afterwards, it compares these new files (certificate and private key) with the old files. If the contents differ, the old files will be replaced with the new ones. If not, the new ones will simply be deleted.
This design enables you to attach a listener (such as an inotify handler) to the original files and run appropriate actions (service restart, reload etc.) when necessary.
One aspect that this script doesn’t cover is handling of wildcard ACME certificates (or at least I didn’t test it).
Feel free to use and adapt this script to your liking. If you come across any errors or you have suggestions, please let me know!