同じテナント内のサブスクリプション間で NSG ルールを複製する Azure Powershell スクリプト

同じテナント内のサブスクリプション間で NSG ルールを複製する Azure Powershell スクリプト

1 つのサブスクリプション内の特定の NSG から別のサブスクリプション内の NSG に NSG ルールを複製する PowerShell スクリプトについて、助けが必要です。両方の NSG が同じサブスクリプション内にある場合にこれを実現するスクリプトがありますが、異なるサブスクリプション内にある場合は実現しません。これが私のスクリプトです。どんな助けでもいただければ幸いです。

#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

答え1

次のようにオリジンnsgの前後にサブスクリプションコンテキストを設定するだけです。

Set-AzContext -SubscriptionName 'サブネーム'

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

Set-AzContext -SubscriptionName 'サブネーム'

関連情報