Created
April 27, 2024 13:09
-
-
Save nyx-rattapoom/c21a7740d72ad63e69148e6da6bdbfa0 to your computer and use it in GitHub Desktop.
Mikrotik update wireguard peers endpoint by resolve from url
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
: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