Skip to content

Instantly share code, notes, and snippets.

@SvenAelterman
Last active July 2, 2017 20:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SvenAelterman/d7ed301a7ec41e220e199a093864ecba to your computer and use it in GitHub Desktop.
Save SvenAelterman/d7ed301a7ec41e220e199a093864ecba to your computer and use it in GitHub Desktop.
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