Skip to content

Instantly share code, notes, and snippets.

@AlLongley
Last active February 3, 2020 01:34
Show Gist options
  • Save AlLongley/24a60be77a2b1009532d048cce7317c5 to your computer and use it in GitHub Desktop.
Save AlLongley/24a60be77a2b1009532d048cce7317c5 to your computer and use it in GitHub Desktop.
Update Google Cloud DNS records
import time
import requests
from google.cloud import dns
# Expecting auth already run in environnment
# export GOOGLE_APPLICATION_CREDENTIALS="~/secretkey.json"
# stolen from https://googleapis.dev/python/google-api-core/latest/auth.html
client = dns.Client(project='YOURPROJECTNAME')
zone = client.zone('YOURDNSZONE')
TWO_HOURS = 2 * 60 * 60 # seconds
# There is definitely a cleaner way
MYIP = requests.get("http://api6.ipify.org").content
UPDATE_URLS = ['www.YOURWEBSITE.com.', 'YOURWEBSITE.com.']
changes = zone.changes()
for record in zone.list_resource_record_sets():
if record.name in UPDATE_URLS and record.record_type=='A':
#print(record.name)
changes.delete_record_set(record)
for url in UPDATE_URLS:
record_set = zone.resource_record_set(url, 'A', TWO_HOURS, [MYIP,])
changes.add_record_set(record_set)
changes.create() # API request
print('Waiting for changes to complete',end='')
while changes.status != 'done':
print('.',end='')
time.sleep(3) # or whatever interval is appropriate
changes.reload() # API request
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment