Skip to content

Instantly share code, notes, and snippets.

@ahhajlou
Created January 21, 2025 05:00
Show Gist options
  • Save ahhajlou/0bbd28b85022a835a35cb367ed2f9f74 to your computer and use it in GitHub Desktop.
Save ahhajlou/0bbd28b85022a835a35cb367ed2f9f74 to your computer and use it in GitHub Desktop.

Certainly! Here’s a step-by-step guide for setting up the DNS-01 challenge with Cloudflare using Certbot, focusing on the API key setup and configuration.

Step-by-Step for Using DNS-01 Challenge with Cloudflare

  1. Generate a Cloudflare API Token:

    • Log in to your Cloudflare account and navigate to My Profile (found under your account icon).
    • Go to the API Tokens tab.
    • Click Create Token.
    • Use the Edit Zone DNS template, which provides limited access, ideal for security.
    • Permissions: Set as follows:
      • ZoneDNSEdit
    • Zone Resources: Select IncludeSpecific Zone and choose the zone (your domain) where you want the certificate.
    • Click Continue to Summary and Create Token.
    • Copy the token generated (you’ll use it in Certbot).
  2. Install Certbot and the Cloudflare Plugin:

    • First, make sure Certbot and the Cloudflare DNS plugin are installed:
      sudo apt update
      sudo apt install certbot python3-certbot-dns-cloudflare
  3. Create a Cloudflare Credentials File:

    • Create a credentials file to securely store the API token. This file will be referenced by Certbot to automatically handle the DNS-01 challenge.
    • Save the file in a secure location, such as /etc/letsencrypt/cloudflare.ini, with the following contents:
      dns_cloudflare_api_token = YOUR_CLOUDFLARE_API_TOKEN
    • Replace YOUR_CLOUDFLARE_API_TOKEN with the token you copied from Cloudflare.
  4. Set Proper Permissions on the Credentials File:

    • Ensure only root can read this file, as it contains sensitive information:
      sudo chmod 600 /etc/letsencrypt/cloudflare.ini
  5. Request the SSL Certificate with Certbot:

    • Run Certbot, specifying the Cloudflare plugin and pointing to your credentials file:
      sudo certbot certonly --dns-cloudflare --dns-cloudflare-credentials /etc/letsencrypt/cloudflare.ini -d {your_domain}
    • Certbot will use the DNS-01 challenge method, adding a temporary TXT record to Cloudflare for verification.
  6. Automate Certificate Renewal:

    • Certbot sets up automatic renewal by default. However, you can check the status or simulate a renewal to confirm everything works:
      sudo certbot renew --dry-run

After setup, Certbot will handle certificate renewals automatically every 60 days, using the Cloudflare API to complete the DNS-01 challenge. This way, even with NAT, the certificate can be automatically updated without requiring a direct connection to your server.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment