Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save nyx-rattapoom/c21a7740d72ad63e69148e6da6bdbfa0 to your computer and use it in GitHub Desktop.
Save nyx-rattapoom/c21a7740d72ad63e69148e6da6bdbfa0 to your computer and use it in GitHub Desktop.
Mikrotik update wireguard peers endpoint by resolve from url
:local vpnEndpoint "your-domain.com"
# Check WAN Link is bound
if ([/ip/dhcp-client/ get ether2-wan status] != "bound") do={
log info "Ether2 wan is not bound, skip update process"
/exit
}
# Find WAN Gateway
:local wanGateway [/ip/dhcp-client/ get ether2-wan gateway]
# Bypass DNS ip for resolved ip of vpn endpoint
:local dnsRouteID [/ip/route find comment="DNS Resolver"]
:local currentDnsRouteGateway [/ip/route get $dnsRouteID gateway]
if ($currentDnsRouteGateway != $wanGateway) do={
/ip/route set $dnsRouteID gateway=$wanGateway
# log info "update wanGateway dns bypass"
}
# Resolved Vpn
:local resolvedVpnIpAddressString [:resolve domain-name=$vpnEndpoint server=8.8.4.4]
# log info "got resolvedVpnIpAddressString=$resolvedVpnIpAddressString"
# Make vpn ip route to WAN link
:local vpnEndpointRouteID [/ip/route find comment="VPN Endpoint"]
:local currentVpnIpAddress [/ip/route get $vpnEndpointRouteID dst-address]
:local currentVpnRouteWanGateway [/ip/route get $vpnEndpointRouteID gateway]
:local currentVpnIpAddressString [:pick $currentVpnIpAddress 0 [:find $currentVpnIpAddress "/"]]
:if ($currentVpnIpAddressString != $resolvedVpnIpAddressString || $currentVpnRouteWanGateway != $wanGateway) do={
/ip/route set $vpnEndpointRouteID dst-address=$resolvedVpnIpAddressString gateway=$wanGateway
# log info "updated vpn route"
}
# Update $resolvedVpnIpAddressString to wg peer interface
:local wgPeerID [/interface/wireguard/peers find interface="wireguard-tunnel"]
:local currentWgPeerEndpointAddress [/interface/wireguard/peers get $wgPeerID endpoint-address]
:if ($currentWgPeerEndpointAddress != $resolvedVpnIpAddressString) do={
/interface/wireguard/peers set $wgPeerID endpoint-address=$resolvedVpnIpAddressString
# log info "update wireguard tunnel endpoint ip address"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment