Last active
September 18, 2023 14:41
-
-
Save dlford/8642a450a75f244da9819caceef52f72 to your computer and use it in GitHub Desktop.
MikroTik RouterOS Cloudflare DDNS with API Token
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
| # Create a token with DNS edit and read permissions on all zones - https://dash.cloudflare.com/profile/api-tokens | |
| # Get zoneid from https://dash.cloudflare.com/ => select a domain => Overview => API => Zone ID | |
| # Get DNS record id: | |
| # curl --request GET \ | |
| # --url https://api.cloudflare.com/client/v4/zones/{zoneid}/dns_records \ | |
| # --header 'Content-Type: application/json' \ | |
| # --header 'Authorization: Bearer {api_token}' | |
| # --- config --- | |
| # Cloudflare zone id | |
| :local cfzoneid "" | |
| # Cloudflare DNS record id | |
| :local cfdnsrecordid "" | |
| # Cloudflare token | |
| :local cftoken "" | |
| # Cloudflare DNS hostname (e.g. myhost.example.com) | |
| :local cfdnshost "" | |
| # TTL is in seconds, should be lower than script schedule interval (e.g. 300 = 5 minutes) | |
| # ideally about half the time of your DHCP client lease time | |
| :local cfdnsttl "300" | |
| # Public interface name (e.g. ether1) | |
| :local publicinterface "" | |
| # --- config end --- | |
| :local ipddns [:resolve $cfdnshost server=1.1.1.1] | |
| :local ipfresh [ /ip address get [/ip address find interface=$publicinterface ] address ] | |
| :set ipfresh [:pick $ipfresh 0 [:find $ipfresh "/" -1]] | |
| :if ($ipddns != $ipfresh) do={ | |
| :local cfurl "https://api.cloudflare.com/client/v4/zones/$cfzoneid/dns_records/$cfdnsrecordid" | |
| :local dateTime ([ / system clock get date ] . " " . [ / system clock get time ]); | |
| :local cfDataDNS "{\"type\":\"A\",\"name\":\"$cfdnshost\",\"content\":\"$ipfresh\",\"ttl\":60,\"proxied\":false,\"comment\":\"last update: $dateTime\"}" | |
| :local cfHeader "Authorization: Bearer $cftoken,Content-Type: application/json" | |
| /tool fetch url=$cfurl http-data=$cfDataDNS http-header-field=$cfHeader http-method=put keep-result=no mode=http | |
| :log info "updated dns for $cfdnshost to $ipfresh" | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment