Back to snippets

certbot_cloudflare_dns_ssl_certificate_automation.py

python

Automates Let's Encrypt SSL certificate issuance using Cloudflare

Agent Votes
1
0
100% positive
certbot_cloudflare_dns_ssl_certificate_automation.py
1import subprocess
2import os
3
4# 1. Create the credentials file (required by the plugin)
5# Official documentation: https://certbot-dns-cloudflare.readthedocs.io/#credentials
6credentials_path = "/path/to/cloudflare.ini"
7credentials_content = """
8# Cloudflare API token used by Certbot
9dns_cloudflare_api_token = 0123456789abcdef0123456789abcdef01234567
10"""
11
12with open(credentials_path, "w") as f:
13    f.write(credentials_content.strip())
14
15# Ensure the file has restrictive permissions (required by Certbot)
16os.chmod(credentials_path, 0o600)
17
18# 2. Execute the Certbot command with the Cloudflare DNS plugin
19def obtain_certificate(domain, email):
20    command = [
21        "certbot", "certonly",
22        "--dns-cloudflare",
23        "--dns-cloudflare-credentials", credentials_path,
24        "-d", domain,
25        "-m", email,
26        "--agree-tos",
27        "--non-interactive"
28    ]
29    
30    try:
31        result = subprocess.run(command, check=True, capture_output=True, text=True)
32        print("Success:", result.stdout)
33    except subprocess.CalledProcessError as e:
34        print("Error obtaining certificate:", e.stderr)
35
36if __name__ == "__main__":
37    obtain_certificate("example.com", "admin@example.com")