Skip to content

Instantly share code, notes, and snippets.

@salessandri
Created May 29, 2023 01:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save salessandri/b30bdf3d02c02376f141ecc5cdb3864f to your computer and use it in GitHub Desktop.
Save salessandri/b30bdf3d02c02376f141ecc5cdb3864f to your computer and use it in GitHub Desktop.
Update A Gandi LiveDNS A Record with the external IP
#!/bin/env python3
import argparse
import logging
import requests
def get_external_ip() -> str:
GET_IP_URL = 'https://ifconfig.me/ip'
logging.info(f'Retrieving external IP from {GET_IP_URL}')
response = requests.get(GET_IP_URL)
if response.status_code != 200:
raise RuntimeError('Error when trying to query the external IP')
return response.text
def main(api_key: str, domain: str, record_name: str, record_ttl: int):
GANDI_DNS_UPDATE_URL = f'https://api.gandi.net/v5/livedns/domains/{domain}/records/{record_name}/A'
external_ip : str = get_external_ip()
logging.info(f'Updating the record {record_name}.{domain}. to {external_ip}')
request_headers = {
'Authorization': f'Apikey {api_key}'
}
request_body = {
'rrset_values': [
f'{external_ip}'
],
'rrset_ttl': record_ttl
}
response = requests.put(GANDI_DNS_UPDATE_URL, headers=request_headers, json=request_body)
if not (200 <= response.status_code < 300):
logging.error(f'Failed updating Gandi DNS record. Status Code: {response.status_code} - {response.text}')
raise RuntimeError('Failed updating Gandi DNS record')
logging.info(f'Successfully updated Gandi DNS Record to: {external_ip}')
if __name__ == '__main__':
logging.basicConfig(format="%(asctime)s [%(levelname)s] %(message)s", level=logging.DEBUG)
parser = argparse.ArgumentParser(
prog='gandi-ddns',
description="Updates a DNS A record in Gandi's LiveDNS"
)
parser.add_argument(
'--api-key',
type=str,
action='store',
required=True,
help='API Key to use to authenticate'
)
parser.add_argument(
'--domain',
type=str,
action='store',
required=True,
help='Domain containing the record to update'
)
parser.add_argument(
'--record-name',
type=str,
action='store',
required=True,
help='Record to update (it is assumed to be an A record)'
)
parser.add_argument(
'--record-ttl',
type=int,
action='store',
required=False,
default=600,
help='TTL to set on the record'
)
args = parser.parse_args()
main(args.api_key, args.domain, args.record_name, args.record_ttl)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment