How To Rename an Azure Virtual Machine

5 Min. Read

In this article, I will share with you how to rename an Azure virtual machine using PowerShell. The same can apply whether you want to rename a Linux or Windows VM.

Introduction

Renaming an Azure VM is not a new problem. If you are coming from the on-premises world, you know how simple it’s to rename a virtual machine in Hyper-V, VMware, or on any other virtualization platform. This is not the case when you deploy a Virtual Machine using the Azure Portal, and you find yourself having to rename it afterward, you know how painful it is.

If you deploy your VMs with any infrastructure-as-code (IaC) tool such as ARM template, Bicep, Terraform, or you use PowerShell or Azure CLI, then you can specify the Azure VM name at deployment time. But again, we can’t rename it after the deployment is completed.

Well, this is the purpose of this article, I have developed a nifty PowerShell tool that will help you to rename an Azure VM (Windows or Linux) by destroying the VM resource without touching the existing resources and then re-creating it with a new name and attach all the resources.

If you want to rename the OS Disk for an Azure virtual machine, please check the following article.

If you want to rename the NIC interface for an Azure virtual machine, please check the following article.

Rename Azure VM

You have a couple of options to run the script, you can either use the Azure Cloud Shell, Visual Studio (VS) Code, or the new Windows Terminal. The Script works with PowerShell 5.1 or PowerShell 7.1.x (core) with the Az module installed.

You can use the following PowerShell command to install and update the “Az module” locally on your machine.

# Make sure you have the latest version of PowerShellGet installed
Install-Module -Name PowerShellGet -Force

 # Install and update to the latest Az PowerShell module
Install-Module -Name Az -AllowClobber -Force

.EXAMPLE

.\Rename-AzVM.ps1 -resourceGroup [ResourceGroupName] -OldVMName [VMName] -NewVMName [VMName] -Verbose

This example will rename an existing Azure virtual machine, you need to specify the Resource Group name, the old VM name, and the new VM name. The script will preserve the old VM settings and resources, and then apply them to the new Azure VM whether it’s Windows or Linux.

Here is an example of the output once you run this tool:

Rename Azure Virtual Machine

PowerShell Code

The complete script is detailed below to automate the entire VM rename process:

<#
.SYNOPSIS
Rename Azure VM.

.DESCRIPTION
Rename an Azure virtual machine for Linux and Windows OS.

.NOTES
File Name : Rename-AzVM.ps1
Author    : Microsoft MVP/MCT - Charbel Nemnom
Version   : 1.0
Date      : 29-August-2021
Update    : 30-August-2021
Requires  : PowerShell 5.1 or PowerShell 7.1.x (Core)
Module    : Az Module
OS        : Windows or Linux VMs

.LINK
To provide feedback or for further assistance please visit: https://charbelnemnom.com

.EXAMPLE
.\Rename-AzVM.ps1 -resourceGroup [ResourceGroupName] -OldVMName [VMName] -NewVMName [VMName] -Verbose
This example will rename an existing Azure virtual machine, you need to specify the Resource Group name, old VM name and the new VM name.
The script will preserve the old VM settings and resources, and then apply them to the new Azure VM.
#>

[CmdletBinding()]
Param (
    [Parameter(Position = 0, Mandatory = $true, HelpMessage = 'Enter the Resource Group of the Azure VM')]
    [Alias('rg')]
    [String]$resourceGroup,

    [Parameter(Position = 1, Mandatory = $True, HelpMessage = 'Enter the existing Azure VM name')]
    [Alias('OldVM')]
    [String]$OldVMName,

    [Parameter(Position = 2, Mandatory = $true, HelpMessage = 'Enter the desired new Azure VM name')]
    [Alias('NewVM')]
    [String]$NewVMName
)

#! Check Azure Connection
Try {
    Write-Verbose "Connecting to Azure Cloud..."
    Connect-AzAccount -ErrorAction Stop | Out-Null
}
Catch {
    Write-Warning "Cannot connect to Azure Cloud. Please check your credentials. Exiting!"
    Break
}

$azSubs = Get-AzSubscription
$azSub = 0
Do {
    Write-Verbose "Set Azure Subscription context to: $($azSubs[$azSub].Name)"
    Set-AzContext -Subscription $azSubs[$azSub] | Out-Null
    $VMInfo = Get-AzVM | Where-Object {$_.Name -eq $OldVMName -and $_.ResourceGroupName -eq $resourceGroup}
    if ($VMInfo) {
        #! Get original Azure VM properties and export it
        Try {
            Write-Verbose "Get original Azure VM properties and export its configuration to $(get-location)"
            Get-AzVM -ResourceGroupName $resourceGroup -Name $OldVMName -ErrorAction Stop | Export-Clixml .\AzVM_Backup.xml -Depth 5
        }
        Catch {
            Write-Warning "Cannot Export Azure VM $OldVMName to $(get-location) - Exiting!"
            Break
        }
    }
    $azSub++
} while ((!$VMInfo) -and ($azSub -lt $azSubs.count))

If (!$VMInfo) {
    Write-Warning "The Azure VM < $OldVMName > does not exist. Please check your virtual machine name!"
    Break
}

#! Import Azure VM settings from backup XML and store it in a variable
Write-Verbose "Importing the old Azure VM properties..."
$oldVM = Import-Clixml .\AzVM_Backup.xml

#! Delete the Old Azure VM
Write-Verbose "Deleting the old Azure VM and keeping the other resources intact..."
Remove-AzVM -ResourceGroupName $oldVM.ResourceGroupName -Name $oldVM.Name -Force

#! Creating the new Azure VM configuration
Write-Verbose "Creating the new Azure VM configuration..."
$newVM = New-AzVMConfig -VMName $NewVMName -VMSize $oldVM.HardwareProfile.VmSize -Tags $oldVM.Tags

#! Attaching the OS Disk of the old VM to the new Azure VM (Windows/Linux)
if ($oldvm.StorageProfile.osdisk.ostype.value -eq "Windows") {
    Write-Verbose "Attaching the Windows OS Disk of the old VM to the new Azure VM..."
    Set-AzVMOSDisk -VM $newVM -CreateOption Attach -ManagedDiskId $oldVM.StorageProfile.OsDisk.ManagedDisk.Id -Name $oldVM.StorageProfile.OsDisk.Name -Windows | Out-Null
}else {
    Write-Verbose "Attaching the Linux OS Disk of the old VM to the new Azure VM..."
    Set-AzVMOSDisk -VM $newVM -CreateOption Attach -ManagedDiskId $oldVM.StorageProfile.OsDisk.ManagedDisk.Id -Name $oldVM.StorageProfile.OsDisk.Name -Linux | Out-Null
}

#! Attaching all NICs of the old VM to the new Azure VM
Write-Verbose "Attaching all NICs of the old VM to the new Azure VM..."
$oldVM.NetworkProfile.NetworkInterfaces | % {Add-AzVMNetworkInterface -VM $newVM -Id $_.Id} | Out-Null

#! Attaching all Data Disks (if any) of the old VM to the new Azure VM
Write-Verbose "Attaching all Data Disks (if any) of the old VM to the new Azure VM..."
$oldVM.StorageProfile.DataDisks | % { Add-AzVMDataDisk -VM $newVM -Name $_.Name -ManagedDiskId $_.ManagedDisk.Id -Caching $_.Caching -Lun $_.Lun -DiskSizeInGB $_.DiskSizeGB -CreateOption Attach }

#! Creating the new Azure VM
Write-Verbose "Creating the new Azure VM..."
New-AzVM -ResourceGroupName $oldVM.ResourceGroupName -Location $oldVM.Location -VM $newVM

If you look back in the Azure Portal, we can see that the old VM name is renamed successfully.

Rename Azure VM - Resource Group
Confirm by looking for the VM in the Azure Portal under the resource group

If you have any feedback or changes that everyone should receive, please feel free to leave a comment below.

That’s it there you have it. Happy Azure VM Renaming!

Summary

In this article, you have learned how to rename an Azure virtual machine using PowerShell. We first back up the VM configuration and export it to an (.XML) file for later reference, then delete a VM, package a new VM configuration, attach all disks and network profile, and finally creating the new VM.

Please note that the PowerShell script outlined above is for a basic VM. There might be other important details that need to be included in the renamed virtual machine. Because some settings can only be set during the creation so these must be carefully considered too before running the script.

A couple of examples where careful planning is required, the Availability Set to which the VM can be added only when the VM is created, however, you can change the availability set for an Azure VM using Azure PowerShell as described here, another example is if the VM is attached to a load balancer, attached to an Azure Application Gateway, or protected with Azure Backup.

We highly recommend planning carefully before you proceed with the renaming process to increase the chance of success.

__
Thank you for reading my blog.

If you have any questions or feedback, please leave a comment.

-Charbel Nemnom-

Related Posts

Previous

Migrating Your Video Pipeline to Azure Media Services

Enable Azure SQL Auditing with Azure Policy

Next

Let me know what you think, or ask a question...

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Subscribe to Stay in Touch

Never miss out on your favorite posts and our latest announcements!

The content of this website is copyrighted from being plagiarized!

You can copy from the 'Code Blocks' in 'Black' by selecting the Code.

Please send your feedback to the author using this form for any 'Code' you like.

Thank you for visiting!