It happens a lot of time with me when i needed to replace or change or modify the IP configuration of the Azure VM doesn't matter public IP or private so in this post we will be modifying Azure Vm Ip configuration with the help of Powershell.
Note: messing around with IP always leads to reboot.
here is the little understanding IP is associated to the NIC and NIC is associated to the VM and NIC is getting ip from the subnet where this VM lying. So the idea is getting to the IPconfig of the VM that too via NIC not directly , most of the azure cmdlet work in similar fashion. Lets start :
Below code will work for the private ip address and you can provide new ipaddress from the subnet which is not in use and available.
$vnet = Get-AzVirtualNetwork -Name 'VirtalNetwrokName' -ResourceGroupName 'ResourcegroupName'
$subnet = Get-AzVirtualNetworkSubnetConfig -Name 'SubnetName' -VirtualNetwork $vnet
$nic = Get-AzNetworkInterface -Name 'nic-name' -ResourceGroupName 'ResourcegroupName'
$nic | Set-AzNetworkInterfaceIpConfig -Name ipconfig1 -PrivateIpAddress 10.x.x.x -Subnet $subnet
$nic | Set-AzNetworkInterface
You also add the public IP address in above code and it would look like this :
$vnet = Get-AzVirtualNetwork -Name 'VirtalNetwrokName' -ResourceGroupName 'ResourcegroupName'
$subnet = Get-AzVirtualNetworkSubnetConfig -Name 'SubnetName' -VirtualNetwork $vnet
$publicIP = Get-AzPublicIpAddress -name 'PublicIpName' -ResourceGroupName 'ResourcegroupName'
$publicIp.PublicIpAllocationMethod = "dynamic"
$nic = Get-AzNetworkInterface -Name 'nic-name' -ResourceGroupName 'ResourcegroupName'
$nic | Set-AzNetworkInterfaceIpConfig -Name ipconfig1 -PrivateIpAddress 10.x.x.x -Subnet $subnet -Primary -PublicIpAddress $publicIP
$nic | Set-AzNetworkInterface
Now above code is all about adding or replacing the ip address either private or public. Now lets talk about if you need to remove the public IP and want to keep your VM only for private virtual network.
Use the below code :
$nic = Get-AzNetworkInterface -Name 'nic-name' -ResourceGroupName 'ResourcegroupName'
$nic.IpConfigurations.publicipaddress.id = $null
Set-AzNetworkInterface -NetworkInterface $nic
Below is the link for the GitHub for this code
https://github.com/ps-world/Azure-VM/blob/master/modifyingip.ps1
good one !!
ReplyDeletethanks!!
ReplyDelete