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


foreach ($AsgAdd in $AsgName) {

$Asg = Get-AzureRmApplicationSecurityGroup -Name $AsgAdd

    if ($Asg.Name -eq $AsgAdd) {

        Write-Output "Adding ASG: $AsgAdd to $VmName"

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

    } else {
        Write-Output "ASG: $AsgName does not exist"
    }

}

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: