This script is for Mikrotik RouterOS v7 routers. It updates a Cloudflare DNS record whenever there’s a change in the router’s public IP address.
It’s important to note that Mikrotik RouterOS already includes an IP Cloud DDNS feature. This feature works great and can be used to recursively update other records (using CNAME) that point to the dynamic DNS record generated by Mikrotik.
However, I needed a script that could log changes to the WAN-IP and, optionally, also perform the Cloudflare DNS update.
CfApiAuthEmail
- The email associated with your Cloudflare account (required for API authentication).CfApiDnsRcName
- The dns record (Type A) at CF you want to update (e.g. "mywanip.domain.com").CfApiDnsZoneID
- The Cloudflare DNS Zone ID. You can locate this in your Cloudflare dashboard.CfApiDnsRcrdID
- The Cloudflare DNS Record ID. More details on this are provided below.CfApiAuthToken
- The Cloudflare AuthKey/Token. You can create it in your Cloudflare dashboard.
Notes:
- RouterOS script policies: read, write, test, and policy.
- Remember to add a Scheduler that start the script every 5 minutes, or any interval that suits your needs.
To create the Cloudflare AuthKey/Token (CfApiAuthToken
) in the Cloudflare dashboard, follow these steps:
- Click on the profile icon located at the top right corner of the dashboard, then select ‘My Profile’.
- Navigate to ‘API Tokens’, and click on ‘Create Token’.
- Select ‘Start with a template’, then choose the ‘Edit zone DNS’ template.
- Under ‘Zone Resources’, select your top-level domain name.
- Proceed by clicking ‘Continue to summary’.
- Finally, click ‘Create Token’ to generate your API token.
You can locate this in your Cloudflare dashboard, select the domain "Overview" on the left and scroll down.
You'll find it on the right in the "API Zone ID" section.
- This process needs to be done only once to obtain the specific Record ID.
- This is for Type A DNS Record, if you need another type adjust the URL in the curl command (and in the RouterOS script as well).
- The
| jq
at the end of the curl command is used to present the results in a more readable format. If you don’t have jq installed, you can simply remove the final pipe and parse the results manually. - Before launching the curl commands below, populate the 4 initial variables and paste them into the shell too (or set values directly in the curl command).
- In the field "id" (of "result"), you'll find the DNS Record ID you are looking for.
CfApiDnsRcName="mywanip.domain.com"
CfApiAuthEmail="[email protected]"
CfApiAuthToken="_Cloudflare_Auth_Key_Token_"
CfApiDnsZoneID="_Cloudflare_Dns_Zone_ID_"
curl -s -X GET "https://api.cloudflare.com/client/v4/zones/$CfApiDnsZoneID/dns_records?type=A&name=$CfApiDnsRcName" \
-H "X-Auth-Email: $CfApiAuthEmail" \
-H "Authorization: Bearer $CfApiAuthToken" \
-H "Content-Type: application/json" | jq