Awesome FOSS Logo
Discover awesome open source software
Launched 🚀🧑‍🚀

LetsEncrypt Systemd Recipes

Categories

If you’re unfamiliar with Let’s Encrypt, it’s a project (I believe originally sponsored by the EFF) that creates a first of it’s kind free automated and open certificate authority. This means administrators who run websites can get free access to SSL certificates. In the past I’ve had to go to sites like StartSSL or purchase a certificate from my hosting provider (and of course, some still do), but Let’s Encrypt has been wonderful for me (I highly recommend donating to Let’s Encrypt).

If you’re unfamiliar with SystemD, it’s basically a replacement for SysV Init scripts, it’s quickly becoming (if you could even argue it’s not already) the go-to piece of software for managing linux distros, and it offers a pretty consistent and easy-to-use command line interface. Arch provides some great SystemD documentation as well.

Here are some recipes I use quite often for managing Let’s Encrypt on my own servers that I find pretty useful.

Per-Service/App Renewal Units

Here’s what the unit file looks like for a single site (I run multiple sites on one machine):

letsencrypt-<sitename>.service:

[Unit]
Description=Let's Encrypt renewal for example.com

[Service]
Type=oneshot
ExecStartPre=/usr/sbin/systemctl stop nginx.service
ExecStart=/usr/bin/certbot certonly --agree-tos --renew-by-default --email t3hmrman@gmail.com -d imap.example.com -d mail.example.com -d example.com -d www.example.com --standalone
ExecStartPost=/usr/sbin/systemctl restart nginx.service

This file (and others like it) would normally reside in /etc/systemd/system/ (location depends on distro, this is for Arch Linux).

As you can see, I use a bunch of subdomains and they’re all listed here. When I last checked, Let’s Encrypt doesn’t support wildcard subdomains, but that’s a small price to pay.

Batch renewal Units

I also have a general unit that renews all the certificates for the box, which is attached to a SystemD Timer.

letsencrypt-renewal.service

[Unit]
Description=Let's Encrypt renewal for all sites

[Service]
Type=oneshot
ExecStartPre=/usr/sbin/systemctl stop nginx.service
ExecStart=/usr/bin/certbot renew --force-renewal
ExecStartPost=/usr/sbin/systemctl restart nginx.service

BONUS: Removing subdomains from your certificate

Turns out it’s actually not so easy to remove domains (you can’t just renew without the ones you don’t want). After ~30 seconds of searching I found a great blog post that explains how to remove subdomains. The jist of it:

  1. Make a backup of your /etc/letsencrypt folder just in case
  2. Remove the folders/files in /etc/letsencrypt/archive, /etc/letsencrypt/live, /etc/letsencrypt/renewal that correspond to the subdomain(s) you no longer want
  3. Renew your certs with certbot (if you followed this guide, run the INDIVIDUAL letsencrypt-<sitename> services as necessary)