[Script] Mikrotik – Update Cloudflare DNS Record

#--------------------------------------------
# MikroTik DDNS Script | Cloudflare API v4
# bayukurnia.com
#--------------------------------------------

# global variables
# we'll update it on every ddns success
:global currentIp

# outgoing interface
:local wanInterface "wanInterfaceName"

# get current $wanInterface IP
:local newIpCidr [/ip address get [find interface="$wanInterface"] address ]
:local newIp [:pick $newIpCidr 0 [:find $newIpCidr "/"]]

:if ($newIp != $currentIp) do={
  # cloudflare variables, adjust with yours
  :local cfToken "cloudflareToken"
  :local cfZoneId "zoneID"
  :local cfDnsId "dnsID"
  :local dnsType "A"
  :local dnsName "dnsName"
  :local dnsTTL "1"
  :local dnsProxied "false"

  # compose endpoint
  # docs: https://api.cloudflare.com/#dns-records-for-a-zone-update-dns-record
  :local apiUrl "https://api.cloudflare.com/client/v4/zones/$cfZoneId/dns_records/$cfDnsId"

  # compose headers & payload
  :local headers "Authorization: Bearer $cfToken"
  :local payload "{\"type\":\"$dnsType\",\"name\":\"$dnsName\",\"content\":\"$newIp\",\"ttl\":$dnsTTL,\"proxied\":$dnsProxied}"

  # make API request
  :do {
    :local response [/tool fetch http-method="put" url=$apiUrl http-header-field=$headers http-data=$payload as-value output=user]

    :if ($response->"status" = "finished") do={
        :log info "DDNS: changed $currentIp to $newIp"

        # update $currentIp with the new one
        :set currentIp $newIp
    }
  } on-error {
    :log error "DDNS: failed to change IP $currentIp to $newIp"
  }
}

Sau đó create Scheduler chạy script trên với interval tùy theo nhu cầu.

# global variables
# we'll update it on every ddns success
:global currentIp

Khai báo currentIp variable ( global )

# get current $wanInterface IP
:local newIpCidr [/ip address get [find interface="$wanInterface"] address ]
:local newIp [:pick $newIpCidr 0 [:find $newIpCidr "/"]]

Sau đó tạo biến chưa WAN IP của “wanInterface”

Ở đây ta sẽ kiểm tra nếu WAN IP mới và IP cũ có khác nhau chưa. Nếu có khác nhau thì mới execute update

:if ($newIp != $currentIp) do={...}

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Up ↑

%d bloggers like this: