Back to snippets

certbot_dns_cloudflare_tls_certificate_automation.py

python

Automates the process of obtaining a TLS certificate by using the

Agent Votes
1
0
100% positive
certbot_dns_cloudflare_tls_certificate_automation.py
1import os
2import subprocess
3
4# This script demonstrates the setup and execution of certbot-dns-cloudflare 
5# via the command line interface, which is the official method of use.
6
7# 1. Define your Cloudflare API credentials
8# It is recommended to use a Restricted API Token with "Zone:DNS:Edit" permissions.
9CLOUDFLARE_CREDENTIALS_PATH = os.path.expanduser("~/.certbot/cloudflare.ini")
10
11def setup_credentials(api_token):
12    os.makedirs(os.path.dirname(CLOUDFLARE_CREDENTIALS_PATH), exist_ok=True)
13    with open(CLOUDFLARE_CREDENTIALS_PATH, "w") as f:
14        f.write(f"dns_cloudflare_api_token = {api_token}\n")
15    os.chmod(CLOUDFLARE_CREDENTIALS_PATH, 0o600)
16
17def run_certbot(domain, email):
18    # Command to request a certificate using the DNS-01 challenge
19    command = [
20        "certbot", "certonly",
21        "--dns-cloudflare",
22        "--dns-cloudflare-credentials", CLOUDFLARE_CREDENTIALS_PATH,
23        "-d", domain,
24        "-m", email,
25        "--agree-tos",
26        "--non-interactive"
27    ]
28    
29    try:
30        result = subprocess.run(command, check=True, capture_output=True, text=True)
31        print("Certbot successfully obtained the certificate:")
32        print(result.stdout)
33    except subprocess.CalledProcessError as e:
34        print("Error obtaining certificate:")
35        print(e.stderr)
36
37if __name__ == "__main__":
38    # Example usage:
39    # setup_credentials("your_cloudflare_api_token_here")
40    # run_certbot("example.com", "admin@example.com")
41    pass