How to update WireGuard peer endpoint address using DNS on MikroTik RouterOS

Update 2022-12-30: Updated code, now uses variables

Assuming your peer comment is peer1 and the correct endpoint DNS record is peer1.mydomain.com, you can use this RouterOS script to update the endpoint based on the DNS record:

:local PEERCOMMENT 
:local DOMAIN 

:set PEERCOMMENT "peer1"
:set DOMAIN "peer1.mydomain.com"

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

Modify the variables to suit your Wireguard config: Set PEERCOMMENT to the comment of the peer that should be updated and set DOMAIN to the DNS domain name that should be used to update the peer’s IP address

After that, add it as a new script in System -> Scripts, then add a Scheduler to run the script e.g. every 30 seconds under System -> Scheduler

Script settings

Scheduler settings

Related posts which might make the process easier to understand: