Last active
June 15, 2022 09:58
-
-
Save Lazrius/5d0833f5b3a2d8055a1ee0d4bcd50368 to your computer and use it in GitHub Desktop.
Simple Cloudflare Dynamic IP Updating Service (using Deno)
This file contains 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
/* | |
This is a fairly simple script that simply grabs your public IP then sends it on to a cloudflare zone to update a particular DNS reccord. | |
I wrote this for keeping my Raspberry Pi always connected as my public IP changed frequently. | |
*/ | |
// Run with `deno run --allow-net cloudflare.ts` | |
// Empty declaration to make it a module | |
export { }; | |
const api = "https://api.cloudflare.com/client/v4"; | |
const zoneId = ""; // You get the zone id from the right panel of your site's dashboard | |
const token = ""; // Generate an API key within your profile, give it DNS Zone Edit rights | |
// If this is an empty array, then it will replace all proxied A records instead. | |
const domains: Array<string> = [ | |
"add.your.domains.here", | |
"qw.example.com" | |
] | |
let response = await fetch('https://api.ipify.org'); | |
const ip = await response.text(); | |
// Construct our header | |
const header = { | |
'Authorization': 'Bearer ' + token, | |
'Content-Type': 'application/json' | |
} | |
response = await fetch(`${api}/zones/${zoneId}/dns_records`, { method: "get", headers: header }); | |
const data = await response.json() as CloudFlareReccordResponse; | |
interface CloudFlareRecord { | |
id: string, | |
zone_id: string, | |
zone_name: string, | |
name: string, | |
type: string, | |
content: string, | |
proxiable: boolean, | |
proxied: boolean, | |
ttl: number, | |
locked: boolean, | |
created_on: Date, | |
modified_on: Date | |
} | |
interface CloudFlareReccordResponse { | |
result: Array<CloudFlareRecord> | |
success: boolean, | |
errors: Array<string>, | |
messages: Array<string> | |
} | |
const handleDomain = async (record: CloudFlareRecord) => { | |
const patch = async (id: string) => { | |
await fetch(`${api}/zones/${zoneId}/dns_records/${record.id}`, { | |
method: 'patch', | |
headers: header, body: `{ "content": "${ip}" }` | |
}); | |
console.log("Updated Record - " + record.name); | |
} | |
if (!domains.length && record.proxied && record.type == "A") { | |
await patch(record.id); | |
} else if (domains.includes(record.name)) { | |
await patch(record.id); | |
} | |
}; | |
if (!data.success) { | |
data.messages.forEach(console.warn); | |
} else { | |
for (const zone of data.result) { | |
await handleDomain(zone); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment