Skip to content
Tutorials Center
My learning

Topics

Lesson 10 of 57 ยท Compute

Virtual Machines

Understand Azure virtual machines: size families, images, disks, SSH and RDP access, creating a VM with the az CLI, spot VMs, reservations and when to choose a VM.

A virtual machine (VM) is a computer you rent by the hour. You pick the amount of CPU and memory, an operating system image and some disks, and Azure starts it on a physical host in a datacenter. After that it is yours: you log in, install software, patch the operating system and decide what runs. VMs are the Infrastructure-as-a-Service end of the spectrum you met in What Is Cloud Computing?, and they are the most flexible and the most work to operate.

This lesson explains how VM sizes are named, what disks a VM has, how to connect, how to create one with the CLI, and the three ways to pay less. Creating a VM needs a subscription, so the commands are read-only. The runnable examples are JavaScript stand-ins with invented prices, because real prices change and differ by region.

Sizes and series

A size fixes the number of virtual CPUs (vCPUs), the memory, the maximum disk and network throughput, and sometimes extras such as a GPU. Sizes are grouped into series by purpose:

Family Typical use
B Burstable: cheap, low baseline CPU that can burst; small sites, dev/test
D General purpose: balanced CPU and memory; the default choice for apps and databases
E Memory optimized: more RAM per vCPU; caches, in-memory analytics, large databases
F Compute optimized: more CPU per GB of RAM; batch jobs, game servers
L Storage optimized: very fast local disks
N GPU: machine learning, rendering

Names follow a pattern. In Standard_D4s_v5, D is the family, 4 the number of vCPUs, s means it supports premium SSD disks, and v5 is the hardware generation. Letters such as a (AMD), d (local temporary disk) or l (low memory) can appear too. Newer generations usually give better performance for the same or lower price, so prefer the latest generation available in your region. The size list differs by region, and quotas limit how many vCPUs of each family you may use (see Accounts, Tenants and Subscriptions).

Resizing is possible: you can move a VM to another size, which usually restarts it. That makes starting small and measuring a good habit.

Images

An image is the starting point for the operating system disk. Azure offers Linux distributions (Ubuntu, Debian, Red Hat and more) and Windows Server from the Marketplace, and you can also build your own image from a configured VM and share it through a gallery. Using a prepared image makes new VMs identical, which is the basis of the scaling covered in Scaling and Autoscale.

Disks

A VM normally has up to three kinds of storage:

  • The OS disk: a managed disk holding the operating system. It persists when the VM stops.
  • Data disks: extra managed disks you attach for application data. Each is a separate resource and can be detached and moved.
  • A temporary disk, on many sizes: fast local storage whose contents can be lost when the VM moves to another host or is redeployed. Use it for caches and scratch files, never for data you need to keep.

Managed disks come as Standard HDD, Standard SSD, Premium SSD and, for demanding databases, higher tiers. Their performance and redundancy are explained in Disks and Redundancy.

Connecting: SSH and RDP

Linux VMs are managed over SSH (port 22) with a key pair, not a password. Windows VMs use RDP (port 3389). Both are popular targets for automated attacks when exposed to the internet. Good practice:

Creating a VM with the CLI

These commands are read-only here, because they would create billable resources:

Terminal
az group create --name web --location westeurope

az vm create \
  --resource-group web \
  --name vm1 \
  --image Ubuntu2204 \
  --size Standard_B2s \
  --admin-username azureuser \
  --generate-ssh-keys

# Connect with the public IP shown in the output
ssh azureuser@<public-ip>

# Stop paying for compute: deallocate (a plain OS shutdown is NOT enough)
az vm deallocate --resource-group web --name vm1

# Clean up everything in the group
az group delete --name web --yes

Behind that single command Azure also created a virtual network, a network interface, a public IP address, a network security group and an OS disk. Each is its own resource; deleting only the VM leaves the disk, IP and others behind, still costing money. Putting everything for one workload in a resource group and deleting the group avoids orphans (see Resource Groups and Azure Resource Manager).

The states matter for billing. A running VM pays for compute. If you shut the operating system down from inside, the VM is stopped but Azure still holds the hardware for you, so you still pay. A deallocated VM releases the hardware and stops compute charges, though its disks keep costing storage money.

flowchart LR
    C["Created"] --> R["Running<br/>compute billed"]
    R -->|"OS shutdown"| S["Stopped<br/>still billed"]
    R -->|"az vm deallocate"| D["Deallocated<br/>disks only"]
    S -->|"az vm deallocate"| D
    D -->|"az vm start"| R

Only deallocation stops compute charges. Disks and public IPs are billed separately.

Sizing a VM: a stand-in

Choosing a size means matching your needs to a catalog row and then checking the cost. The stand-in below uses a small invented catalog and invented hourly prices. It finds the cheapest size that satisfies a CPU and memory requirement with a safety margin, and estimates a 730-hour month. Real catalogs have many more sizes and real prices vary by region and operating system.

JS Pick the cheapest fitting VM size

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Look at the "cache server": the memory need makes the memory-optimized E4s cheaper than a larger general-purpose size, which is exactly why the E family exists. The last row shows a real situation too: sometimes no single VM fits and you must scale out instead.

Paying less

There are three levers, and you can combine them with the habits above (deallocate when idle, right-size, delete orphans):

  • Reservations: commit to a size family in a region for one or three years in exchange for a significant discount versus pay-as-you-go. Best for steady, predictable workloads. A related savings plan commits to an hourly spend and is more flexible about which sizes it applies to.
  • Spot VMs: unused capacity at a large discount, with no guarantee. Azure can evict a spot VM at short notice when it needs the capacity back or when the market price passes your maximum. Use them only for interruptible work: batch jobs, rendering, CI workers, stateless scale-out nodes.
  • Hybrid benefit and dev/test pricing: reuse existing Windows Server or SQL Server licenses, or pay lower rates for non-production subscriptions, when your agreement allows it.
Terminal
az vm create --resource-group batch --name worker1 \
  --image Ubuntu2204 --size Standard_D4s_v5 \
  --priority Spot --eviction-policy Deallocate --max-price -1

--max-price -1 means "pay up to the normal on-demand price".

Comparing the options: a stand-in

The second stand-in compares a month of the same VM under four plans. All discounts are invented round numbers for the exercise; read the actual rates in the Azure pricing calculator.

JS Compare pay-as-you-go, reserved and spot

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Notice that a plan is only cheaper if it matches how you use the VM: a reservation on a machine you leave deallocated most of the time is wasted money, and a spot VM is no bargain for something that must never stop.

Operating a VM: extensions, resizing, shutdown and diagnostics

Creating a VM is the easy part; the rest of its life is operations. These commands are read-only here because they change a real VM.

Extensions

A VM extension is a small package that runs inside the VM, managed from the Azure control plane: install monitoring agents, run a script, configure antivirus, join a domain, or apply a desired-state configuration. The Custom Script Extension is the simplest way to run a script once a VM exists:

Terminal
az vm extension set --resource-group web --vm-name vm1 \
  --publisher Microsoft.Azure.Extensions --name CustomScript --version 2.1 \
  --settings '{"commandToExecute": "sudo apt-get update && sudo apt-get install -y nginx"}'

az vm extension list --resource-group web --vm-name vm1 --output table

Extensions need the VM agent and outbound access to Azure, and they run with high privilege, so treat their scripts like production code.

Resizing

az vm list-vm-resize-options shows sizes available on the VM's current hardware cluster. Resizing to one of them restarts the VM; if the new size is not on the current hardware, you must deallocate first so Azure can place it elsewhere. Plan a short outage and avoid resizing a VM that has a temporary disk you rely on, because its contents are lost when the VM moves.

Terminal
az vm list-vm-resize-options --resource-group web --name vm1 --output table
az vm resize --resource-group web --name vm1 --size Standard_D4s_v5
# if the size is not offered: az vm deallocate, then resize, then az vm start

Auto-shutdown and tags

Dev and test VMs are often idle at night. The auto-shutdown setting deallocates a VM at a fixed time every day and can notify you first; scheduling a start is done with automation such as Azure Automation or a Functions timer. Use tags (env=dev, owner=ana) so each VM can be found and billed (see Cost Management).

Terminal
az vm auto-shutdown --resource-group web --name vm1 --time 1900
az vm update --resource-group web --name vm1 --set tags.env=dev tags.owner=ana

Boot diagnostics, passwords and snapshots

When a VM will not respond, you cannot look at its screen. Boot diagnostics captures the serial console log and a screenshot, so you can see a failed boot or a stuck update. Reset access (the VMAccess extension) resets an admin password or SSH key when you are locked out. A snapshot copies a disk at one moment, for a safe point before risky changes (see Disks and Redundancy).

Terminal
az vm boot-diagnostics enable --resource-group web --name vm1
az vm boot-diagnostics get-boot-log --resource-group web --name vm1
az vm user update --resource-group web --name vm1 --username azureuser --ssh-key-value "$(cat ~/.ssh/id_rsa.pub)"
az snapshot create --resource-group web --name vm1-os-before-patch \
  --source $(az vm show -g web -n vm1 --query storageProfile.osDisk.managedDisk.id -o tsv)

The Azure mobile app and Cloud Shell can run many of these tasks from a phone in an emergency (see Portal, Azure CLI and PowerShell).

A first-aid checklist: a stand-in

When a VM misbehaves, work from the outside in. The stand-in turns symptoms into the first thing to check.

JS VM troubleshooting first steps

Press Run (or Ctrl + Enter) to see the console output here.

No output.

When to choose a VM

Choose a VM when you need full control of the operating system, run software that does not fit a managed service, lift an existing application as-is, or need special hardware such as GPUs. If you just need to host a web app or run small pieces of code, App Service and Web Apps or Azure Functions remove the patching and scaling work. The full decision tree is in Choosing a Compute Service.

Fleet chores: bulk resize, scheduled start and stop, archiving and cleanup

Resizing many VMs with a script

Resizing one VM in the portal is easy; resizing twenty is a script. The PowerShell pattern loops over a list of names, reads each VM, sets the new size and applies the change. Run it in a maintenance window, because each VM restarts.

POWERSHELL
$VMsList = @("TestVM", "TestVM2", "TestVM3")
$rg = "web"
$newSize = "Standard_D4s_v5"

foreach ($name in $VMsList) {
    $vm = Get-AzVM -ResourceGroupName $rg -Name $name
    if ($vm.HardwareProfile.VmSize -eq $newSize) { continue }   # already done
    $vm.HardwareProfile.VmSize = $newSize
    Update-AzVM -ResourceGroupName $rg -VM $vm
}

The advantages over clicking: it is repeatable, skips machines that already match, and can log what it changed. If a size is not available on the VM's current hardware cluster, deallocate it first with Stop-AzVM, resize, then Start-AzVM. Inside Windows, resizing changes the hardware the guest sees automatically; you do not need msconfig to use the extra processors, and you should not limit processors there unless you want fewer than the VM provides.

Starting and stopping on a schedule

Auto-shutdown handles the evening. For a start in the morning and a shutdown in the evening with email notification, use the Start/Stop VMs v2 solution (it deploys Functions and Logic Apps that start and stop VMs selected by tag, resource group or subscription), or write a timer-triggered Function or an Automation runbook yourself. Prerequisites are a resource group to host the solution and permission to deploy it; tag the VMs it should manage.

Spot VMs: terminology and limits

A Spot VM runs on spare capacity at a large discount. Terms to know: the eviction policy (Deallocate keeps the disks so you can restart later, Delete removes everything), the max price (the most per hour you will pay, or -1 for "up to on-demand"), and eviction itself (Azure takes the VM back with about 30 seconds of notice, available inside the VM through the Scheduled Events endpoint). Advantages are cost and large capacity for batch jobs. Limitations: no uptime SLA, no guarantee of capacity, not available for every size, and not suitable for anything that cannot be interrupted.

Archiving a VM and deleting leftovers

To archive a VM you will not need for months, stop (deallocate) it, make a snapshot or export the managed disk to a VHD in a storage account (using a SAS URL and azcopy), and place that storage in the Cool or Archive tier. Then delete the VM, NIC, public IP and original disk. You keep the restore option at a small fraction of the cost, but you must write down the VM size, network settings and extensions, because only the disk is kept.

Snapshots pile up. List and delete old ones deliberately:

POWERSHELL
Get-AzSnapshot | Where-Object { $_.TimeCreated -lt (Get-Date).AddDays(-30) } |
  Select-Object Name, ResourceGroupName, TimeCreated
# review the list, then:
# Remove-AzSnapshot -ResourceGroupName <rg> -SnapshotName <name> -Force

Review the list before removing anything: a snapshot may be the only copy of a disk. The stand-in selects candidates by age and tag so you can see the logic.

JS Which snapshots can be cleaned up?

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. In the size name Standard_D4s_v5, what does the 4 mean?

    The number after the family letter is the vCPU count. The final v5 is the hardware generation.
  2. 2. You shut down a VM from inside its operating system. What happens to billing?

    An OS shutdown leaves the VM allocated. Deallocating releases the hardware and ends compute charges, though disks still cost storage fees.
  3. 3. Which workload is the best fit for a spot VM?

    Spot capacity can be evicted at short notice, so it suits interruptible, restartable work.
  4. 4. Where should you keep data you cannot afford to lose on a VM?

    The temporary disk can be wiped when the VM moves hosts. Managed disks persist independently of the host.
  5. 5. Which is the safest way to administer a Linux VM?

    Keys instead of passwords, and no broad exposure of management ports, remove the most common attack paths.

Summary

  • A VM is rented compute with a size (family, vCPUs, memory), an image and disks; you operate the operating system.
  • Series such as B, D, E, F, L and N fit different workloads; read names like Standard_D4s_v5 as family, vCPUs, features and generation.
  • OS and data disks persist; the temporary disk does not.
  • Use SSH keys or RDP through Bastion or restricted rules; avoid public management ports.
  • Deallocate to stop compute billing; delete the whole resource group to avoid orphans.
  • Save with right-sizing, reservations or savings plans, and spot VMs for interruptible work.

Next: App Service and Web Apps.