Application Security Group assignment using PowerShell

What are Application Security Groups? (ASGs)

ASGs are used within a NSG to apply a network security rule to a specific workload or group of VMs – defined by ASG worked as being the “network object” & expilicit IP addresses are added to this object. This provides the capability to group VMs into associated groups or workloads, simplifying the NSG rule definition process. Another great use of this is for scalability, creating the virtual machine and assigning the newly created virtual machine to its ASG will provide it with all the NSG rules in place for that specific ASG – zero distribution to your service!

Read more in my blog NSGs & ASGs Simplified

Over time you may want to add additional Virtual Machines to an ASG or multiple ASG’s to a Virtual Machine.

This can be a tedious process, so I have decided to do this via PowerShell

Create variables as below for your Virtual Machine ($VmName) & ASG’s that you want to assign to the Virtual Machine ($asgName)

$VmName = "tamops-vm"
$asgName = @("asg1","asg2","asg3")

The script below iterates over each $asgName in the array and assigns it to the Virtual Machine’s NIC

$Vm = Get-AzVM -Name $VmName
$nic = Get-AzNetworkInterface -ResourceId $Vm.NetworkProfile.NetworkInterfaces.id
 
$AsgAdd=@()

foreach ($AsgAdd in $AsgName) {
  
    $Asg = Get-AzureRmApplicationSecurityGroup -Name $AsgAdd
    $AsgAdd += $Asg

}

$nic.IpConfigurations[0].ApplicationSecurityGroups = $AsgAdd
$nic | Set-AzNetworkInterface

2 comments

  1. Hi Thomas,
    This script overwrites the first added ASG with the next one.. so at the end, we have only asg3 assigned in the Nic. asg1 and asg2 doesn’t exist.

    $nic.IpConfigurations[0].ApplicationSecurityGroups = $Asg ==> This is overwriting the existing ASG right?

    1. Thank you, I missed this comment.

      Originally I included the incorrect script – now fixed.

Leave a Reply