Skip to content

Instantly share code, notes, and snippets.

@Debcharon
Last active June 7, 2024 03:34
Show Gist options
  • Save Debcharon/bb1bf32d82a32ec5745dc75081bcfd4f to your computer and use it in GitHub Desktop.
Save Debcharon/bb1bf32d82a32ec5745dc75081bcfd4f to your computer and use it in GitHub Desktop.
Azure VM Static IP Change (for Standard SKU IP address)
# Connect Azure account
Connect-AzAccount -Identity
# replace these with your own values
$resource_group = "MyDevCompute"
# Get Azure Resource in same resource group
$vm_name = (Get-AzResource -ResourceGroupName $resource_group -ResourceType "Microsoft.Compute/virtualMachines").Name
$public_ip_name = (Get-AzResource -ResourceGroupName $resource_group -ResourceType "Microsoft.Network/publicIPAddresses")[0].Name
$dns_label = (Get-AzPublicIpAddress -ResourceGroupName $resource_group -Name $public_ip_name).DnsSettings.DomainNameLabel
# Stop the VM
# Stop-AzVM -ResourceGroupName $resource_group -Name $vm_name -Force
# Get the NIC
$nic_name = (Get-AzResource -ResourceGroupName $resource_group -ResourceType "Microsoft.Network/networkInterfaces").Name
$nic = Get-AzNetworkInterface -ResourceGroupName $resource_group -Name $nic_name
# Get NIC ipconfig
# $ip_config_name = (Get-AzNetworkInterface -ResourceGroupName $resource_group -Name $nic_name).IpConfigurations[0].Name
# Disassociate the existing public IP address from the NIC
$nic.IpConfigurations[0].PublicIpAddress = $null
Set-AzNetworkInterface -NetworkInterface $nic
# Remove the old public IP address
Remove-AzPublicIpAddress -ResourceGroupName $resource_group -Name $public_ip_name -Force
# Create a new public IP address
$location = (Get-AzResourceGroup -Name $resource_group).Location
$public_ip = New-AzPublicIpAddress -Name $public_ip_name -ResourceGroupName $resource_group -Sku Standard -AllocationMethod Static -Location $location -DomainNameLabel $dns_label -Force
# Associate the new public IP address with the NIC
$nic.IpConfigurations[0].PublicIpAddress = $public_ip
Set-AzNetworkInterface -NetworkInterface $nic
# Start the VM
# Start-AzVM -ResourceGroupName $resource_group -Name $vm_name
# Output the new public IP address details
Get-AzPublicIpAddress -ResourceGroupName $resource_group -Name $public_ip_name |
Select-Object @{Name='Fqdn'; Expression={$_.DnsSettings.Fqdn}}, IpAddress, PublicIpAllocationMethod
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment