-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathARM - Virtual Network (VNet) - Subnet - Associate a Network Security Group (NSG) to Subnet.ps1
80 lines (45 loc) · 1.89 KB
/
ARM - Virtual Network (VNet) - Subnet - Associate a Network Security Group (NSG) to Subnet.ps1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
<# Associate a Network Security Group (NSG) to Subnet #>
<#
Virtual Network (VNet)
Network Security Group (NSG)
#>
# Variables - Subnet
$subnetShortName = "Test"
$subnetSuffix = "Subnet"
$subnetName = "${subnetShortName}${subnetSuffix}"
<# Associate a Network Security Group (NSG) to Subnet, if it does not exist #>
$vnet = Get-AzureRmVirtualNetwork -Name $vnetName -ResourceGroupName $rgName
Get-AzureRmVirtualNetworkSubnetConfig -Name $subnetName -VirtualNetwork $vnet -ErrorVariable isSubnetExist -ErrorAction SilentlyContinue `
if (!$isSubnetExist)
{
Write-Output "Subnet exist"
# Network Security Group (NSG)
Write-Verbose "Fetching Network Security Group (NSG): {$nsgName}"
$nsg = Get-AzureRmNetworkSecurityGroup -Name $nsgName -ResourceGroupName $rgName
# Virtual Network (VNet)
Write-Verbose "Fetching Virtual Network (VNet): {$vnetName}"
$vnet = Get-AzureRmVirtualNetwork -Name $vnetName -ResourceGroupName $rgName
Write-Verbose "Associating a Network Security Group (NSG): {$nsgName} to Subnet (VNet): {$subnetName}"
Set-AzureRmVirtualNetworkSubnetConfig `
-Name $subnetName `
-VirtualNetwork $vnet `
-NetworkSecurityGroup $nsg
# updates the existing virtual network with the updated subnet.
$vnet | Set-AzureRmVirtualNetwork
}
else
{
Write-Output "Subnet does not exist"
}
Write-Verbose "Get list of all subnets"
Write-Output "Subnets"
Write-Verbose "Fetching Virtual Network: {$vnetName}"
$vnet = Get-AzureRmVirtualNetwork -Name $vnetName -ResourceGroupName $rgName
Get-AzureRmVirtualNetworkSubnetConfig -VirtualNetwork $vnet `
| Select-Object Name, AddressPrefix `
| Format-Table -AutoSize -Wrap
<#
## References
https://docs.microsoft.com/en-us/powershell/module/azurerm.network/set-azurermvirtualnetworksubnetconfig?view=azurermps-6.13.0
#>