Script Sample - VM Operations - Change Azure VM Size
@20aman Dec 03, 2018If you want to change the size of multiple Azure VMs in your environment, then you can leverage this script sample to update the sizes in one go. You will want to change the size of the VMs periodically after thoroughly reviewing the consumption. This can optimize your environment and can save you money in the process as well.
Script Requirements
The script requires you to populate the configurations CSV file. The sample CSV file is also provided along with the script. This configurations file should have the following columns:
- Computer - Name of the VM in Azure
- OSType - Windows or Linux
- ResourceGroupName - Resource Group of the VM
- SizeConversionNeeded - yes or no
- NewVMComputeSize - new size of the VM. e.g. Standard_DS4_v2. This should conform to the VM size names. For Windows VMs these names can be found by navigating to one of the sizes related link here: Sizes for Windows virtual machines in Azure
Script Working
The script works in 3 simple steps. In the first step the script fetches the Azure VM using Get-AzureRmVM cmdlet and ensures that it exists.
$currentVm = Get-AzureRmVM -ResourceGroupName $ResourceGroupName -Name $virtualMachineName -ErrorAction Stop
The second step is to update the size property for the Hardware profile of the vm object.
$currentVm.HardwareProfile.VmSize = $vmSize
Lastly, the script updates the VM using the below command.
Update-AzureRmVM -VM $currentVm -ResourceGroupName $ResourceGroupName
Note that there will be a restart on the VM during the size conversion. Do plan for an outage although very minimal. Do keep some buffer in the outage window to account for any unforeseen issues that may occur during the conversion. I have converted various VMs and have never encountered any issues. Still, when I plan for an outage, as a best practice I do plan for a larger window.
The script encapsulates all this logic into a reusable function. It also provides the best practices template to invoke this function. Note: Check the comments marked with "ToDo" where you should be making the changes.
Location of the Script
You can find this script in GitHub at this location: Change-AzureVMSize.ps1