Mikrotik RouterOS WireGuard dynamic DNS endpoint refresh

MikroTik RouterOS doesn't yet support DNS names for peer entpoints (v7.1.1). As a workaround, you can set the endpoint address using the CLI, but RouterOS will not re-resolve the DNS name. If the IP addresses behind the DNS name change at some point, for example if you use DDNS, the WireGuard tunnel will eventually stop working. As a solution, you can use a script that checks if the peer endpoint address still matches the dns name and if not, updates to the latest ip address of the DNS name.

Script:

Add under System > Scheduler a new script and choose a useful interval.

:local wgPeerComment
:local wgPeerDns

:set wgPeerComment "Peer #1 Comment"
:set wgPeerDns "dns.example.com"

:if ([interface wireguard peers get number=[find comment="$wgPeerComment"] value-name=endpoint-address] != [resolve $wgPeerDns]) do={
  interface wireguard peers set number=[find comment="$wgPeerComment"] endpoint-address=[/resolve $wgPeerDns]
}
Example: