Keeping your DNS records current is a must if you’re running services on a dynamic IP address. After I moved my DNS Zone from NoIP to Azure, I needed to have a reliable way to update the DNS record of one of my machines overseas. As there’s no “native” dyndns client solution for Azure, the task was to build my own. Which is not as bad as it sounds.
In this post, I’ll introduce a Python script that automatically updates your Azure DNS record with your machine’s latest public IP address. The best part? The configuration is secure—sensitive details like your Azure subscription and DNS settings are stored in environment variables. You can check out the full code on my GitHub repository: https://github.com/renanfernandes/my-stuff/blob/main/scripts/azure_ddns_updater.py.
Script Overview
The script leverages the Azure SDK for Python to interact with Azure DNS. It fetches your public IP using ipify and updates the DNS record if necessary. Sensitive configuration values are read from environment variables, which adds a layer of security by keeping credentials out of the code.
Setting Up Your Environment Variables
Before running the script, ensure you set the following environment variables:
- SUBSCRIPTION_ID: Your Azure subscription ID.
- RESOURCE_GROUP: The Azure resource group where your DNS zone is located.
- DNS_ZONE: The DNS zone (e.g., example.com).
- RECORD_NAME: The DNS record name (e.g., home for home.example.com).
For example, on a Linux machine you can export these variables in your shell profile or in a dedicated configuration file, such as /etc/environment.
Running the script
Once you’ve set the environment variables and installed the azure sdk, simply run the script:
renanfernandes@coronel:~$ chmod +x azure_ddns_updater.py
renanfernandes@coronel:~$ ./azure_ddns_updater.py
Current public IP: XX.XX.XX.239
Existing DNS A record IPs: ['XX.XX.XX.33']
IP addresses differ. Updating record.
DNS record updated successfully to IP: XX.XX.XX.239
renanfernandes@coronel:~$
For continuous updates, consider scheduling the script with a cron job. For example, to run it every hour, add the following line to your crontab:
0 * * * * /usr/bin/env python3 /path/to/azure_ddns_updater.py >> /tmp/azure_ddns_updater.log 2>&1
Conclusion
That’s all! Interested in the full code or contributing improvements? Check out my GitHub repository: https://github.com/renanfernandes/my-stuff.
Give it a try and let me know your thoughts!