Mikrotik - Public IP Script

Introduction

I have a NAT rule like the following.

 5    ;;; auto-updated jul/23/2020 12:49:15
      chain=dstnat action=dst-nat to-addresses=192.168.3.108 to-ports=80
      protocol=tcp dst-address=185.227.212.85
      in-interface=vlan832-Internet-VOIP dst-port=80 log=no log-prefix=""

And I wanted to track too how much my public IP changes. Also to trigger few scripts on other machines to update other things like public DNS records.

Mikrotik Script

name="public-ip" owner="admin" policy=read,write source=
  :local inetinterface "vlan832-Internet-VOIP"

  :local currentIP [/ip address get [find interface="$inetinterface" disabled=no] address]

  :for i from=( [:len $currentIP] - 1) to=0 do={
    :if ( [:pick $currentIP $i] = "/") do={
      :set currentIP [:pick $currentIP 0 $i]
    }
  }

  :local rulesToChange [/ip firewall nat find where to-addresses=192.168.3.108 in-interface="$inetinterface"]

  :foreach rule in=$rulesToChange do= {
    :local previousIP [/ip firewall nat get $rule dst-address]
    :if ($previousIP != $currentIP) do={
      :log info "Updating $previousIP -> $currentIP"
      :local datetime "$[/system clock get date] $[/system clock get time]"
      /ip firewall nat set dst-address=$currentIP comment="auto-updated $datetime" $rule
    }
  }

Create the schedule to run it.

> system scheduler add name=schedule2 interval=10s on-event="/system script run public-ip"