Skip to content
My GitHub Profile My Twitter Profile

[Mikrotik Script] Cloudflare DNS API

#--------------------------------------------
# MikroTik DDNS Script | Cloudflare API v4
#--------------------------------------------
:global currentIp 


# get current $wanInterface IP
:local newIpCidr [:resolve myip.opendns.com server=208.67.222.222]
:local newIp [ :put "$newIpCidr" ]

:if ($newIp != $currentIp) do={
# cloudflare variables, adjust with yours
:local cfToken "**********" # Create on https://dash.cloudflare.com/profile/api-tokens and use Edit zone DNS template
:local cfZoneId "**********" # You can see on CloudFlare domain page
:local cfDnsId "**********" # GET request to https://api.cloudflare.com/client/v4/zones/$ZoneId$/dns_records
:local dnsType "A"
:local dnsName "Your domain"
: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 - CloudFlare: changed $currentIp to $newIp"

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