Last active
June 3, 2024 13:59
-
-
Save selivan/d526699789d7838bbcfa20dc16888161 to your computer and use it in GitHub Desktop.
Bash script to update CloudFlare DNS record. Required credentials: DNS zone id, 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
#!/bin/bash | |
if [ -z "$1" -o -z "$2" -o -z "$3" -o -z "$4" ]; then | |
echo "Usage: $0 <zone id> <auth token> <dns record name> <value> [proxied true|false (default: false)] [dns record type (default: A)] [ttl(default: 1=auto)]" | |
exit 1 | |
fi | |
type curl > /dev/null && type jq > /dev/null || { echo "curl or jq not found"; exit 1; } | |
ZONE_ID="$1" | |
TOKEN="$2" | |
NAME="$3" | |
CONTENT="$4" | |
PROXIED="${5:-false}" | |
TYPE="${6:-A}" | |
TTL="${7:-1}" | |
RECORD_ID=$(curl -s -X GET "https://api.cloudflare.com/client/v4/zones/$ZONE_ID/dns_records/" -H "Authorization: Bearer $TOKEN" | jq -r ".result[] | select(.name == \"$NAME\") | .id") | |
if [ -z "$RECORD_ID" ]; then | |
echo "DNS record does not exist, creating a new one" | |
curl -s -X POST \ | |
"https://api.cloudflare.com/client/v4/zones/$ZONE_ID/dns_records/" \ | |
-H "Authorization: Bearer $TOKEN" \ | |
-H "Content-Type: application/json" \ | |
--data '{"type":"'"$TYPE"'","name":"'"$NAME"'","content":"'"$CONTENT"'","proxied":'"$PROXIED"',"ttl":'"$TTL"'}' \ | |
| jq | |
else | |
echo "DNS record exists: id=$RECORD_ID. Updating" | |
curl -s -X PATCH \ | |
"https://api.cloudflare.com/client/v4/zones/$ZONE_ID/dns_records/$RECORD_ID" \ | |
-H "Authorization: Bearer $TOKEN" \ | |
-H "Content-Type: application/json" \ | |
--data '{"type":"'"$TYPE"'","name":"'"$NAME"'","content":"'"$CONTENT"'","proxied":'"$PROXIED"',"ttl":'"$TTL"'}' \ | |
| jq | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment