Automate let’s encrypt with systemd timer

A long long time ago I wrote a blog post about let’s encrypt automation with systemd timers that triggers letsencrypt: https://blog.bastelfreak.de/2016/05/lets-encrypt-automation-the-awesome-way/

Much changed this 2016. letsencrypt CLI is now called certbot, it can do auto renew via it’s own service and much more. I adjusted my setup slightly. I still have my own services:

# /etc/systemd/system/letsencrypt-renew@.timer
[Unit]
Description=run cert renew for %I every two month

[Timer]
# every two months?
OnCalendar=*-1/2-1 4:0:0
Persistent=true

[Install]
WantedBy=multi-user.target

# /etc/systemd/system/letsencrypt-renew@.service
[Unit]
Description=renew certificates for %I

[Service]
Type=oneshot
ExecStartPre=/bin/mkdir -p /var/lib/letsencrypt/.well-known
ExecStart=/usr/bin/certbot certonly \
  --webroot \
  --webroot-path=/var/lib/letsencrypt/ \
  --renew-by-default \
  --keep \
  --agree-tos \
  --email tim@bastelfreak.de \
  --rsa-key-size 4096 \
  --non-interactive \
  --text \
  -d %I
ExecStartPost=/bin/systemctl reload-or-restart apache2

[Install]
WantedBy=multi-user.target

This pretty much looks like my old setup. Back in the days, every vhost in my webserver configuration had an entry to redirect let’s encrypt requests to another directory, outside of the docroot. Now I use a dedicated vhost for this:

<VirtualHost *:80 [2a01:4f8:171:1152::c]:80>
	DocumentRoot /home/something.bastelfreak.de/htdocs
	ServerName something.bastelfreak.de
  ServerAdmin admin@bastelfreak.de
	<Directory /home/something.bastelfreak.de/htdocs>
		Options -Indexes +SymLinksifOwnerMatch
		Require all granted
    AllowOverride All
	</Directory>
	ErrorLog /home/something.bastelfreak.de/logs/error.apache.log
  LogLevel info
  CustomLog /home/something.bastelfreak.de/logs/access.log combined
</VirtualHost>

this allows me to easily block requests to the vhost that are not coming from let’s encrypt servers! To enable this for a new domain, I simply need to do:

systemctl enable letsencrypt-renew@newdomain.tld.timer
This entry was posted in General, Linux. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.