Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Azure SQL DB PowerShell script for managing firewall rules
Login-AzureRmAccount
Select-AzureRmSubscription -SubscriptionName 'Your Subscription Name'
$RgName = 'Your Resource Group Name'
$SrvName = 'Your SQL Server Name'
$staticIps = "1.2.3.4", "1.2.3.5"
$ruleNames = "Rule 1", "Rule 2"
$i = 0
$currentRules = Get-AzureRmSqlServerFirewallRule -ServerName $SrvName `
-ResourceGroupName $RgName
Foreach ($ip in $staticIps)
{
$rule = $currentRules | Where ($_.StartIpAddress -eq $ip)
# If a rule with this IP does not exist
If (!$rule)
{
Write-Host No rule for $ip - creating
New-AzureRmSqlServerFirewallRule -ResourceGroupName $RgName `
-ServerName $SrvName -StartIpAddress $ip `
-EndIpAddress $ip -FirewallRuleName $ruleNames[$i]
}
$i++
}
$ThisIp = (Invoke-RestMethod https://api.ipify.org?format=json).ip
New-AzureRmSqlServerFirewallRule -ResourceGroupName $RgName `
-ServerName $SrvName `
-StartIpAddress $ThisIp -EndIpAddress $ThisIp `
-FirewallRuleName "Current IP"
$WebAppName = 'Your Web App Name'
$webAppIPs = (Get-AzureRmResource -ResourceGroupName $RgName -ResourceType Microsoft.Web/sites -ResourceName $webAppName).Properties.outboundIpAddresses
$webAppIPs = $webAppIPs.Split(',')
# Loop through all 4 IP addresses of the web app
Foreach ($ip in $webAppIPs)
{
$rule = $currentRules | Where ($_.StartIpAddress -eq $ip)
# If a rule with this IP does not exist
If (!$rule)
{
Write-Host No rule for $ip - creating
New-AzureRmSqlServerFirewallRule -ResourceGroupName $RgName `
-ServerName $SrvName -StartIpAddress $ip `
-EndIpAddress $ip -FirewallRuleName "Web App IP $i"
}
$i++
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.