Enable certbot automatic renewal for cloudflare CDN

Page content

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.

1. Background

1.1 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:

# 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
    • 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.

2. Fix error

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

2.2 Create a cloudflare credential file

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)

dns_cloudflare_api_token = 0123456789abcdef0123456789abcdef01234567
  • Version earlier than 2.3.1

Use GLobal API Key (NOT recommended)

dns_cloudflare_email = [email protected]
dns_cloudflare_api_key = 0123456789abcdef0123456789abcdef01234

2.3 Restrict accession of the credential file

sudo chmod 0600 /etc/cloudflare/credential.ini

2.4 Acquire new certificate

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

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

2.5 Test certbot automatic renewal

sudo certbot renew --dry-run

Now, the auto renew is OK.

A. Reference