ネットワークセキュリティグループ(NSG)をPowerShellからまとめて設定する
Azure 仮想マシンのアクセス制限にネットワークセキュリティグループを設定することが多いと思います。 ポータルからも設定出来るのですが、ルールの更新中(プログレスバーが動いている間)に次のルールを登録することが出来ないため、結構面倒で時間もかかってしまいます。
とういことで、数が多いときはPowerShellでまとめて登録してしまいましょう。
# ログイン及びサブスクリプションの選択 Login-AzureRmAccount $subscriptionId = (Get-AzureRmSubscription | Out-GridView -PassThru).SubscriptionId Select-AzureRmSubscription -SubscriptionId $subscriptionId # ネットワークセキュリティグループを新規に作成する New-AzureRmNetworkSecurityGroup -Location [ロケーション] -Name [NSG名] -ResourceGroupName [リソースグループ名] # 変更するネットワークセキュリティグループを取得 $nsg = Get-AzureRmNetworkSecurityGroup -Name [NSG名] -ResourceGroupName [リソースグループ名] # ルールを指定 # VNET内の通信を許可する $rule = Add-AzureRmNetworkSecurityRuleConfig -NetworkSecurityGroup $nsg -Name 'localnet' -Access Allow -Protocol * -Direction Inbound -Priority 110 -SourceAddressPrefix VirtualNetwork -SourcePortRange * -DestinationAddressPrefix * -DestinationPortRange * # 外部からの通信は、指定したIPアドレス(レンジ)のみ接続する。 $rule = Add-AzureRmNetworkSecurityRuleConfig -NetworkSecurityGroup $nsg -Name 'ssh' -Access Allow -Protocol * -Direction Inbound -Priority 210 -SourceAddressPrefix [IPアドレス(CIDR)] -SourcePortRange * -DestinationAddressPrefix * -DestinationPortRange 22 $rule = Add-AzureRmNetworkSecurityRuleConfig -NetworkSecurityGroup $nsg -Name 'http' -Access Allow -Protocol * -Direction Inbound -Priority 220 -SourceAddressPrefix [IPアドレス(CIDR)] -SourcePortRange * -DestinationAddressPrefix * -DestinationPortRange 80 $rule = Add-AzureRmNetworkSecurityRuleConfig -NetworkSecurityGroup $nsg -Name 'https' -Access Allow -Protocol * -Direction Inbound -Priority 230 -SourceAddressPrefix [IPアドレス(CIDR)] -SourcePortRange * -DestinationAddressPrefix * -DestinationPortRange 443 # ルールをNSGに反映する Set-AzureRmNetworkSecurityGroup -NetworkSecurityGroup $rule
「-SourceAddressPrefix」は、タグで指定することが出来るようです。 * Internet * VirtualNetwork * AzureLoadBalancer のいずれかがビルドインで指定できるようです。
登録できるルールの数は、セキュリティグループ当たり200個までとのことなので、IPアドレスを範囲で指定するなどして、ルールが増えすぎないように注意ですね。