Skip to content

Instantly share code, notes, and snippets.

@dustinbutterworth
Last active October 4, 2021 19:49
Show Gist options
  • Save dustinbutterworth/3cd84b25a9b77b4fd07b169a2940c3b0 to your computer and use it in GitHub Desktop.
Save dustinbutterworth/3cd84b25a9b77b4fd07b169a2940c3b0 to your computer and use it in GitHub Desktop.
Add Cloudflare CIDR's to Azure App Service's Network Restriction using the Cloudflare API to pull latest CIDRs.
#!/usr/bin/env pwsh
# To Run: cf-azure-app-service-restriction.ps1 <ResourceGroup> <FunctionName>
# Credit to Praveen Kumar Sreeram, got the basic script from his blog post here and modified it a bit:
# https://praveenkumarsreeram.com/2021/04/26/azure-devops-bulk-ip-address-restriction-of-azure-app-service-dynamically-using-powershell/
Param(
[Parameter(Mandatory = $true)]
[string] $ResourceGroupName,
[Parameter(Mandatory = $true)]
[string] $WebAppName
)
$CloudflareCidrs = @()
$IpTypes = ('ipv4_cidrs', 'ipv6_cidrs')
$CloudflareApiCall = (Invoke-WebRequest -URI https://api.cloudflare.com/client/v4/ips) | ConvertFrom-Json
$CfRule = 0
foreach ($Type in $IpTypes) {
foreach ($Cidr in $CloudflareApiCall.result.$Type) {
$CfRule += 1
$CfRuleString = 'CFRule' + [string]$CfRule
$item = New-Object PSObject |
Add-Member -type NoteProperty -Name 'IPAddress' -Value $Cidr -PassThru |
Add-Member -type NoteProperty -Name 'Action' -Value 'Allow' -PassThru |
Add-Member -type NoteProperty -Name 'Priority' -Value '100' -PassThru |
Add-Member -type NoteProperty -Name 'Name' -Value $CfRuleString -PassThru
$CloudflareCidrs += $item
}
}
# $CloudflareCidrs
$APIVersion = ((Get-AzResourceProvider -ProviderNamespace Microsoft.Web).ResourceTypes | Where-Object ResourceTypeName -eq sites).ApiVersions[0]
$config = (Get-AzResource -ResourceType Microsoft.Web/sites/config -Name $WebAppName -ResourceGroupName $ResourceGroupName -ApiVersion $APIVersion)
foreach($item in $CloudflareCidrs){
$Rule=$config.Properties.ipSecurityRestrictions | Where-Object { $_.ipAddress -eq $item.IPAddress}
if($null -ne $Rule)
{
Write-Host -ForegroundColor Green 'No Action on the IP:' $item.ipAddress
}
else
{
$config.Properties.ipSecurityRestrictions+=$item
}
}
Set-AzResource -ResourceId $config.ResourceId -Properties $config.Properties -ApiVersion $APIVersion -Force
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment