Score:0

Azure Powershell script to clone NSG rules across subscriptions in the same Tenant

bm flag

I need some help with a powershell script clone NSG rules from a particular NSG in 1 subscription to a NSG in another subscription. I have a script that accomplishes this if both NSG's are in the same subscription but not if they are in different subscriptions. Here is what I have. Any help would be appreciated.

#name of NSG that you want to copy 
$nsgOrigin = ""
#name new NSG  
$nsgDestination = "" 
#Resource Group Name of source NSG 
$rgName = "" 
#Resource Group Name when you want the new NSG placed 
$rgNameDest = ""
 
$nsg = Get-AZNetworkSecurityGroup -Name $nsgOrigin -ResourceGroupName $rgName 
$nsgRules = Get-AZNetworkSecurityRuleConfig -NetworkSecurityGroup $nsg 
$newNsg = Get-AZNetworkSecurityGroup -name $nsgDestination -ResourceGroupName $rgNameDest 
foreach ($nsgRule in $nsgRules) { 

$acl = @{Name = $nsgRule.Name; Protocol = $nsgRule.Protocol; SourcePortRange= $nsgRule.SourcePortRange; DestinationPortRange = $nsgRule.DestinationPortRange;Priority = $nsgRule.Priority;Direction = $nsgRule.Direction; Access = $nsgRule.Access; SourceApplicationSecurityGroup = $nsgRule.SourceApplicationSecurityGroups }


if ( $nsgRule.DestinationAddressPrefix.count -gt 0 ) { 
$acl  += @{DestinationAddressPrefix = $nsgRule.DestinationAddressPrefix }
} 
if ( $nsgRule.SourceAddressPrefix.count -gt 0 ) {
$acl  += @{SourceAddressPrefix = $nsgRule.SourceAddressPrefix }
}
if ( $nsgRule.SourceApplicationSecurityGroups.count -gt 0 ) {
$acl  += @{SourceApplicationSecurityGroup = $nsgRule.SourceApplicationSecurityGroups }
}
if ( $nsgRule.DestinationApplicationSecurityGroups.count -gt 0 ) {
$acl  += @{DestinationApplicationSecurityGroup = $nsgRule.DestinationApplicationSecurityGroups }
}


Add-AZNetworkSecurityRuleConfig -NetworkSecurityGroup $newNsg @acl
       
} 
Set-AZNetworkSecurityGroup -NetworkSecurityGroup $newNsg

Score:0
mg flag

You just need to set the subscription context before and after the origin nsg like this

Set-AzContext -SubscriptionName 'SUBNAME'

$nsg = Get-AZNetworkSecurityGroup -Name $nsgOrigin -ResourceGroupName $rgName $nsgRules = Get-AZNetworkSecurityRuleConfig -NetworkSecurityGroup $nsg

Set-AzContext -SubscriptionName 'SUBNAME'

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.