Skip to content

Instantly share code, notes, and snippets.

@chuanliang
Last active December 21, 2023 00:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chuanliang/dee1524548f22835074f90adcde8980d to your computer and use it in GitHub Desktop.
Save chuanliang/dee1524548f22835074f90adcde8980d to your computer and use it in GitHub Desktop.
A bash script to bulk change all IP addresses of A record in all domains in one cloudflare account
#!/bin/bash
old_ip="111.111.111.111"
new_ip="222.222.222.222"
email="my@cloudflare.com"
api_token="0123456789abcdefghijklmnopqrstuvwxyz1234"
zone_id_list=( $(curl -s -X GET "https://api.cloudflare.com/client/v4/zones/?per_page=500" -H "X-Auth-Email: $email " -H "Authorization:Bearer $api_token " -H "Content-Type: application/json"| jq -r '.result[].id') )
for zone_id in "${zone_id_list[@]}"
do
echo "zone_id is "$zone_id
record_a_list=$(curl -s -X GET "https://api.cloudflare.com/client/v4/zones/${zone_id}/dns_records?per_page=500&type=A&content=$old_ip " -H "X-Auth-Email: $email " -H "Authorization:Bearer $api_token " -H "Content-Type: application/json")
record_a_ip=$(echo $record_a_list | jq -r '{"result"}[] | .[0] | .content')
echo "cloudflare dns ip is:" $record_a_ip
if [ -n $record_a_ip -a $record_a_ip == $old_ip ]
then
echo "change the A record"
record_list=$(echo $record_a_list | jq -r '.result[].id')
for id in ${record_list}
do
echo "dns_records id is " $id
curl -s -X PATCH "https://api.cloudflare.com/client/v4/zones/${zone_id}/dns_records/${id}" -H "X-Auth-Email: $email " -H "Authorization:Bearer $api_token " -H "Content-Type: application/json" --data "{\"content\":\"$new_ip\"}"
done
fi
done
@casperklein
Copy link

record_a_ip=$(echo $record_a_list |  jq -r '{"result"}[] | .[0] | .content')

This will return only 1 record per zone. But there may be more than one record with $old_ip per zone. You can loop over the result like this:

while read NAME IP; do
	echo "Found $NAME ($IP)"

	# update records here
	# ......
done < <(jq -r '.result[] | [ .name, .content ] | @tsv' <<< "$record_a_list")

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment