Created
April 8, 2020 19:23
-
-
Save larryclaman/5a3bb2a7b0bb7b559b1af192469c718a to your computer and use it in GitHub Desktop.
Convert an Azure VM to a Spot VM type
This file contains hidden or 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
<# Convert a VM to a Spot VM | |
Based on sample script at https://docs.microsoft.com/en-us/azure/virtual-machines/windows/change-availability-set | |
NOTE: Extensions will not be copied to new instance!! | |
#> | |
# Set variables to your specifics | |
$resourceGroup = "myRG" | |
$vmName = "myVM" | |
# Get the details of the VM to be moved to the Availability Set | |
$originalVM = Get-AzVM ` | |
-ResourceGroupName $resourceGroup ` | |
-Name $vmName | |
# Create the basic configuration for the replacement VM. | |
$newVM = New-AzVMConfig ` | |
-VMName $originalVM.Name ` | |
-VMSize $originalVM.HardwareProfile.VmSize ` | |
-Priority "Spot" -MaxPrice -1 | |
# Confgure OS Disk | |
Set-AzVMOSDisk ` | |
-VM $newVM -CreateOption Attach ` | |
-ManagedDiskId $originalVM.StorageProfile.OsDisk.ManagedDisk.Id ` | |
-Name $originalVM.StorageProfile.OsDisk.Name | |
if ($originalVM.OSProfile.WindowsConfiguration) { | |
$newVM.StorageProfile.OsDisk.OsType="Windows" | |
} else { | |
$newVM.StorageProfile.OsDisk.OsType="Linux" | |
} | |
# Add Data Disks | |
foreach ($disk in $originalVM.StorageProfile.DataDisks) { | |
Add-AzVMDataDisk -VM $newVM ` | |
-Name $disk.Name ` | |
-ManagedDiskId $disk.ManagedDisk.Id ` | |
-Caching $disk.Caching ` | |
-Lun $disk.Lun ` | |
-DiskSizeInGB $disk.DiskSizeGB ` | |
-CreateOption Attach | |
} | |
# Add NIC(s) and keep the same NIC as primary | |
foreach ($nic in $originalVM.NetworkProfile.NetworkInterfaces) { | |
if ($nic.Primary -eq "True") | |
{ | |
Add-AzVMNetworkInterface ` | |
-VM $newVM ` | |
-Id $nic.Id -Primary | |
} | |
else | |
{ | |
Add-AzVMNetworkInterface ` | |
-VM $newVM ` | |
-Id $nic.Id | |
} | |
} | |
if ($originalVM.AvailabilitySetReference.Id) { | |
#$newVM.AvailabilitySetReference=$originalVM.AvailabilitySetReference.Id | |
echo "Warning: VM $originalVM.Name is in an availability set. Spot VMs cannot run in availability sets." | |
} | |
# Remove the original VM | |
Remove-AzVM -ResourceGroupName $resourceGroup -Name $vmName | |
# Recreate the VM | |
New-AzVM ` | |
-ResourceGroupName $resourceGroup ` | |
-Location $originalVM.Location ` | |
-VM $newVM ` | |
-DisableBginfoExtension | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment