Automatic SSL Certs with Certbot and Cloudflare
Here's how you can utilise the Cloudflare API to generate self signed certificates using Certbot and Let's Encrypt. This is completely free assuming you already have a domain registered with Cloudflare.
Prerequisites
First, you'll need to install a few packages to be able to use Certbot and the Cloudflare DNS plugin...
apt install certbot python3-certbot python3-certbot-dns-cloudflare
Cloudflare Token
You'll need to login to your Cloudflare account and generate an API Token that Certbot will use to create a temporary DNS record to verify you own the domain...
- Log in to your Cloudflare account.
- Go to "My Profile" → "API Tokens".
- Click on "Create Token".
- Under "Permissions", select "Zone" and ensure it has permissions to edit DNS records.
- Copy the generated API token and note it down for the next step.
Back to your terminal now.
mkdir -p ~/.secrets/certbot/
nano ~/.secrets/certbot/cloudflare.ini
Enter the following into this file...
# Cloudflare API credentials used by Certbot
dns_cloudflare_api_token =
After the = symbol, paste the API token you generated in the previous step.
Next, set the necessary permissions on the file you just created...
chmod 600 ~/.secrets/certbot/cloudflare.ini
Generating the Certificate
Now you're ready to generate the SSL certificate
certbot certonly --dns-cloudflare --dns-cloudflare-credentials ~/.secrets/certbot/cloudflare.ini --dns-cloudflare-propagation-seconds 60 -d example.com
Make sure to replace example.com with your actual domain. Note you can generate a certificate for multiple domains or even a wildcard certificate. For each domain, you just need to duplicate the -d example.com section. Here's an example of how it can look...
certbot certonly --dns-cloudflare --dns-cloudflare-credentials ~/.secrets/certbot/cloudflare.ini --dns-cloudflare-propagation-seconds 60 -d jdbnet.co.uk -d *.jdbnet.co.uk
Automatic Renewal
For this example, I'm going to show you how to setup automatic renewal with Haproxy as the system using the certificate but you can swap this out fairly easily with Nginx for example just by swapping the system you're restarting at the end...
#!/bin/bash
echo "Starting Renewal Process"
/usr/bin/certbot renew
echo "Replacing Existing Cert"
rm /etc/haproxy/cert.pem
cat /etc/letsencrypt/live/example.com/fullchain.pem >> /etc/haproxy/cert.pem
cat /etc/letsencrypt/live/example.com/privkey.pem >> /etc/haproxy/cert.pem
echo "Restarting Haproxy"
systemctl restart haproxy
Ensure you change the path to the certificate to match the actual path.
That's it, I call the above script using a cron job once a week but you can run this manually if you'd prefer.