Automating with PowerShell: an Azure DynDNS replacement.

We’ve been using DynDNS Managed DNS for a long time. We use Managed DNS to offer dynamically updating DNS records for clients with either on-site services, or where we believe that dynamic updating of records is needed.

Oracle has bought DynDNS somewhere in 2019 and decided to slowly start killing off the DynDNS Managed DNS services. This has caused us to look for a different solution. Of course, I immediately thought of Azure, with an Azure DNS hosted zone.

The only issue was that I had some constraints;

  • I wanted to be able to keep using the clients we are using, sometimes built into devices such as the Unifi USG Gateway
  • I needed to have the ability to dynamically create records, instead of always having to do this manually.
  • I also hoped for a method that would allow us to authenticate with an API key, instead of a username/password.
  • and of course a business requirement; I needed to get this for the same price or lower than Managed DNS.

After looking into it for some moment, I immediately found the business constraint would be no issue. Azure DNS zones are extremely cheap. Combined with an Azure Function I would be able to fill in all other issues. The total price for our solution is less than 2€ a month.(Azure Calculator) That’s a big difference with the 200€ a month we paid for Managed DNS.

So, lets start the setup and get our own DynDNS service going!

Setup

First we’ll need a domain name. I’ll leave it up to you where you’ll get the domain. After buying the domain, click on this link to create a new Azure DNS Zone. After creating the zone, point your NS servers to the listed NS servers Azure gives you.

Next, we’ll create our Azure function, you can jump to that by clicking this link. You can follow the default manual for this like with our AzGlue function. There are just some small differences:

  • When asked for the language, choose PowerShell Core 6.
  • After creating the application, click on “Identity” in the left hand menu. Enable the system Identity here.
  • Now click on ‘Configuration” and add a property called APIKey. This will be the key clients will use to update their DNS configuration. Put any string you’d like here.
  • Close this blade, and go to the Azure DNS zone we’ve created, and click on “Security”. Add the Function App as a “DNS Zone Contributor”.
  • Close everything, and return to the Function App. Now click on Functions -> Add -> HTTP Trigger
  • Name your trigger. I’ve called mine “AzDynaDNS”. Select the “Anonymous” Authorization level.
  • When the trigger is deployed, click on “Integration” and then on the “HTTP Trigger”. change the route template to “{*path}” and click save.
  • now click on “Code & Test” and paste in the PowerShell code found below.

This PowerShell code simulates the way the DynDNS client works, this means we can use this in conjunction with routers, or IoT devices that support the DynDNS client.

We’ve made some modifications though; we’re dumping the username, and only using an API key instead. If you do want to use username/password based authentication, or 1 API key per client, feel free to modify the script.

The Script

So the process is pretty straight forward; Whenever the Azure Function API is called using a DynDNS client, the script compares the password if it contains the API key, it then checks if the hostname exists, and creates it if not. It also compares the current IP to the new IP and updates this, if required.

using namespace System.Net
param($Request, $TriggerMetadata)
############### Settings ##############
#Only used if Autodetection fails, e.g. multiple DNS zones, etc.
$ResourceGroup = "YOURRESOURCEGROUPNAME"
$ZoneName = "YOURZONENAME.COM"
############### /Settings ##############
if (!$request.headers.authorization) {
    write-host "No API key"
    Push-OutputBinding -Name Response -Value ([HttpResponseContext]@{
            StatusCode = [HttpStatusCode]::OK
            Body       = "401 - No API token or token is invalid."
        })
    exit
}

$Base64APIKey = $request.headers.authorization -split " " | select-object -last 1
$APIKey = [Text.Encoding]::Utf8.GetString([Convert]::FromBase64String($Base64APIKey)) -split ":" | select-object -last 1

if ($APIKey -ne $env:APIKey) {
    write-host "Invalid API key"
    Push-OutputBinding -Name Response -Value ([HttpResponseContext]@{
            StatusCode = [HttpStatusCode]::OK
            Body       = "401 - No API token or token is invalid."
        })
    exit
}

$AutoDetect = (get-azresource -ResourceType "Microsoft.Network/dnszones")
If ($AutoDetect) { 
    write-host "Using Autodetect."
    $ZoneName = $Autodetect.name
    $ResourceGroup = $AutoDetect.ResourceGroupName
}


$Domain = $request.Query.hostname.split('.') | select-object -first 1
$NewIP = $request.Query.myip
write-host "$domain has $newip. Checking record and creating if required."
$ExistingRecord = Get-AzDnsRecordSet -ResourceGroupName $ResourceGroup -ZoneName $ZoneName -Name $Domain -RecordType A -ErrorAction SilentlyContinue
if (!$ExistingRecord) {
    write-host "Creating new record for $domain"
    New-AzDnsRecordSet -name $domain -Zonename $ZoneName -ResourceGroupName $ResourceGroup -RecordType A -Ttl 60 -DnsRecords (New-AzDnsRecordConfig -Ipv4Address $NewIP)
    Push-OutputBinding -Name Response -Value (  [HttpResponseContext]@{
            StatusCode = [HttpStatusCode]::OK
            Body       = "good $newip"
        })
    exit 
}
else {
    if ($ExistingRecord.Records[-1].Ipv4Address -ne $NewIP) { 
        write-host "Updating record for $domain - new IP is $newIP"
        $ExistingRecord.Records[-1].Ipv4Address = $NewIP
        Set-AzDnsRecordSet -RecordSet $ExistingRecord
        Push-OutputBinding -Name Response -Value ([HttpResponseContext]@{
                StatusCode = [HttpStatusCode]::OK
                Body       = "good $newip"
            })
    }
    else {
        write-host "No Change - $domain IP is still $newIP"
        Push-OutputBinding -Name Response -Value ([HttpResponseContext]@{
                StatusCode = [HttpStatusCode]::OK
                Body       = "nochg $NewIP"
            })
    }
    exit
}

So, now that we’ve done all of this, we can point our DynDNS settings towards the Azure Function, and you should see records getting created and updated:

And that’s it! an easy way to create a faster, and cheaper alternative to Oracles DynDNS Managed DNS service. As always, Happy PowerShelling.

1 thought on “Automating with PowerShell: an Azure DynDNS replacement.

  1. Pingback: Automating with PowerShell: Deploying Azure Functions - CyberDrain

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.