Skip to content

Instantly share code, notes, and snippets.

@zehuanli
Last active May 9, 2024 20:32
Show Gist options
  • Save zehuanli/41c45353a579d1aa275e512257939be3 to your computer and use it in GitHub Desktop.
Save zehuanli/41c45353a579d1aa275e512257939be3 to your computer and use it in GitHub Desktop.
Azure allow IPs from a list file
# Resource group and NSG name
$resourceGroupName = 'RESOURCE_GROUP_NAME'
$nsgName = 'NETWORK_SECURITY_GROUP_NAME'
# Path to the file containing IP ranges
$ipRangesFile = 'IP_RANGE_FILE_PATH'
# Read IP ranges from file
$ipRanges = Get-Content $ipRangesFile
# Get the NSG object
$nsg = Get-AzNetworkSecurityGroup -ResourceGroupName $resourceGroupName -Name $nsgName
# Create NSG rules for each IP range
$priority = 100
foreach ($ipRange in $ipRanges) {
$ruleName = "AllowFrom-$priority"
$ruleParams = @{
'Name' = $ruleName
'Protocol' = 'Tcp'
'SourceAddressPrefix' = $ipRange
'SourcePortRange' = '*' # Allow traffic from any source port
'DestinationAddressPrefix' = '*' # Allow traffic to any destination
'DestinationPortRange' = @('80', '443') # Allow traffic to destination ports 80 and 443
'Access' = 'Allow'
'Direction' = 'Inbound'
'Priority' = $priority
'Description' = "Allow inbound TCP traffic from IP $ipRange on ports 80 and 443"
}
$rule = New-AzNetworkSecurityRuleConfig @ruleParams
$nsg.SecurityRules.Add($rule)
Set-AzNetworkSecurityGroup -NetworkSecurityGroup $nsg
Write-Output "Created NSG rule: $ruleName"
$priority++
}
Write-Output 'NSG rules creation completed.'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment