NSG に大量のルールを登録する場合など、既存の NSG の設定をエクスポートしたり、コピーしたり、CSV からインポートしたいことがありますよね。Azure PowerShell でサクっとやりましょう。
CSV へエクスポート
# 既存の NSG の設定を CSV に保存
(Get-AzureRmNetworkSecurityGroup -Name "NSG 名" -ResourceGroupName "リソース グループ名").SecurityRules | select `
Name, `
Description, `
Protocol, `
@{Name="SourcePortRange"; Expression={$_.SourcePortRange -join ","}}, `
@{Name="DestinationPortRange"; Expression={$_.DestinationPortRange -join ","}}, `
@{Name="SourceAddressPrefix"; Expression={$_.SourceAddressPrefix -join ","}}, `
@{Name="DestinationAddressPrefix"; Expression={$_.DestinationAddressPrefix -join ","}}, `
Access, `
Priority, `
Direction `
| ConvertTo-Csv | select -Skip 1 | Out-File $Env:USERPROFILE\Desktop\nsg.csv -Encoding utf8
CSV からインポート
# 既存の NSG を取得
$NSG = Get-AzureRmNetworkSecurityGroup -Name "NSG 名" -ResourceGroupName "リソース グループ名"
# もしくは空の NSG を作成
# $NSG = New-AzureRmNetworkSecurityGroup -Name "NSG 名" -ResourceGroupName "リソース グループ名" -Location "リージョン名"
# CSV ファイルを取得
$CSV = Import-CSV "CSV のパス" -Encoding UTF8
# 各行のルールを追加
$CSV | foreach{
Add-AzureRmNetworkSecurityRuleConfig `
-Name $_.Name `
-NetworkSecurityGroup $NSG `
-Description $_.Description `
-Protocol $_.Protocol `
-SourcePortRange $_.SourcePortRange `
-DestinationPortRange $_.DestinationPortRange `
-SourceAddressPrefix ($_.SourceAddressPrefix -split ",") `
-DestinationAddressPrefix ($_.DestinationAddressPrefix -split ",") `
-Access $_.Access `
-Priority $_.Priority `
-Direction $_.Direction
}
# 設定を反映
Set-AzureRmNetworkSecurityGroup -NetworkSecurityGroup $NSG
ちなみに、1 つのルールに複数のアドレス空間を入れることができるようになったので、Source / Destination Address Prefix に -split でバラした配列を突っ込めるようにしてみました。(インポート用の CSV サンプルはこちら)
- General availability: Augmented rules for NSGs
https://azure.microsoft.com/ja-jp/updates/agumented-rules-ga-nsg/
ね、簡単でしょう?
2 comments for “Azure PowerShell で NSG を CSV にエクスポート・インポート・複製する方法”