Created
September 16, 2021 19:17
-
-
Save yutsuku/a312268d8d20bfb13c0897e50e1e3713 to your computer and use it in GitHub Desktop.
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
#!/bin/bash | |
# | |
# Updates type "A" record for a subdomain with current external IP Address at Cloudflare. | |
# Obtain API Token at https://dash.cloudflare.com/profile/api-tokens with permissions "Zone.DNS". | |
# | |
# Author: [email protected] | |
# Revision: 2021-09-16 | |
# | |
# Requires: curl, jq, dig | |
# | |
# config start | |
DOMAIN='example.com' | |
SUBDOMAIN='home.example.com' | |
TOKEN='<READ DESCRIPTION>' | |
# config end | |
# obtain current external ip address | |
IP=$(dig +short myip.opendns.com @resolver1.opendns.com) | |
# get id for main domain (zone) | |
ZONEID=$(curl -s -X GET "https://api.cloudflare.com/client/v4/zones?name=$DOMAIN" \ | |
-H "Authorization: Bearer $TOKEN" \ | |
-H "Content-Type:application/json" | jq -r '.result[].id') | |
# get id for subdomain (inside zone) | |
DNS_RECORD=$(curl -s -X GET "https://api.cloudflare.com/client/v4/zones/$ZONEID/dns_records?type=A&name=$SUBDOMAIN" \ | |
-H "Authorization: Bearer $TOKEN" \ | |
-H "Content-Type: application/json") | |
DNS_RECORD_ID=$(echo $DNS_RECORD | jq -r '.result[].id') | |
DNS_RECORD_CONTENT=$(echo $DNS_RECORD | jq -r '.result[].content') | |
if [[ $DNS_RECORD_CONTENT = $IP ]]; then | |
echo OK | |
else | |
echo UPDATING "A" record for $SUBDOMAIN - $DNS_RECORD_CONTENT to $IP | |
# update DNS info | |
STATUS=$(curl -s -X PATCH "https://api.cloudflare.com/client/v4/zones/$ZONEID/dns_records/$DNS_RECORD_ID" \ | |
-H "Authorization: Bearer $TOKEN" \ | |
-H "Content-Type: application/json" \ | |
--data "{\"type\":\"A\",\"name\":\"$SUBDOMAIN\",\"content\":\"$IP\"}") | |
STATUS_SUCCESS=$(echo $STATUS | jq -r '.success') | |
if [[ $STATUS_SUCCESS = "true" ]]; then | |
echo OK | |
else | |
echo FAIL | |
fi | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment