Created
April 23, 2025 02:54
-
-
Save ergosteur/c14a2afca494ef46492b521eed70d16e to your computer and use it in GitHub Desktop.
DHCP Lease Event Script for Mikrotik to automatically add DNS A records for new IPv4 DHCP Leases
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # DNS_LeaseEvent | |
| # Handles a single DHCP lease bind or release/expire event | |
| # 1) Locate the exact lease by its MAC & IP | |
| :local leaseId [/ip dhcp-server lease find where mac-address=$leaseActMAC and address=$leaseActIP] | |
| :if ($leaseId = "") do={ | |
| :log warning "DNS_LeaseEvent: lease not found for $leaseActMAC / $leaseActIP, aborting" | |
| :return | |
| } | |
| # 2) Pull lease details | |
| :local hostName [/ip dhcp-server lease get $leaseId host-name] | |
| :local ipAddress [/ip dhcp-server lease get $leaseId address] | |
| :local ttl [/ip dhcp-server lease get $leaseId expires-after] | |
| # 3) Find which network entry covers this IP | |
| :local netId [/ip dhcp-server network find where $ipAddress in address] | |
| :local domain "" | |
| :if ($netId != "") do={ | |
| :set domain [/ip dhcp-server network get $netId domain] | |
| } | |
| # 4) Assemble the FQDN | |
| :local fqdn $hostName | |
| :if ([:len $domain] > 0) do={ | |
| :set fqdn ($fqdn . "." . $domain) | |
| } | |
| # 5) React based on bind (leaseBound=1) or release/expire (leaseBound=0) | |
| :if ($leaseBound = "1") do={ | |
| # — BIND event: prune only truly stale “dhcp” records, then add this one | |
| :foreach oldRec in=[/ip dns static find where name=$fqdn and comment="dhcp"] do={ | |
| :local oldIP [/ip dns static get $oldRec address] | |
| :local otherLease [/ip dhcp-server lease find \ | |
| where address=$oldIP \ | |
| and status="bound" \ | |
| and host-name=$hostName \ | |
| and mac-address!=$leaseActMAC \ | |
| ] | |
| :if ([:len $otherLease] > 0) do={ | |
| :local otherMAC [/ip dhcp-server lease get $otherLease mac-address] | |
| :log info "DNS_LeaseEvent: preserving $fqdn → $oldIP (still bound to MAC $otherMAC)" | |
| } else={ | |
| :log info "DNS_LeaseEvent: removing stale $fqdn → $oldIP" | |
| /ip dns static remove $oldRec | |
| } | |
| } | |
| /ip dns static add \ | |
| name=$fqdn \ | |
| address=$ipAddress \ | |
| ttl=$ttl \ | |
| comment="dhcp" \ | |
| disabled=no | |
| :log info "DNS_LeaseEvent: bound → added $fqdn → $ipAddress (TTL=$ttl)" | |
| } else={ | |
| # — RELEASE/EXPIRE: set remaining static’s TTL to 15m instead of deleting | |
| :foreach rec in=[/ip dns static find where name=$fqdn and comment="dhcp"] do={ | |
| /ip dns static set $rec ttl=15m | |
| :log info "DNS_LeaseEvent: release/expire → set TTL=15m for $fqdn" | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment