PowerShell Invoke-RestMethod / CloudFlare API v4 Code Sample
If you're looking to create your own CloudFlare API v4-based PowerShell module, and would like some syntax examples, here's a simplified breakdown of my CloudFlareDynDns module on github, which I discuss in "Use PowerShell and CloudFlare API v4 to Dynamically Update CloudFlare DNS to your External IP".
1# Set auth and subdomain information
2$token = "1234567893feefc5f0q5000bfo0c38d90bbeb"
3$email = "[email protected]"
4$domain = "example.com"
5$record = "homelab"
6
7# Get external IP
8$ipaddr = Invoke-RestMethod https://ipinfo.io/json | Select-Object -ExpandProperty ip
9
10$baseurl = "https://api.cloudflare.com/client/v4/zones"
11$zoneurl = "$baseurl/?name=$domain"
12
13# To login use...
14$headers = @{
15 'X-Auth-Key' = $token
16 'X-Auth-Email ' = $email
17}
18
19# Get Zone info
20$zone = Invoke-RestMethod -Uri $zoneurl -Method Get -Headers $headers
21$zoneid = $zone.result.id
22
23$recordurl = "$baseurl/$zoneid/dns_records/?name=$record.$domain"
24
25# Get current DNS record
26$dnsrecord = Invoke-RestMethod -Uri $recordurl -Method Get -Headers $headers
27
28# If it exists, update, if not, add
29if ($dnsrecord.result.count -gt 0) {
30
31 $recordid = $dnsrecord.result.id
32 $dnsrecord.result | Add-Member "content" $ipaddr -Force
33 $body = $dnsrecord.result | ConvertTo-Json
34
35 $updateurl = "$baseurl/$zoneid/dns_records/$recordid/"
36 $result = Invoke-RestMethod -Uri $updateurl -Method Put -Headers $headers -Body $body
37
38 Write-Output "Record $record.$domain has been updated to the IP $($result.result.content)"
39
40} else {
41 $newrecord = @{
42 "type" = "A"
43 "name" = "$record.$domain"
44 "content" = $ipaddr
45 }
46
47 $body = $newrecord | ConvertTo-Json
48 $newrecordurl = "$baseurl/$zoneid/dns_records"
49 $request = Invoke-RestMethod -Uri $newrecordurl -Method Post -Headers $headers -Body $body -ContentType "application/json"
50 Write-Output "New record $record.$domain has been created with the ID $($request.result.id)"
51}