據說 cloudflare 也是可以用 ddns 的

 實作在 mikrotik 上更新 cloudflare ddns ip ,原來只要開通 cloudflare api 就行……

單藍,要再加些楜椒和鹽…

工作環境:
 Linux Shell
 Mikrotik routerOS
 cloudflare API

# 建立更新 cloudflare DNS 記錄用的 API Token
# create API Token in cloudflare
The TOKEN value is created in the Cloudflare dashboard. Follow these steps:
1.  Click the profile icon in the top right of the dashboard, and choose 'My Profile'.
2.  Click on 'API Tokens', then 'Create Token'.
3.  Click 'Start with a template', then choose the 'Edit zone DNS' template.
4.  Under 'Zone Resources', choose your top level domain name from the pull-down list on the right.
5.  Click 'Continue to summary'.
6.  Click 'Create Token'.
7.  Copy the token shown on the following screen and set the TOKEN environment variable to its value.

# 更新 cloudflare DNS 紀錄會用到的變數
# 參考資料說要用 direnv 因為除錯失敗,直接把變數放到 gen_script 裏了……
# Variables needed for updating cloudflare DNS records
HOST=api.cloudflare.com
DOMAIN=yourDomain.name
TOKEN=yourToken
ZONE_ID=yourZoneID

# 取得 dns id and dns name 的指令,記得先 sudo apt install jq
# COMMAND get dns id and dns name

curl -s "https://$HOST/client/v4/zones/$ZONE_ID/dns_records" \
  -H "Accept: application/json" \
  -H "Authorization: Bearer $TOKEN" \
  | jq -r ".result[] \
  | select(.name == (\"*.$DOMAIN\", \"$DOMAIN\")) \
  | .id + \":\" + .name"

# 如果你有其他的 dns names 要加
# ADD what you want for update your other dns names
  | select(.name == (\"*.$DOMAIN\", \"$DOMAIN\", \"another.$DOMAIN\", \"others.$DOMAIN\")) \

# mikrotik 可用的更新 cloudflare DDNS 的腳本模板就長這樣
# TEMPLATE(result for mikrotik) using the dns id and dns name to update DNS records in the cloudflare
:global mcdPreviousIP;

:local mcdCurrentIP
:set mcdCurrentIP [/ip cloud get public-address]

:if ($mcdCurrentIP != $mcdPreviousIP) do={
  :log info "mcd: new IP $mcdCurrentIP (was $mcdPreviousIP)"
  :set mcdPreviousIP $mcdCurrentIP
  /tool fetch mode=https \\
    http-method=put \\
    url="https://$HOST/client/v4/zones/$ZONE_ID/dns_records/$id" \\
    http-header-field="content-type: application/json,Authorization: Bearer $TOKEN" \\
    http-data="{\"type\":\"A\",\"name\":\"$name\",\"content\":\"\$mcdCurrentIP\"}" \\
    output=none
}

# 確定可以更新之後記得把腳本加到定期執行工作裏
You will probably want to configure the router to run the script every few minutes:
1  Choose 'System' > 'Scheduler'.
2  Click 'Add New'.
3  Set an appropriate name (e.g. mcd).
4  Set an interval, such as 00:15:00 for every 15 minutes.
5  Select only the 'read', 'write', 'policy', and 'test' policies, as above.
6  Under 'On Event' enter the name you gave to the script when you created it (step 4 above).
7  Click 'Apply'.

 總結一下,

1、在 cloudflare 建立 Token

2、在 gen_script(詳如下方參考資料) 裏把變數寫進去,再把要新增的 FQDN 設好

3、執行 gen_script

4、到 mikrotik 上把腳本放進去,再把排程設好 

5、確認腳本運行正常

 

cloudflare DNS 記錄已更新

收工!

 

參考資料

留言

這個網誌中的熱門文章

使用 Excel 計算2個地點之間的直線距離

LINE 儲存的檔案傳到 email 不方便 很不方便 非常不方便 但是有解的筆記

Excel 巨集合併多個 Excel 檔案