Personal Azure Firewall Rule PowerShell Script for PaaS Resources

Working across the Azure Data Analytics space nowadays means working with PaaS resources predominately locked down by firewalls.This is always a good place to be in as it means restricted access from the Internet to limit access to a set of IP addresses specified and therefore means the resource is less likely to be attacked. For services such as Integration Runtimes or VPNs, these IP addresses are usually static and rarely require updating. With the need to work from home more there is now a need to include personal IP addresses in this list, and usually these are not static. Sometimes your IP will not change for weeks, while other times it seems like a new IP is assigned every day.

In most cases you’d expect to see a firewall set up for SQL Server but more often than not its being applied to other resources such as Analysis Services, Key Vault, Blob Storage, Data Lakes, etc. As I’m sure many of us now experience, keeping those firewall rules up to date can sometimes be slightly laborious, especially when working across multiple tenants and multiple environments with multiple resources. In a recent data platform build I counted that it required me to update 12 different resources. Rather than update them all together I only updated the ones I needed to access, until later in the day needed to do this update to some other resources, and so on.

This led me to write some PowerShell which can be configured to automatically add/update your own personal firewall rule for a series of PaaS resources. This could even be extended to run on your laptop startup thus removing the need to ever update these firewall rules again for your local IP. Hopefully it should be self-explanatory – the variables at the top will need configuring as per your tenant/subscription but other than that it should just work. The Tenant ID can be taken from the Azure Portal under Azure Active Directory > Properties > Directory ID while the Subscription ID can be taken from Subscriptions > Subscription ID.

You’ll need to have the Azure PowerShell cmdlets (Az modules) installed to run the following script. This can be done via Install-Module -Name Az -AllowClobber.

There’s not much to add to this blog post otherwise. Hopefully you’ll find this useful and it saves you some of that daily pain when having to update PaaS resource firewall rules!

# Configure variables for your firewall rule name, location of previous IP file and tenant/subscription Ids
$myFirewallRuleName = 'TR-Home'
$myIp = (Invoke-WebRequest ifconfig.me/ip).Content.Trim()
$mypreviousIp = Get-Content -Path C:\Temp\previousIP.txt -ErrorAction SilentlyContinue
Write-Output "PreviousIP: $($mypreviousIp) CurrentIP: $($myIp) FirewallRuleName: $($myFirewallRuleName)"
$tenantId = 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'
$subscriptionId = 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'

# Less secure due to storing password in plain text but authentication method to avoid the pop-up
# $userName = "user@adatis.co.uk"
# $userPassword =  ConvertTo-SecureString "InsertPasswordHere" -AsPlainText -Force 
# $userCredential = New-Object -TypeName System.Management.Automation.PSCredential ($userName, $userPassword)
# Connect-AzAccount -Credential $userCredential -Tenant $tenantId -SubscriptionId $subscription

Connect-AzAccount -Tenant $tenantId -SubscriptionId $subscriptionId

# List of resources to update firewall rules for
$resourceList = @(
        ,@('sqlserver', 'ResourceGroupName', 'ResourceName')
        ,@('keyvault',  'ResourceGroupName', 'ResourceName')
        ,@('storage',   'ResourceGroupName', 'ResourceName')
        ,@('aas',       'ResourceGroupName', 'ResourceName')
)

Foreach($resource in $resourceList) {
    if ($resource[0] -eq 'sqlserver') {
        try {
            Set-AzSqlServerFirewallRule -ResourceGroupName $resource[1] -ServerName $resource[2] -FirewallRuleName $myFirewallRuleName -StartIpAddress $myIp -EndIpAddress $myIp -ErrorAction Stop
        } catch {
            New-AzSqlServerFirewallRule -ResourceGroupName $resource[1] -ServerName $resource[2] -FirewallRuleName $myFirewallRuleName -StartIpAddress $myIp -EndIpAddress $myIp
        }
    }
    if ($resource[0] -eq 'keyvault') {
            Remove-AzKeyVaultNetworkRule -ResourceGroupName $resource[1] -VaultName $resource[2] -IpAddressRange $mypreviousIp -PassThru
            Add-AzKeyVaultNetworkRule -ResourceGroupName $resource[1] -VaultName $resource[2] -IpAddressRange $myIp -PassThru
    }
    if ($resource[0] -eq 'storage') {
            Remove-AzStorageAccountNetworkRule -ResourceGroupName $resource[1] -Name $resource[2] -IPAddressOrRange $mypreviousIp
            Add-AzStorageAccountNetworkRule -ResourceGroupName $resource[1] -Name $resource[2] -IPAddressOrRange $myIp
    }
    if ($resource[0] -eq 'aas') {
              # Get the existing firewall config from AAS
              $analysisServicesServer = Get-AzAnalysisServicesServer -ResourceGroupName $resource[1] -Name $resource[2]
              $currentFirewallConfig = $analysisServicesServer.FirewallConfig

              # Loop over and remove the old IP
              for($i = $currentFirewallConfig.FirewallRules.Count-1; $i -gt 0; $i--) {
                  if($currentFirewallConfig.FirewallRules[$i].FirewallRuleName -eq $myFirewallRuleName) {
                      $firewallRule = $currentFirewallConfig.FirewallRules[$i]
                      $currentFirewallConfig.FirewallRules.Remove($firewallRule) 
                  }
              }

              # Add the new IP to a rule, add this rule to the config, and update AAS
              $myRule = New-AzAnalysisServicesFirewallRule -FirewallRuleName $myFirewallRuleName -RangeStart $myIp -RangeEnd $myIp
              $currentFirewallConfig.FirewallRules.Add($myRule)
              Set-AzAnalysisServicesServer -ResourceGroupName $resource[1] -Name $resource[2] -FirewallConfig $currentFirewallConfig -PassThru
    }
 }

 # Store IP set so that on future runs it can remove the IP and keep things tidy
 $myIp | Out-File -FilePath C:\Temp\previousIP.txt


 

Leave a Reply

Your email address will not be published. Required fields are marked *