Associate NSG to Subnets in foreach loop Powershell - azure

I've created a small script which creates subnets, I can then pass them through a loop and create network security groups (nsg) with the name of the subnet + -nsg, but when I try to associate the nsg to the subnet it fails saying the nsg doesn't exist. So i created two small scripts and split the create nsg from the associate nsg, but again same error.
Error:
Set-AzureNetworkSecurityGroupToSubnet : ResourceNotFound : The Network Security Group nsg-test-nsg does not exist.
But this does definitely exist.
The code I have is:
$resource = "rg-subnets"
$vnetName = "vnet-bmg"
$loc = "West Europe"
$vnet = Get-AzureRmVirtualNetwork -ResourceGroupName $resource -Name $vnetName
$sub = (Get-AzureRmVirtualNetworkSubnetConfig -VirtualNetwork $vnet).name
foreach ($subnet in $sub){
New-AzureRmNetworkSecurityGroup -Name $subnet-nsg -ResourceGroupName $resource -Location $loc -Force
Set-AzureNetworkSecurityGroupToSubnet -Name $subnet-nsg -VirtualNetworkName $vnetName -SubnetName $subnet
}
Help! :)

This worked for me,
$resource = "rg-subnets"
$vnetName = "vnet-bmg"
$loc = "West Europe"
$vnet = Get-AzureRmVirtualNetwork -ResourceGroupName $resource -Name $vnetName
$sub = (Get-AzureRmVirtualNetworkSubnetConfig -VirtualNetwork $vnet).name
foreach ($subnet in $sub){
New-AzureRmNetworkSecurityGroup -Name $subnet-nsg -ResourceGroupName $resource -Location $loc -Force
$subnetName = Get-AzureRmVirtualNetworkSubnetConfig -VirtualNetwork $vnet -Name $subnet
$nsg = Get-AzureRmNetworkSecurityGroup -ResourceGroupName $resource -Name "$subnet-nsg"
$subnetName.NetworkSecurityGroup = $nsg
Set-AzureRmVirtualNetwork -VirtualNetwork $vnet -Verbose
}

Related

Azure VMs fails as public ip is allocated to other resource

I am using a powershell script to create multiple Vms based on an image. The first Vm is ok but when attempting the second Vm I get an error saying that :
| Resource /subscriptions/....../networkInterfaces/xxxxx/ipConfigurations/xxxxx is referencing public IP address
| /subscriptions/xxxxxxxxx/providers/Microsoft.Network/publicIPAddresses/Microsoft.Azure.Commands.Network.Models.PSPublicIpAddress that is already allocated to
| resource /subscriptions/......./networkInterfaces/xxxxx/ipConfigurations/xxxxx.
Here is the script I am using:
param(
[string] $WeekNo="NoWeek",
[int] $VmCount=0
)
#$cred = Get-Credential -Message "Enter a username and password for the virtual machine."
## VM Account
# Credentials for Local Admin account you created in the sysprepped (generalized) vhd image
$VMLocalAdminUser = "xxxxx"
$VMLocalAdminSecurePassword = ConvertTo-SecureString "xxxxxxx" -AsPlainText -Force
$image = "/subscriptions/xxxxxxx/resourceGroups/xxxxxx/providers/Microsoft.Compute/images/xxxxxxxxx"
## Azure Account
$LocationName = "SwedenCentral"
$ResourceGroupName = "xxxx_" + $WeekNo
if( -Not( Get-AzureRmResourceGroup -Name $ResourceGroupName -Location $LocationName -ErrorAction Ignore)) {
New-AzureRmResourceGroup -Name $ResourceGroupName -Location $LocationName
Write-Host "ResourceGroup" $ResourceGroupName "created"
$VMSize = "Standard_B2ms"
## Networking
$NetworkName = "xxxxxx_" + $WeekNo + "_net" # "MyNet"
$SubnetName = "MySubnet"
$SubnetAddressPrefix = "10.0.0.0/24"
$VnetAddressPrefix = "10.0.0.0/16"
$SingleSubnet = New-AzVirtualNetworkSubnetConfig -Name $SubnetName -AddressPrefix $SubnetAddressPrefix
$Vnet = New-AzVirtualNetwork -Name $NetworkName -ResourceGroupName $ResourceGroupName -Location $LocationName -AddressPrefix $VnetAddressPrefix -Subnet $SingleSubnet
}
$Credential = New-Object System.Management.Automation.PSCredential ($VMLocalAdminUser, $VMLocalAdminSecurePassword);
$VMName = "xxxx" + $WeekNo
##New-AzVM -ResourceGroupName $ResourceGroupName -Location $LocationName -VM $VirtualMachine -Verbose -Image $image
for($i=1; $i -le $VmCount; $i++){
$VMBaseName = "iCPSEDU" + $WeekNo + $i
$StorageAccount = "xxxxx" + $WeekNo + $i
$PublicIPAddressName = $VMBaseName + "PIP$(Get-Random)"
$NICName = $VMBaseName + "NIC"
$DNSNameLabel = "xxxx" + $WeekNo + $i + "dns" # mydnsname.westus.cloudapp.azure.com
$PIP = New-AzPublicIpAddress -Name $PublicIPAddressName -DomainNameLabel $DNSNameLabel -ResourceGroupName $ResourceGroupName -Location $LocationName -AllocationMethod Dynamic
$NIC = New-AzNetworkInterface -Name $NICName -ResourceGroupName $ResourceGroupName -Location $LocationName -SubnetId $Vnet.Subnets[0].Id -PublicIpAddressId $PIP.Id
Write-Host "Creating VM " $VMBaseName
New-AzVm `
-ResourceGroupName $ResourceGroupName `
-Name $VMBaseName `
-ImageName $image `
-Location $LocationName `
-VirtualNetworkName $Vnet `
-SubnetName $SubnetName `
-SecurityGroupName "myImageNSG" `
-PublicIpAddressName $PIP -Credential $Credential -Size $VMSize -PublicIpSku Standard
Write-Host "VM " $VMBaseName " Created"
Stop-AzVM -ResourceGroupName $ResourceGroupName $VMBaseName -Force -NoWait
Write-Host "VM " $VMBaseName " Stopped"
}
Write-Host "Done."`
To me it seems that the variable used for the PIP is not "flushed" properly between the executions but I have no idea on how to do this?
Or is there something else causing the error?
I have tried adding some delays but without effect.
Create a public IP address and specify a DNS name
Create a NSG
Create a NIC and associate with created pub IP address and NSG
Create a virtual machine configuration and assign the NIC
Create the VM with the config
https://github.com/Azure/azure-docs-powershell-samples/blob/master/virtual-machine/create-vm-detailed/create-windows-vm-detailed.ps1
rough summary of important steps:
$pip = New-AzPublicIpAddress -ResourceGroupName $resourceGroup -Location $location `
-Name "mypublicdns$(Get-Random)" -AllocationMethod Static -IdleTimeoutInMinutes 4
$nsg = New-AzNetworkSecurityGroup -ResourceGroupName $resourceGroup -Location $location `
-Name myNetworkSecurityGroup -SecurityRules $nsgRuleRDP
$nic = New-AzNetworkInterface -Name myNic -ResourceGroupName $resourceGroup -Location $location `
-SubnetId $vnet.Subnets[0].Id -PublicIpAddressId $pip.Id -NetworkSecurityGroupId $nsg.Id
$vmConfig = New-AzVMConfig -VMName $vmName -VMSize Standard_D1 | `
Set-AzVMOperatingSystem -Windows -ComputerName $vmName -Credential $cred | `
Set-AzVMSourceImage -PublisherName MicrosoftWindowsServer -Offer WindowsServer -Skus 2016-Datacenter -Version latest | `
Add-AzVMNetworkInterface -Id $nic.Id
New-AzVM -ResourceGroupName $resourceGroup -Location $location -VM $vmConfig
MS is providing well tested powershell code for various tasks:
I prefer the github samples https://github.com/Azure/azure-docs-powershell-samples over the steps in learn and doc.microsoft.com
also have a deeper look at the Azure CLI examples and template based deployments. It seems to me that MS is abandoning PS a bit.

How to create multiple Subnets in pre-existing Vnet Powershell

I have the following code which works good for adding a few subnets but I would like for this script to leverage a CSV file to import from and add the subnets into a pre-existing Vnet?
$appssubnet = New-AzVirtualNetworkSubnetConfig -Name servers -AddressPrefix "172.16.1.0/24" -NetworkSecurityGroupId "/subscriptions/xxxxxxxxxx-xxxx-xxxx-xxxxx-xxxxxxxxxxxx/resourceGroups/powershell-grp/providers/Microsoft.Network/networkSecurityGroups/app-nsg1"`
-RouteTableId "/subscriptions/xxxxxxxxxx-xxxx-xxxx-xxxxx-xxxxxxxxxxxx/resourceGroups/powershell-grp/providers/Microsoft.Network/routeTables/powershell-rt"
$serversubnet = New-AzVirtualNetworkSubnetConfig -Name apps -AddressPrefix "172.16.2.0/24" -RouteTableId "/subscriptions/xxxxxxxxxx-xxxx-xxxx-xxxxx-xxxxxxxxxxxx/resourceGroups/powershell-grp/providers/Microsoft.Network/routeTables/powershell-rt"
$dmz = New-AzVirtualNetworkSubnetConfig -Name dmz -AddressPrefix "172.16.3.0/24"
$updatedvnet = New-AzVirtualNetwork -Name "testsubnet" -ResourceGroupName "powershell-grp" -Location "North Europe" -AddressPrefix "172.16.0.0/16" -Subnet $serversubnet, $dmz, $appssubnet -Force:$true
$updatedvnet | Set-AzVirtualNetwork
You can use the below powershell script.
$subnets1 = Import-Csv "C:\Users\v-XXXsXX18\Documents\TestCount.csv"
#$subnets1.subnetName
foreach ($subnet in $subnets1){
$dmz = New-AzVirtualNetworkSubnetConfig -Name $subnet.SubnetName -AddressPrefix $subnet.AddressPrefix
$vnet=Get-AzVirtualNetwork -Name "MyVirtualNetworkTes" -ResourceGroupName "v-raXXXXndtree"
$updatedvnet=Add-AzVirtualNetworkSubnetConfig -Name $dmz.Name -VirtualNetwork $vnet -AddressPrefix $dmz.AddressPrefix
$updatedvnet | Set-AzVirtualNetwork
}
Output--

argument is null or empty - start-job

I am getting an argument is null error while trying to execute below command. Is there a way to can call the variable inside start-job
$RG = "xx"
$Location1 = "xx"
$VNET1="xx"
$PublicIP1="xx"
$VNGW1 = "xx"
Start-Job {
New-AzVirtualNetworkGateway -Name $VNGW1 -ResourceGroupName $RG -Location $Location1 -GatewayType Vpn -VpnType RouteBased -GatewaySku VpnGw1 -Asn 65511 -IpConfigurations $gwipconf1 -EnableBgp $True
}
Cannot validate argument on parameter 'Name'. The argument is null or empty. Provide an argument that is not null or empty, and then try the command again.
Cannot validate argument on parameter 'Name'. The argument is null or
empty. Provide an argument that is not null or empty, and then try the
command again.
Without the Argument list in Start-Job cmdlet, we cannot use the variables.
We have created a PowerShell script & tested the below scripts in our environment which is working fine. We can create Virtual Network Gateway using start-job in below two ways:
Using Variables as Argument List
Using Script in Start-Job
Using Variables as Argument List:
Firstly, We have created all the dependency resources for Virtual Network Gateway using below cmdlets:
$subnet = New-AzVirtualNetworkSubnetConfig -Name 'gatewaysubnet' -AddressPrefix '10.254.0.0/27'
$ngwpip = New-AzPublicIpAddress -Name ngwpip -ResourceGroupName "vnet-gateway" -Location "UK West" -AllocationMethod Dynamic
$vnet = New-AzVirtualNetwork -AddressPrefix "10.254.0.0/27" -Location "UK West" -Name vnet-gateway -ResourceGroupName "vnet-gateway" -Subnet $subnet
$subnet = Get-AzVirtualNetworkSubnetConfig -name 'gatewaysubnet' -VirtualNetwork $vnet
$ngwipconfig = New-AzVirtualNetworkGatewayIpConfig -Name ngwipconfig -SubnetId $subnet.Id -PublicIpAddressId $ngwpip.Id
Once the dependencies are created, we used the below Start-Job cmdlet for the creation of Virtual Network Gateway:
$RG = "xx"
$Location = "xx"
$gwipconf = "xx"
$VNGW = "xx"
Start-Job {
New-AzVirtualNetworkGateway -Name $args[3] -ResourceGroupName $args[0] -Location $ args[1] -GatewayType Vpn -VpnType RouteBased -GatewaySku VpnGw1 -Asn 65511 -IpConfigurations $ args[2] -EnableBgp $True
} -ArgumentList #($RG, $Location, $gwipconf, $VNGW)
Using Script in Start-Job:
Here, we have created a PowerShell file (gateway.ps1) & stored in local machine which contains the dependent resources creation followed by virtual network gateway creation(using the start-job).
New-AzResourceGroup -Location "UK West" -Name "vnet-gateway"
$subnet = New-AzVirtualNetworkSubnetConfig -Name 'gatewaysubnet' -AddressPrefix '10.254.0.0/27'
$ngwpip = New-AzPublicIpAddress -Name ngwpip -ResourceGroupName "vnet-gateway" -Location "UK West" -AllocationMethod Dynamic
$vnet = New-AzVirtualNetwork -AddressPrefix "10.254.0.0/27" -Location "UK West" -Name vnet-gateway -ResourceGroupName "vnet-gateway" -Subnet $subnet
$subnet = Get-AzVirtualNetworkSubnetConfig -name 'gatewaysubnet' -VirtualNetwork $vnet
$ngwipconfig = New-AzVirtualNetworkGatewayIpConfig -Name ngwipconfig -SubnetId $subnet.Id -PublicIpAddressId $ngwpip.Id
New-AzVirtualNetworkGateway -Name myNGW -ResourceGroupName vnet-gateway -Location "UK West" -IpConfigurations $ngwIpConfig -GatewayType "Vpn" -VpnType "RouteBased" -GatewaySku "Basic" -CustomRoute 192.168.0.0/24
Now, We have passed the above powershell script file path as an argument to the Start-job to create VPN gateway:
start-job -filepath \<pathofPowershellScript>
Here is the sample output for the reference :

How to add add additonal ip to a Network Interface Card in azure

I have a set of Private Ip address that i want to add to a Nic in Azure. I am running into error on adding the IP's to Nic.
set-AzContext -subscription "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
$vnet = Get-AzVirtualNetwork -Name "rosvnet" -ResourceGroupName "sample"
$subnet = Get-AzVirtualNetworkSubnetConfig -Name "default" -VirtualNetwork $vnet
$Nic = Get-AzNetworkInterface -ResourceGroupName "sample" -Name "closer-nic"
$Nic | New-AzNetworkInterfaceIpConfig -Name "ipconfig1" -PrivateIpAddress "10.1.0.11" -Subnet $subnet
$Nic | New-AzNetworkInterfaceIpConfig -Name "ipconfig2" -PrivateIpAddress "10.1.0.13" -Subnet $subnet
$Nic | New-AzNetworkInterfaceIpConfig -Name "ipconfig2" -PrivateIpAddress "10.1.0.14" -Subnet $subnet
Set-AzNetworkInterface -NetworkInterface $Nic
error is:
New-AzNetworkInterfaceIpConfig : The input object cannot be bound to any parameters for the command either because the command does not take pipeline input or the input and its properties do not
match any of the parameters that take pipeline input.
you can do like this
set-AzContext -subscription "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
$vnet = Get-AzVirtualNetwork -Name "rosvnet" -ResourceGroupName "sample"
$subnet = Get-AzVirtualNetworkSubnetConfig -Name "default" -VirtualNetwork $vnet
$Nic1 = New-AzNetworkInterfaceIpConfig -Name "ipconfig1" -PrivateIpAddress "10.1.0.11" -Primary -Subnet $subnet
$Nic2 = New-AzNetworkInterfaceIpConfig -Name "ipconfig2" -PrivateIpAddress "10.1.0.13" -Subnet $subnet
$Nic3 = New-AzNetworkInterfaceIpConfig -Name "ipconfig2" -PrivateIpAddress "10.1.0.14" -Subnet $subnet
$NIC = New-AzNetworkInterface `
-Name MyNIC `
-ResourceGroupName `
-Location `
-NetworkSecurityGroupId `
-IpConfiguration $Nic1,$Nic2,$Nic3

how to create multiple vms in azure resourcemanager portal with same NIC using powershell

I am trying to create multiple vms in azure resourcemanager portal with same NIC using powershell. But single VM alone getting created. when I use array for this exception occurs.
$i = 1;
[System.Collections.ArrayList]$vmArray1=#()
Do
{
$i;
switch($i){
{$vmName="Namenode"+$i}
{$vmName="Namenode"+$i}
default {$vmName="Datanode"+($i-2)}
}
$vmconfig=New-AzureRmVMConfig -VMName $vmName -VMSize $vmSize
$vmArray1.Add($vmconfig)
$i +=1
} Until ($i -gt $NumberOfVM)
$vm=Set-AzureRmVMOperatingSystem -VM $vmconfig -Windows -ComputerName $vmArray1 -Credential $credvm -ProvisionVMAgent -EnableAutoUpdate
But an exception occurs. Please let me know how to resolve this.
I am not sure whether it's your typing error or not. Your Set-AzureRmVMOperatingSystem Command is not inside the loop. That means it will always run only once. Beside of Operating System, you also need to provide Source Image, OS Disk, and Network Interface.
I have written something for you, and I have tested it at my end. It will create a set of VMs in one resource group and one Virtual Network. If you want the VMs in different resource groups or VNet, you can move the creation commands of resource groups or Vnet into the loop.
$credvm = Get-Credential
$NumberOfVM = <the number of VM you want to create>;
$ResourceGroupName = "<your resource group name>"
$Location = "East Asia"
## Storage
$StorageName = "<your storage account name>"
$StorageType = "Standard_GRS"
# Resource Group, if resource group has been created comment this out.
New-AzureRmResourceGroup -Name $ResourceGroupName -Location $Location
## Network
$InterfaceName = "<your interface name>"
$Subnet1Name = "Subnet1"
$VNetName = "<your vnet name>"
$VNetAddressPrefix = "10.0.0.0/16"
$VNetSubnetAddressPrefix = "10.0.0.0/24"
## Compute
$vmSize = "Standard_A2"
# Network
$SubnetConfig = New-AzureRmVirtualNetworkSubnetConfig -Name $Subnet1Name -AddressPrefix $VNetSubnetAddressPrefix
$VNet = New-AzureRmVirtualNetwork -Name $VNetName -ResourceGroupName $ResourceGroupName -Location $Location -AddressPrefix $VNetAddressPrefix -Subnet $SubnetConfig
$i = 1;
Do
{
$i;
$vmName="Namenode"+$i
$vmconfig=New-AzureRmVMConfig -VMName $vmName -VMSize $vmSize
$vm=Set-AzureRmVMOperatingSystem -VM $vmconfig -Windows -ComputerName $vmName -Credential $credvm -ProvisionVMAgent -EnableAutoUpdate
$OSDiskName = $vmName + "osDisk"
# Storage
$StorageAccount = New-AzureRmStorageAccount -ResourceGroupName $ResourceGroupName -Name $StorageName$i -Type $StorageType -Location $Location
## Setup local VM object
$vm = Set-AzureRmVMSourceImage -VM $vm -PublisherName MicrosoftWindowsServer -Offer WindowsServer -Skus 2012-R2-Datacenter -Version "latest"
$PIp = New-AzureRmPublicIpAddress -Name $InterfaceName$i -ResourceGroupName $ResourceGroupName -Location $Location -AllocationMethod Dynamic
$Interface = New-AzureRmNetworkInterface -Name $InterfaceName$i -ResourceGroupName $ResourceGroupName -Location $Location -SubnetId $VNet.Subnets[0].Id -PublicIpAddressId $PIp.Id
$VirtualMachine = Add-AzureRmVMNetworkInterface -VM $vm -Id $Interface.Id
$OSDiskUri = $StorageAccount.PrimaryEndpoints.Blob.ToString() + "vhds/" + $OSDiskName + ".vhd"
$VirtualMachine = Set-AzureRmVMOSDisk -VM $VirtualMachine -Name $OSDiskName -VhdUri $OSDiskUri -CreateOption FromImage
## Create the VM in Azure
New-AzureRmVM -ResourceGroupName $ResourceGroupName -Location $Location -VM $VirtualMachine
$i +=1
}
Until ($i -gt $NumberOfVM)

Resources