Created
June 22, 2016 11:33
-
-
Save coza73/fee6152995c6de6915b0e3e8b1ca2b6e to your computer and use it in GitHub Desktop.
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
function log ([string]$logdata){ | |
$logfile = "c:\temp\Cloudflare-dns.log" | |
$date = get-date | |
Write-Output "$date - $logdata" | Out-File $logfile -width 240 -Append | |
} | |
$headers = @{ | |
'X-Auth-Key' = 'key'; | |
'X-Auth-Email' = 'email'; | |
'Content-Type' = 'application/json' | |
} | |
$ZoneRecords = @( | |
'my.dns.com, that.dns.com' | |
) | |
[string]$Zone = 'dns.com'; | |
[string]$cloudFlareApiBaseUrl = 'https://api.cloudflare.com/client/v4'; | |
[string]$public_IP=''; | |
# Get Zone ID from cloudflare | |
try | |
{ | |
$request = Invoke-WebRequest -Uri "${cloudFlareApiBaseUrl}/zones/?name=${Zone}" -Method 'GET' -Headers $headers | |
} | |
catch | |
{ | |
$MyError = $_ | |
Throw $MyError | |
} | |
$zoneId = $(ConvertFrom-Json $request.Content).result[0].id | |
#Lookup external ip | |
try | |
{ | |
$public_IP = (Invoke-RestMethod https://api.ipify.org?format=json).ip.trim() | |
} | |
catch | |
{ | |
$MyError = $_ | |
Throw $MyError | |
} | |
Foreach ($Element IN $ZoneRecords) { | |
#GET record info from cloudflare | |
#$Recordweb = Invoke-WebRequest -Uri "${cloudFlareApiBaseUrl}/zones/${ZoneId}/dns_records/?name=${Element}" -Method 'GET' -Headers $headers | |
try | |
{ | |
$Record = Invoke-RestMethod -Uri "${cloudFlareApiBaseUrl}/zones/${ZoneId}/dns_records/?name=${Element}" -Method 'GET' -Headers $headers -ContentType 'application/json' | |
} | |
catch | |
{ | |
$MyError = $_ | |
Throw $MyError | |
} | |
#When using webrequest need to convert from jason | |
#$Record_ID = $(ConvertFrom-Json $Record.Content).result[0].id | |
#$Record_IP = $(ConvertFrom-Json $Record.Content).result[0].content | |
$Record_ID = $Record.result[0].id | |
$Record_IP = $Record.result[0].content | |
if ($Record_IP -ne $public_IP) { | |
write-host "Changing from $Record_IP to new $public_IP" | |
log "Changing from $Record_IP to new $public_IP" | |
$Data = @{ | |
'id' = "${Record_ID}"; | |
'type' = 'A'; | |
'name' = "${Element}"; | |
'content' = "${public_IP}"; | |
} | |
# If it exists, UPDATE (PUT), if not, CREATE (POST) | |
[string]$method = 'PUT'; | |
if ($Record.result.Count -eq 0) { | |
$method = 'POST'; | |
$Data.Remove('id'); | |
} | |
$DataJson = ConvertTo-Json $Data | |
try | |
{ | |
$JSONResponse = Invoke-RestMethod -Uri "${cloudFlareApiBaseUrl}/zones/${ZoneId}/dns_records/${Record_ID}/" -Headers $Headers -Body $DataJson -Method "${method}" -ContentType 'application/json' -ErrorAction Stop | |
} | |
catch | |
{ | |
$MyError = $_ | |
Throw $MyError | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment