Friday, February 2, 2018

PowerShell script to expand and reduce the size of an Azure VM

When we provision VMs from Azure, we select the best possible size template from the gallery. But sometimes our VMs can’t cater the demand for specific time periods or are underutilized in certain times. One of my SQL Server VMs is very busy on Mondays, but manageable on other days.

I had to use Azure PowerShell script to modify the size template. In this article I’ll share the script I’ve used to expand the VM size and later reduce its size.

I’ve split the article in to two

  1. PowerShell script to expand and reduce the size of an Azure VM
  2. Change the size of Azure VM in a given schedule using Azure Runbook

Expand VM size

$vmName = "Test-VM"
$resourceGroup = "Test-Resource"
$highHwProfile = "Standard_DS13_v2_Promo"
$subscriptionId = "<subscription_id>"

Login-AzureRmAccount
Select-AzureRMSubscription -SubscriptionId $subscriptionId

Get-AzureRmVMSize -ResourceGroupName $resourceGroup -VMName $vmName
$vm = Get-AzureRmVM -ResourceGroupName $resourceGroup -Name $vmName
$vm.HardwareProfile.VmSize = $highHwProfile
Update-AzureRmVM -VM $vm -ResourceGroupName $resourceGroup

Reduce VM size

$vmName = "Test-VM"
$resourceGroup = "Test-Resource"
$highHwProfile = "Standard_DS12_v2_Promo"
$subscriptionId = "<subscription_id>"

Login-AzureRmAccount
Select-AzureRMSubscription -SubscriptionId $subscriptionId

Get-AzureRmVMSize -ResourceGroupName $resourceGroup -VMName $vmName
$vm = Get-AzureRmVM -ResourceGroupName $resourceGroup -Name $vmName
$vm.HardwareProfile.VmSize = $highHwProfile
Update-AzureRmVM -VM $vm -ResourceGroupName $resourceGroup

No comments: