Last active
April 29, 2019 17:40
-
-
Save jrotello/4cb9255d4403ed4eee3e4e1250ece3d1 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
[CmdletBinding()] | |
param( | |
[Parameter(Mandatory = $true, ValueFromPipeline = $true)] | |
[string[]]$Hostname, | |
[Parameter()] | |
[string]$CloudflareEmail = "$env:CLOUDFLARE_EMAIL", | |
[Parameter()] | |
[string]$CloudflareApiKey = "$env:CLOUDFLARE_APIKEY" | |
) | |
Begin { | |
if ([string]::IsNullOrWhiteSpace($CloudflareEmail)) { | |
Write-Error "You must provide a Cloudflare email address" -ErrorAction Stop | |
} | |
if ([string]::IsNullOrWhiteSpace($CloudflareApiKey)) { | |
Write-Error "You must provide a Cloudflare API key" -ErrorAction Stop | |
} | |
$headers = @{ | |
'X-Auth-Email' = $CloudflareEmail; | |
'X-Auth-Key' = $CloudflareApiKey; | |
'Content-Type' = 'application/json' | |
} | |
$cloudflaseBaseUri = 'https://api.cloudflare.com/client/v4' | |
} | |
Process { | |
foreach ($h in $Hostname) { | |
$parts = $h.Split('.') | |
$zoneName = "{0}.{1}" -f $parts[-2], $parts[-1] | |
# lookup dns zone | |
$response = Invoke-RestMethod -Method Get -Headers $headers -Uri "$cloudflaseBaseUri/zones?name=$([uri]::EscapeDataString($zoneName))" -ErrorAction Stop | |
if ($response.result_info.count -ne 1) { | |
Write-Error "Unable to find a DNS zone for '$zoneName'" -ErrorAction Stop | |
} | |
$zone = $response.result | |
# lookup dns record for hostname | |
$dnsRecordsUri = "$cloudflaseBaseUri/zones/$($zone.id)/dns_records" | |
$response = Invoke-RestMethod -Method Get -Headers $headers -Uri $dnsRecordsUri | |
$record = $response.result | Where-Object name -eq $h | |
if ($null -eq $record) { | |
Write-Error "Unable to find record for '$h'" -ErrorAction Stop | |
} | |
if ($record.type -ne 'A') { | |
Write-Error "'$h' must point to an 'A' record." -ErrorAction Stop | |
} | |
$ip = Invoke-RestMethod https://diagnostic.opendns.com/myip | |
if ($record.content -eq $ip) { | |
Write-Host "IP address for '$h' has not changed [$ip]" | |
} else { | |
Write-Host "IP address for '$h' has changed from '$($record.content)' to '$ip'." | |
$body = @{ | |
"type" = $record.type; | |
"name" = $record.name; | |
"content" = $ip; | |
} | ConvertTo-Json | |
$response = Invoke-RestMethod -Method PUT -Headers $headers -Uri "$dnsRecordsUri/$($record.id)" -Body $body | |
if (-not $response.success) { | |
Write-Error "There was an error updating the IP address for '$h'`n`n$($response | ConvertTo-Json)" | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment