Created
November 8, 2023 06:48
Azure VM Dynamic Secondary IP change, all of them will be renew
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Connect Azure account | |
Connect-AzAccount -Identity | |
# replace these with your own values | |
$resource_group = "AzureVMJP" | |
# Get Azure Resource in same resource group | |
$location = (Get-AzResourceGroup -Name $resource_group).Location | |
$vm_name = (Get-AzResource -ResourceGroupName $resource_group -ResourceType "Microsoft.Compute/virtualMachines").Name | |
# 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 | |
$secondary_ip_configs = $nic.IpConfigurations | Where-Object { $_.Name -ne $ip_config_name } | |
# Disassociate the existing public IP address from the NIC | |
foreach ($secondary_ip_config in $secondary_ip_configs) { | |
$secondary_ip_config.PublicIpAddress = $null | |
} | |
Set-AzNetworkInterface -NetworkInterface $nic | |
# Create a new public IP address | |
foreach ($secondary_ip_config in $secondary_ip_configs) { | |
# Extract the number from the secondary IP configuration name | |
$num = $secondary_ip_config.Name -replace 'ipconfig', '' | |
# Create a new public IP address name | |
$public_ip_name = $resource_group + "-ip" + ($num - 1) | |
# Create a new public IP address | |
$public_ip = New-AzPublicIpAddress -Name $public_ip_name -ResourceGroupName $resource_group -AllocationMethod Dynamic -Location $location -Force | |
# Associate the new public IP address with the secondary IP configuration | |
$secondary_ip_config.PublicIpAddress = $public_ip | |
} | |
# Associate the new public IP address with the NIC | |
Set-AzNetworkInterface -NetworkInterface $nic | |
# Start the VM | |
# Start-AzVM -ResourceGroupName $resource_group -Name $vm_name | |
# Output the new public IP address details for each secondary IP configuration | |
foreach ($secondary_ip_config in $secondary_ip_configs) { | |
$public_ip_name = $resource_group + '-ip' + ([int]($secondary_ip_config.Name -replace 'ipconfig', '') - 1) | |
Get-AzPublicIpAddress -ResourceGroupName $resource_group -Name $public_ip_name | | |
Select-Object IpAddress, PublicIpAllocationMethod | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment