Created
February 13, 2022 10:19
-
-
Save haansn08/50565768c66c5fbf382b2bc2484e8a41 to your computer and use it in GitHub Desktop.
Cloudflare Dynamic IP
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[Unit] | |
Description=Update DNS record on Cloudflare | |
[Service] | |
ExecStart=/usr/bin/python /opt/cf.py | |
DynamicUser=yes | |
LoadCredentialEncrypted=cf-api-token:/etc/cf-api-token | |
[Install] | |
WantedBy=network.target |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[Unit] | |
Description=Run external IP update every hour | |
[Timer] | |
OnBootSec=10 | |
OnUnitActiveSec=1h | |
[Install] | |
WantedBy=timers.target |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os, sys, json | |
import requests | |
import dns.resolver | |
# See systemd's LoadCredentialEncrypted= option | |
f_cf_token = open(os.path.join(os.environ.get('CREDENTIALS_DIRECTORY'), 'cf-api-token')) | |
cf_token = f_cf_token.read() | |
f_cf_token.close() | |
cf_api_base = 'https://api.cloudflare.com/client/v4' | |
cf_zone_id = 'ab28ab290e92f20997573aa238bbd203' | |
cf_record_id = 'ee2839bcd2394bee22f349375dea32db' | |
if not cf_token: | |
sys.stderr.write('CF_TOKEN not set. Exiting.\n') | |
sys.exit(1) | |
# Discover external IP address using myip.opendns.com | |
resolver = dns.resolver.Resolver(configure=False) | |
resolver.nameservers = ['208.67.222.222', '208.67.220.220'] | |
external_ip = resolver.resolve('myip.opendns.com', 'A')[0].address | |
print(f'Discovered external IP address {external_ip}') | |
res = requests.patch( | |
f'{cf_api_base}/zones/{cf_zone_id}/dns_records/{cf_record_id}', | |
headers={'Authorization': f'Bearer {cf_token}'}, | |
data=json.dumps({'content': external_ip}) | |
) | |
if res.status_code == 200: | |
print('Cloudflare API request successful') | |
sys.exit(0) | |
else: | |
sys.stderr.write('Cloudflare API request failed\n') | |
sys.stderr.write(res.text) | |
sys.exit(1) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment