Enable certbot automatic renewal for cloudflare CDN

A couple of days ago, I received an email from the Let’s Encrypt and was told the certificate of my domain will expire soon. This domain has been encrypted by certbot and the automatic renewal worked well at that time. About one month ago, I added it to cloudflare CDN. It may hindered the certificate renew.

So I spent some time to fix the problem.

Background

OS, HTTP server and Certbot encryption

The OS for the server is Debian 10/buster and nginx HTTP server was installed. It has been encrypted by certbot as suggested:

1
2
3
4
5
6
7
8
9
# Install certbot
sudo apt-get install certbot python-certbot-nginx

# Get a certificate and have Certbot edit the Nginx configuration automatically to serve it,
# turning on HTTPS access in a single step
sudo certbot --nginx

# Test automatic renewal
sudo certbot renew --dry-run

For the Cloudflare, this domain was configured as:

  • DNS:
    • TTL: Auto
    • Proxy status: Proxied (Orange icon)
    • Modify nameservers to Cloudflare nameservers
  • SSL/TLS
    • Full (strict): Encrypts end-to-end, but requires a trusted CA or Cloudflare Origin CA certificate on the server

When I run certbot renew --dry-run, there were error message mentioned DNS stuff.

Fix error

1
sudo apt install python3-cloudflare python3-certbot-dns-cloudflare

Create a cloudflare credential file

1
2
3
sudo mkdir /etc/cloudflare
cd /etc/cloudflare
touch credential.ini

According to the version of python3-cloudflare, the content of credential.ini is different:

  • Version 2.3.1 or later

Use cloudflare restricted API Token (recommended)

1
dns_cloudflare_api_token = 0123456789abcdef0123456789abcdef01234567
  • Version earlier than 2.3.1

Use GLobal API Key (NOT recommended)

1
2
dns_cloudflare_email = [email protected]
dns_cloudflare_api_key = 0123456789abcdef0123456789abcdef01234

Restrict accession of the credential file

1
sudo chmod 0600 /etc/cloudflare/credential.ini

Acquire new certificate

Since the encryption already configured, here generate new certificate only:

1
2
3
4
sudo certbot certonly \
--dns-cloudflare \
--dns-cloudflare-credentials /etc/cloudflare/credential.ini
-d www.mydomain.com

Test certbot automatic renewal

1
sudo certbot renew --dry-run

Now, the auto renew is OK.

Reference