Posted in:

Azure DNS Zones are a convenient way to manage your DNS records. You can configure up to 10,000 "record sets" which should be more than enough, although if you are in a situation where you automate the creation and teardown of many test deployments, it can be easy to forget to delete the DNS entries for resources that no longer exist, leaving you with a "dangling DNS" situation that can be a security risk.

A simple way to fix this is to scan your DNS Zone for all CNAME entries that point to domains that no longer exist. Here's a basic PowerShell script that does this (using Resolve-DnsName to test for existence) using the Azure CLI and then deletes the ones pointing to invalid domains.

# replace these example values with your own:
$zoneName = "mydomain.com"
$resourceGroupName = "mydnszonegrp"
$subscription = "3ba84cbe-9fc1-47e8-86bc-c42c584f30d1"

$records = az network dns record-set cname list --zone-name $zoneName `
                    --resource-group $resourceGroupName `
                    --subscription $subscription `
                    --query "[].{name:name, cname:CNAMERecord.cname}" | ConvertFrom-Json
$valid = 0
# Loop through each record and use Resolve-DnsName to check if the target domain exists
foreach ($record in $records) {
    try {        
        # Try to resolve the CNAME record and ignore the output
        Resolve-DnsName -Name $record.cname -ErrorAction Stop | Out-Null
        $valid++
    }
    catch {
        Write-Output "The target domain for $($record.name): $($record.cname) does not exist"

        # Delete the record
        az network dns record-set cname delete --zone-name $zoneName `
                    --resource-group $resourceGroupName `
                    --subscription $subscription `
                    --name $record.name --yes
    }
}
Write-Output "Records still valid: $valid"

Of course I recommend doing a dry run before actually deleting the records. This only does CNAME records. You might also want to clean up A records, but those would be a bit harder to automatically determine if they were still valid.

Want to learn more about the Azure CLI? Be sure to check out my Pluralsight course Azure CLI: Getting Started.