Skip to content

Instantly share code, notes, and snippets.

@gfrancesco
Last active October 28, 2024 17:34
Show Gist options
  • Save gfrancesco/2a57cd5dccf815f68c82905198956708 to your computer and use it in GitHub Desktop.
Save gfrancesco/2a57cd5dccf815f68c82905198956708 to your computer and use it in GitHub Desktop.
Mikrotik v6.44+ script to update Cloudflare DNS
# Get the following:
# - cfZoneId : 'Zone ID' on the right column of your domain page
# - dnsName : e.g. 'my_subdomain.example.com'
# - cfToken : on CF upper right corner 'My Profile' -> 'API Tokens' -> 'Create Token'
#
# then get the cfDnsId with this API call, replace the variables with your values:
# curl -X GET "https://api.cloudflare.com/client/v4/zones/$cfZoneId/dns_records?type=A&name=$dnsName" \
# -H "Authorization: Bearer $cfToken"
#
# Required permissions for the script AND the scheduler: read, write, policy, test
#
#--------------------------------------------
# MikroTik DDNS Script | Cloudflare API v4
# bayukurnia.com
#--------------------------------------------
# global variables
# we'll update it on every ddns success
:global currentIp
# outgoing interface
:local wanInterface "indihome"
# 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 "aJV8sCQqxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
:local cfZoneId "fb36edd6xxxxxxxxxxxxxxxxxxxxxxxx"
:local cfDnsId "afc8b34dxxxxxxxxxxxxxxxxxxxxxxxx"
:local dnsType "A"
:local dnsSubName "my_subdomain"
: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\":\"$dnsSubName\",\"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"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment