How to set PublicIPAllocation via PowerShell

Also, How to remove a public IP address object via Azure PowerShell

I was recently tasked with changing a series of AzureRM Public IP address allocation methods from dynamic to static and others from Static IP addresses to dynamic.

To set a NIC to static is very straight forward.

[code language=”PowerShell”]

$ip.PublicIpAllocationMethod = ‘Static’

$ip |Set-AzureRmPublicIpAddress

[/code]

You change the value to static and then run the set-azurermpublicIPAddress command

 

To set a NIC back to Dynamic however is a little more complicated.

[code language=”PowerShell”]

#Get the network adapter that uses the IP

$nic = Get-AzureRmNetworkInterface -Name $ip.Name -ResourceGroupName $ip.ResourceGroupName

#create an empty network adapter powershell object

$nullPubIp = New-Object Microsoft.Azure.Commands.Network.Models.PSPublicIpAddress

#apply the empty network adapter powershell object (removes the IP address object)

$nic.IpConfigurations[0].PublicIpAddress = $nullPubIp

Set-AzureRmNetworkInterface -NetworkInterface $nic

#change the allocationmethod

$ip.PublicIpAllocationMethod = ‘Dynamic’

$ip |Set-AzureRmPublicIpAddress

#reapply the IP address object to the adapter

$nic.IpConfigurations[0].PublicIpAddress = $ip

Set-AzureRmNetworkInterface -NetworkInterface $nic

[/code]

As you can see it is a multi-step process.

  1. In my example the VM NIC and IP address have the same name (supported because the resource type is different) so I was able to pass the string value of the IP address name and resource group and get the network adapter
  2. Create an empty ($null) IP address object
  3. Apply the $null object and save the adapter
  4. Convert the existing IP address object back to dynamic
  5. Reapply the IP address object to the adapter.

It is possible that you could create a new IP address object, but the problem is that the DNS name would take a while to purge out, so this is a much better solution.

 

Special thanks to my coworker Chris Dituri for showing me how to remove the public IP by applying the null object.