Create/ Add a New NIC and Private IP Address to Existing Azure VM
The first step is to open Windows PowerShell ISE and log in to your Azure subscription using the Login-AzureRmAccount cmdlet. Let’s define some variables for our VM, network, and other parameters that will be required.
$RG defines the Resource Group where the VM and VNET are located. The new NIC will be created in this Resource Group. I picked a name for the new NIC ($nicName), and a private IP address, which I know is available ($ipAddress). If you are not sure what the rest of the values should be for your deployment, locate the VM in the Azure management portal, and you’ll find information about the deployment, network, and any other related resources.
PowerShell
1
2
3
4
5
6
7
|
$vmName = ‘myVM’
$vnetName = ‘myVNET’
$RG = ‘PetriRG’
$subnetName = ‘Subnet-1’
$nicName = ‘PetriVM-NIC3’
$location = ‘North Europe’
$ipAddress = ’10.0.0.6’
|
The next step is to create an object for the VM using Get-AzureRmVM:
PowerShell
1
|
$myVm = Get-AzureRmVM -Name $vmName -ResourceGroupName $RG
|
And now we’ll create an object for the virtual network using Get-AzureRmVirtualNetwork:
PowerShell
1
|
$vnet = Get-AzureRmVirtualNetwork -Name $vnetName -ResourceGroupName $RG
|
The new NIC needs to be connected to a subnet ($subnetName), but we need to know the subnet ID before we can work with it in PowerShell:
PowerShell
1
|
$subnetID = (Get-AzureRmVirtualNetworkSubnetConfig -Name $subnetName -VirtualNetwork $vnet).Id
|
Finally, we can create a new NIC using the New-AzureRmNetworkInterface cmdlet:
PowerShell
1
|
New-AzureRmNetworkInterface -Name $nicName -ResourceGroupName $RG -Location $location -SubnetId $subnetID -PrivateIpAddress $ipAddress
|
Add a network interface in Azure (Image Credit: Russell Smith)
Attach the NIC to a VM
Now that a new NIC has been created, all that’s left to do is to attach it to the VM. First, we’ll create an object for the NIC using the Get-AzureRmNetworkInterfacecmdlet:
PowerShell
1
|
$myNIC = Get-AzureRmNetworkInterface -Name $nicName -ResourceGroupName $RG
|
Let’s add the NIC to the VM configuration:
PowerShell
1
|
$myVm = Add-AzureRmVMNetworkInterface -VM $myVm -Id $myNIC.Id
|
If you want to check that the configuration has been changed to include the new NIC, you can run the command below to see the list of NICs attached to the VM:
PowerShell
1
|
$myVM.NetworkProfile.NetworkInterfaces
|
Note that the primary NIC (0) is the first NIC in the list. If you want to set another NIC as the primary NIC, for instance, the third NIC (2), run the command below:
PowerShell
1
|
$myVM.NetworkProfile.NetworkInterfaces.Item(2).Primary = $true
|
Lastly, let’s commit the new configuration using the Update-AzureRmVM cmdlet:
PowerShell
1
|
Update-AzureRmVM -VM $myVm -ResourceGroupName $RG
|