Skip to content

Instantly share code, notes, and snippets.

@Debcharon
Last active November 17, 2023 10:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Debcharon/78f8a832a0134ba8e20453bc00c330f3 to your computer and use it in GitHub Desktop.
Save Debcharon/78f8a832a0134ba8e20453bc00c330f3 to your computer and use it in GitHub Desktop.
Azure VM Dynamic IP Change
# 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
@Debcharon
Copy link
Author

Notice:

  1. You need to run command first on Your Azure CloudShell after creating Automation account.
az ad sp create-for-rbac --name {automation-account-name} --role Owner --scopes /subscriptions/{linked-subscription-name}/resourceGroups/{resource-group-name} --create-cert

#az ad sp create-for-rbac --name {automation-account-name} --role Owner --scopes /subscriptions/{linked-subscription-name}/resourceGroups/{resource-group-name}
  1. You need to replace $resource_group = "AzureVMJP" with your owned resource name.

Link: az ad sp | Microsoft Learn

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment