Last active
November 17, 2023 10:14
-
-
Save Debcharon/78f8a832a0134ba8e20453bc00c330f3 to your computer and use it in GitHub Desktop.
Azure VM Dynamic IP Change
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 | |
$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 | |
# Create a new public IP address | |
$location = (Get-AzResourceGroup -Name $resource_group).Location | |
$public_ip = New-AzPublicIpAddress -Name $public_ip_name -ResourceGroupName $resource_group -AllocationMethod Dynamic -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
Notice:
$resource_group = "AzureVMJP"
with your owned resource name.Link: az ad sp | Microsoft Learn