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“.
# Set auth and subdomain information $token = "1234567893feefc5f0q5000bfo0c38d90bbeb" $email = "[email protected]" $domain = "example.com" $record = "homelab" # Get external IP $ipaddr = Invoke-RestMethod http://ipinfo.io/json | Select-Object -ExpandProperty ip $baseurl = "https://api.cloudflare.com/client/v4/zones" $zoneurl = "$baseurl/?name=$domain" # To login use... $headers = @{ 'X-Auth-Key' = $token 'X-Auth-Email ' = $email } # Get Zone info $zone = Invoke-RestMethod -Uri $zoneurl -Method Get -Headers $headers $zoneid = $zone.result.id $recordurl = "$baseurl/$zoneid/dns_records/?name=$record.$domain" # Get current DNS record $dnsrecord = Invoke-RestMethod -Uri $recordurl -Method Get -Headers $headers # If it exists, update, if not, add if ($dnsrecord.result.count -gt 0) { $recordid = $dnsrecord.result.id $dnsrecord.result | Add-Member "content" $ipaddr -Force $body = $dnsrecord.result | ConvertTo-Json $updateurl = "$baseurl/$zoneid/dns_records/$recordid/" $result = Invoke-RestMethod -Uri $updateurl -Method Put -Headers $headers -Body $body Write-Output "Record $record.$domain has been updated to the IP $($result.result.content)" } else { $newrecord = @{ "type" = "A" "name" = "$record.$domain" "content" = $ipaddr } $body = $newrecord | ConvertTo-Json $newrecordurl = "$baseurl/$zoneid/dns_records" $request = Invoke-RestMethod -Uri $newrecordurl -Method Post -Headers $headers -Body $body -ContentType "application/json" Write-Output "New record $record.$domain has been created with the ID $($request.result.id)" }
Recent Comments