Replacing NIC or IP address on Azure VM


There are scenarios where we have to either remove the NIC or attach the new one or replace the IP address on Azure VM. Powershell is one of the best way to do this and so is the Portal.
Well when we talk about the NIC replacement that seems pretty straightforward but not the IP address because it could be the possibilities that IP that you want assign is already associated with another NIC or in use so before you plan the IP replacement or assignment you should check and confirm desired IP is free to attach.

Now you can not simply click unattached NIC on the Network configuration page as shown below because VM must have at least one NIC.

Second you can attach the new NIC without any trouble because VM has existing NIC and IP assigned however you can not move the existing NIC without stopping the VM because that NIC or IP is in use.



Hence the steps to follow would be -
  1. Attach the desired NIC to the VM first.
  2. Stop the VM 
  3. Detach the old NIC 
  4. Update the IP configuration of new NIC (desired private Ip but make sure not in use already)
  5. Start the VM.
Similarly you can delete the existing IP configuration from the NIC but NIC can not exist without IP so you need to first give it random IP and then delete the existing IP configuration.




As shown in the picture above secondary IP added to the NIC and then delete the primary IP configuration if you try to delete primary directly you will get error.

We can perform the NIC replacement task with the help of PS as well and below is code and you can also download it from github : https://github.com/ps-world/Azure-VM/blob/master/Nicreplace.PS1

Assumptions:
You are logged in to your Azure account via PS & you are using AZ module of PS.

$rg = 'Resourcegroupname'
$vm = get-azvm -ResourceGroupName $rg -Name $vmname
$nicid = $VM.NetworkProfile.NetworkInterfaces.Id
$newnic = Get-AzNetworkInterface -ResourceGroupName $rg -Name $nicname
Add-AzVMNetworkInterface -VM $vm -Id $newnic.Id
Remove-AzVMNetworkInterface -VM $vm -NetworkInterfaceIDs $nicid
Update-AzVM -VM $vm -ResourceGroupName $rg




No comments:

Post a Comment

Azure DevOps

Azure DevOps is a suite of development tools provided by Microsoft, designed to support the entire development lifecycle of a software proje...