Cloudflare Update DNS Record Python Script

DNSEver를 떠나 Cloudflare에 정착. 서버의 변경 된 IP 주소를 주기적으로 DNS 레코드에 반영하기 위해 간단한 Python 스크립트를 작성해보았다.

API documentation: https://api.cloudflare.com/

import requests
import json

zone_id = '...'
email = '...'
api_key = '...'

ip_addr = requests.get('https://api.ipify.org').text

headers = {
  'X-Auth-Email': email,
  'X-Auth-Key': api_key,
  'Content-Type': 'application/json',
}

list_dns_record_url = 'https://api.cloudflare.com/client/v4/zones/{}/dns_records'
update_dns_record_url = 'https://api.cloudflare.com/client/v4/zones/{}/dns_records/{}'

response = requests.get(list_dns_record_url.format(zone_id), headers=headers)
for record in response.json()['result']:
  if record['type'] == 'A':
    data = {
      'type': 'A',
      'name': record['name'],
      'content': ip_addr,
      'ttl': 1,
      'proxied': True,
    }
    response = requests.put(update_dns_record_url.format(zone_id, record['id']), headers=headers, data=json.dumps(data))
    print(response.json())