How to create a network security group that allows only a certain ip in inbound rules

Ilia Naleva 0 Reputation points
2023-01-23T18:27:38.04+00:00

I would like to migrate about 80 instances from AWS to Azure.

Each instance allows only a certain set of connections, for example:

Instance A: allow http + https connection from ip 1.2.3.4 on inbound and all ips in outbound.
Instance B: allow http + https connection from ip 5.6.7.8 on inbound and all ips in outbound.

some instances have 1-20 allowed IPs.

I saw that there is no import options for security groups, so i wonder if there is any other way to do that, maybe some kind of script?

Azure Virtual Machines
Azure Virtual Machines
An Azure service that is used to provision Windows and Linux virtual machines.
9,036 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Andreas Baumgarten 123.6K Reputation points MVP Volunteer Moderator
    2023-01-23T21:01:02.8533333+00:00

    Hi @Ilia Naleva ,

    this should be possible using a CSV file and a PowerShell script (Az module required).

    Create a CSV file, for instance nsg_Rules.csv . Content should look like this:

    Name,Protocol,Direction,Priority,SourceAddressPrefix,SourcePortRange,DestinationAddressPrefix,DestinationPortRange,Access
    Rule1,TCP,Inbound,100,*,*,*,80,Allow
    Rule2,TCP,Inbound,110,10.0.0.0/24,*,*,4711,Allow
    Rule3,TCP,Outbound,110,10.0.0.0/24,*,*,4711,Allow
    

    The following PowerShell script will read the CSV file and creates a NSG rule per line:

    $NSG = "testNSG1"
    $rules = Import-Csv -Path .\Junk\nsg_Rules.csv
    $nsgObj = Get-AzNetworkSecurityGroup -Name $NSG
    foreach ($rule in $rules) {
      $Params = @{
        'Name'                     = $rule.Name
        'Protocol'                 = $rule.Protocol
        'Direction'                = $rule.Direction
        'Priority'                 = $rule.Priority
        'SourceAddressPrefix'      = $rule.SourceAddressPrefix
        'SourcePortRange'          = $rule.SourcePortRange
        'DestinationAddressPrefix' = $rule.DestinationAddressPrefix
        'DestinationPortRange'     = $rule.DestinationPortRange
        'Access'                   = $rule.Access
      }
      $nsgObj | Add-AzNetworkSecurityRuleConfig @Params | Set-AzNetworkSecurityGroup
    }
    

    (If the reply was helpful please don't forget to upvote and/or accept as answer, thank you)

    Regards

    Andreas Baumgarten

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.