Skip to content

Instantly share code, notes, and snippets.

@joeltg
Created April 25, 2022 01:49
Show Gist options
  • Select an option

  • Save joeltg/dbe545e2e13aeec7804faae87651f041 to your computer and use it in GitHub Desktop.

Select an option

Save joeltg/dbe545e2e13aeec7804faae87651f041 to your computer and use it in GitHub Desktop.

Revisions

  1. joeltg created this gist Apr 25, 2022.
    52 changes: 52 additions & 0 deletions cfupdater
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,52 @@
    #!/bin/sh

    zone_identifier=""
    record_name=""
    auth_token=""

    get_response=$(curl -s -X GET "https://api.cloudflare.com/client/v4/zones/${zone_identifier}/dns_records?name=${record_name}&type=A" -H "Authorization: Bearer ${auth_token}" -H "Accept: application/json")

    get_success=$(echo ${get_response} | jq .success)

    if [ "${get_success}" != "true" ]; then
    >&2 echo "API GET failed, cannot fetch DNS record."
    exit 1
    fi

    count=$(echo ${get_response} | jq .result_info.count)

    if [ "${count}" != "1" ]; then
    >&2 echo "No existing A record."
    fi

    record=$(echo ${get_response} | jq .result[0])
    record_id=$(echo ${record} | jq -r .id)
    record_content=$(echo ${record} | jq -r .content)

    # Check for current external network IP
    ip=$(curl -s https://icanhazip.com/)

    if [ "${ip}" != "" ]; then
    echo "Fetched current external network IP: ${ip}"
    else
    >&2 echo "Network error, cannot fetch external network IP."
    fi

    if [ "${ip}" = "${record_content}" ]; then
    echo "Update for A record ${record_name} cancelled; IP has not changed."
    exit 0
    else
    echo "Different IP addresses detected, synchronizing..."
    fi

    data="{\"content\":\"${ip}\"}"
    patch_response=$(curl -s -X PATCH "https://api.cloudflare.com/client/v4/zones/${zone_identifier}/dns_records/${record_id}" -H "Authorization: Bearer ${auth_token}" -H "Content-Type: application/json" --data ${data})
    patch_success=$(echo ${patch_response} | jq .success)

    if [ "${patch_success}" = "true" ]; then
    echo "Successfully updated A record for ${record_name}.\n - Old value: ${record_content}\n + New value: ${ip}"
    exit 0
    else
    >&2 echo "APT PATCH failed, cannot update DNS record."
    exit 1
    fi