The time has come to move from theory to practice. In this guided exercise you will follow Laura as she builds, from start to finish, a lab virtual machine in Azure to rehearse everything she will need with the ERP: creating a resource group with tags, a network with a restrictive NSG, the VM, connecting to it securely, adding and preparing a data disk, installing software automatically at start-up, taking a snapshot, deallocating it, verifying everything and, most importantly, deleting everything at the end. So that you can do it at minimal cost, the main path uses a small Linux VM; at the end you will see the Windows version with SQL Server that Laura will use for the real ERP, and the same route summarised in the web portal. By the end you will have applied, with your own hands, the concepts of the whole of module 2.

  1. Goal and architecture of the lab

Laura wants to rehearse the steps of building a VM before creating vm-erp-01. The lab reproduces, on a small scale, the architecture from IaaS Components, with one difference: since the lab has no VPN to the warehouse, the VM will have a public IP, but the NSG will only allow SSH from your IP.

flowchart LR
    TU["Your machine or Cloud Shell<br/>(your public IP)"]
    subgraph RG["rg-hortalia-lab - spaincentral region"]
        subgraph VNET["vnet-hortalia-lab - 10.40.0.0/16"]
            subgraph SNET["snet-lab - 10.40.1.0/24 - NSG nsg-snet-lab"]
                VM["vm-lab-erp<br/>Ubuntu 24.04 LTS, Standard_B1s"]
                D1[("OS disk<br/>Standard SSD")]
                D2[("32 GB data disk<br/>Standard SSD, mounted on /data")]
                VM --- D1
                VM --- D2
            end
        end
        PIP["pip-vm-lab-erp<br/>Standard public IP"]
        SNAP[("snap-vm-lab-erp-datos-01")]
    end
    TU -->|"SSH 22 from your IP only"| PIP --> VM
    D2 -.->|snapshot| SNAP

All the names follow the convention we have used throughout the module: a prefix per resource type, project, and environment. The 10.40.0.0/16 network does not overlap with any of the ones already reserved (10.20.0.0/16 production, 10.21.0.0/16 recovery, 10.30.0.0/16 test).

An important clarification: Hortalia's ERP needs Windows Server, so you will not install the ERP on this Linux VM. The goal of the lab is to practise the mechanics of IaaS (network, NSG, VM, disks, snapshots, life cycle, clean-up), which are identical on Windows. In section 15 you will see the specific differences for Windows.

  1. Prerequisites and cost warning

You need:

  • An Azure subscription. If you do not have one, the free Azure account offers credit for the first few days and a number of monthly hours of certain small VM sizes for 12 months (check the current terms; they include B series sizes such as Standard_B1s). Credits from educational or partner programmes work too.
  • The Azure CLI, in one of these two ways:
    • Azure Cloud Shell (recommended to get started): a terminal in the browser, inside the portal, with the CLI already installed and the session signed in. Choose the Bash environment.
    • The CLI installed on your machine (Windows, macOS, or Linux), with an SSH client (included in current systems).
  • Basic terminal skills: running commands, copying and pasting.

Cost warning. This exercise creates resources that are billed while they exist: a VM, two disks, a public IP, and a snapshot. With the proposed sizes, the cost of doing the whole exercise in an hour or two is of the order of a few cents of a euro (an illustrative figure), and it can be zero if your free account covers the chosen size. But if you forget to delete the resources, they will keep being billed day after day. Step 11 (clean-up) is not optional. If you interrupt the exercise, jump straight to it.

An extra recommendation: before you start, create a budget with an alert in Microsoft Cost Management (for example, €10 a month) so you get an email if something is left running.

  1. Step 0: prepare the session

# Only if you use the CLI on your own machine (in Cloud Shell you are already signed in)
az login

# Check which subscription you are working in
az account show --query "{Subscription:name, Id:id}" --output table

# If you have several, choose the right one
# az account set --subscription "<subscription name or id>"

# Lab variables
RG=rg-hortalia-lab
LOC=spaincentral
VNET=vnet-hortalia-lab
NSG=nsg-snet-lab
VM=vm-lab-erp
SIZE=Standard_B1s
MY_IP=$(curl -s https://ifconfig.me)
echo "Your public IP is: $MY_IP"
  • az login opens the browser so you can sign in with your account.
  • az account show displays the active subscription. Always check it: creating resources in the wrong subscription (the company's production one, for example) is a more frequent mistake than it seems.
  • The variables hold the names we will use in every step. If you close the terminal, they are lost: run this block again before carrying on.
  • MY_IP=$(curl -s https://ifconfig.me) queries a web service that returns the public IP you reach the internet from, and stores it in the variable. If you work in Cloud Shell, you will get Cloud Shell's IP, which is precisely where you will connect from over SSH; bear in mind that it can change if you open a new session.

  1. Step 1: create the resource group with tags

az group create --name $RG --location $LOC \
    --tags proyecto=erp entorno=laboratorio propietario=laura caducidad=2026-10-31
  • The whole lab will live in this resource group, which will let you delete everything at once at the end.
  • The tags identify the project, the environment, and the owner. The caducidad (expiry) tag is a good habit for labs: it says when it should have been removed, and it makes forgotten resources easier to find.

Expected output (abbreviated): a JSON with "provisioningState": "Succeeded".

  1. Step 2: create the network and the NSG

az network vnet create --resource-group $RG --name $VNET \
    --address-prefixes 10.40.0.0/16 \
    --subnet-name snet-lab --subnet-prefixes 10.40.1.0/24

az network nsg create --resource-group $RG --name $NSG

az network nsg rule create --resource-group $RG --nsg-name $NSG \
    --name Permitir-SSH-MiIP --priority 100 \
    --direction Inbound --access Allow --protocol Tcp \
    --source-address-prefixes "$MY_IP/32" --source-port-ranges '*' \
    --destination-address-prefixes '*' --destination-port-ranges 22

az network vnet subnet update --resource-group $RG --vnet-name $VNET \
    --name snet-lab --network-security-group $NSG
  • The first command creates the 10.40.0.0/16 network with the snet-lab subnet (10.40.1.0/24).
  • The NSG has a single inbound rule: SSH (port 22) from your IP only (/32 means exactly one address). Everything else is blocked by the default DenyAllInBound rule.
  • The last command associates the NSG with the subnet. Without it, the rule would protect nothing.

Check it:

az network vnet subnet show --resource-group $RG --vnet-name $VNET --name snet-lab \
    --query "{Subnet:name, Range:addressPrefix, NSG:networkSecurityGroup.id}" --output table

The NSG column must show the identifier of nsg-snet-lab. If it comes up empty, the NSG is not associated.

  1. Step 3: check the size and the quota

Not every size is available in every region or for every subscription. Before creating the VM:

az vm list-skus --location $LOC --size $SIZE --resource-type virtualMachines --output table

az vm list-usage --location $LOC --output table | grep -E "Total Regional vCPUs|BS Family"
  • The first command shows whether Standard_B1s exists in the region. If the Restrictions column shows something like NotAvailableForSubscription, or the list comes up empty, that size is not available to you there.
  • The second shows your total vCPU quota in the region and the one for the B family. You need at least 1 free vCPU.

If the size is not available, you have two options: choose another small size that is (for example, SIZE=Standard_B2s or SIZE=Standard_B2ats_v2) or choose another nearby region (for example, LOC=westeurope or LOC=francecentral). In this second case, delete the group and start again from Step 1, because the network must be in the same region as the VM.

  1. Step 4: create the VM with cloud-init

First, create the cloud-init configuration file that will run on first boot. In Cloud Shell you can use the nano editor or paste this block directly:

cat > cloud-init.yaml <<'EOF'
#cloud-config
package_update: true
package_upgrade: true
timezone: Europe/Madrid
packages:
  - htop
  - jq
  - sysstat
  - fio
write_files:
  - path: /etc/motd
    content: |
      Hortalia lab VM - for testing only, no real data.
runcmd:
  - systemctl enable --now sysstat
  - echo "cloud-init finished $(date)" >> /var/log/hortalia-lab.log
EOF
  • cat > cloud-init.yaml <<'EOF' ... EOF writes into the file everything between the two EOF markers. The quotes in 'EOF' stop bash from interpreting $(date) at that point; we want it to run inside the VM.
  • #cloud-config: a mandatory first line; it tells cloud-init the format of the file.
  • package_update and package_upgrade: refresh the package list and install the available updates (the first round of patching, which in IaaS is your responsibility).
  • timezone: the Madrid time zone.
  • packages: packages to install. htop (process monitor), jq (JSON processing), sysstat (performance statistics, like the Windows Performance Monitor Laura used for sizing), and fio (to measure the disk's IOPS).
  • write_files: creates the welcome message you will see when you connect.
  • runcmd: commands that run at the end of the first boot.

Now, create the VM:

az vm create \
    --resource-group $RG --name $VM --location $LOC \
    --image Canonical:ubuntu-24_04-lts:server:latest \
    --size $SIZE \
    --vnet-name $VNET --subnet snet-lab \
    --nsg "" \
    --public-ip-address pip-$VM --public-ip-sku Standard \
    --admin-username laura --generate-ssh-keys \
    --custom-data cloud-init.yaml \
    --storage-sku StandardSSD_LRS \
    --os-disk-delete-option Delete --nic-delete-option Delete \
    --tags proyecto=erp entorno=laboratorio propietario=laura

An explanation of each parameter:

  • --image Canonical:ubuntu-24_04-lts:server:latest: the image, with its four-part URN (publisher, offer, SKU, version): Ubuntu Server 24.04 LTS, latest published version.
  • --size $SIZE: the size checked in the previous step.
  • --vnet-name and --subnet: connect the VM to the network we created. If you leave them out, az vm create creates a new network on its own, as happened to Laura with vm-prueba-erp in module 1.
  • --nsg "": do not create an extra NSG on the network interface. By default, az vm create would create one with SSH open to any source; we already protect the subnet with ours.
  • --public-ip-address pip-$VM --public-ip-sku Standard: creates a Standard public IP, which is closed except for what the NSG allows.
  • --admin-username laura --generate-ssh-keys: creates the laura user with SSH key authentication (no password). If you do not have a key pair in ~/.ssh/, it generates one; if you already do, it uses the existing public key.
  • --custom-data cloud-init.yaml: passes the cloud-init file to the VM.
  • --storage-sku StandardSSD_LRS: a Standard SSD system disk (enough for a lab).
  • --os-disk-delete-option Delete --nic-delete-option Delete: if the VM is deleted, its system disk and network interface are deleted too, avoiding orphan resources (we saw this in 02-01).

After a minute or two, the CLI returns something like this (fictional data):

{
  "fqdns": "",
  "id": "/subscriptions/0000.../resourceGroups/rg-hortalia-lab/providers/Microsoft.Compute/virtualMachines/vm-lab-erp",
  "location": "spaincentral",
  "powerState": "VM running",
  "privateIpAddress": "10.40.1.4",
  "publicIpAddress": "20.199.61.23",
  "resourceGroup": "rg-hortalia-lab"
}

Note that the private IP is 10.40.1.4: Azure reserves the first four addresses of every subnet (and the last one), so the first available one is .4.

  1. Step 5: connect securely

IP_VM=$(az vm show --resource-group $RG --name $VM --show-details \
    --query publicIps --output tsv)
ssh laura@$IP_VM
  • The first command gets the VM's public IP and stores it in IP_VM.
  • ssh laura@$IP_VM opens the connection. The first time, SSH asks whether you trust the machine's fingerprint: type yes. You should see the welcome message from /etc/motd.

If the connection hangs without responding, the most likely cause is that your IP has changed since you created the rule (common in Cloud Shell and on mobile networks). Update it:

MY_IP=$(curl -s https://ifconfig.me)
az network nsg rule update --resource-group $RG --nsg-name $NSG \
    --name Permitir-SSH-MiIP --source-address-prefixes "$MY_IP/32"

Safer alternatives than exposing SSH, which would be preferable in a real environment:

Option How it works When to use it
Azure Bastion A managed service that gives SSH/RDP access from the browser or the CLI; the VM needs no public IP Production and environments with no VPN; it has an hourly cost
VPN (site-to-site or point-to-site) Your machine joins the private network and you connect to the private IP When the VPN already exists, as at Hortalia
Sign-in with Entra ID (az ssh vm) Authentication with your corporate identity and MFA instead of local keys Organisations that want to centralise identities
Public IP with an NSG limited to your IP What we do in this lab Short-lived labs only

  1. Step 6: add, initialise, and mount a data disk

From another terminal (or after leaving the VM with exit), add a new disk:

az vm disk attach --resource-group $RG --vm-name $VM \
    --name disk-$VM-datos --new --size-gb 32 --sku StandardSSD_LRS --lun 0
  • az vm disk attach: attaches a disk to the VM. With --new, it creates it on the spot.
  • --size-gb 32 --sku StandardSSD_LRS: a 32 GB Standard SSD disk.
  • --lun 0: the disk's logical "slot" on the VM. Pinning it lets you locate it with certainty from inside.
  • The operation happens hot, with the VM running.

Now, inside the VM (connect again with ssh laura@$IP_VM), the disk shows up as an unformatted device. It has to be partitioned, formatted, and mounted:

# 1. List the disks: the new one appears with no partitions and no mount point
lsblk -o NAME,SIZE,TYPE,MOUNTPOINTS

# 2. Locate the disk by its LUN (a link created by the Azure rules)
ls -l /dev/disk/azure/scsi1/

# 3. Create a GPT partition table and a partition taking up the whole disk
sudo parted /dev/disk/azure/scsi1/lun0 --script mklabel gpt mkpart data ext4 0% 100%
sudo partprobe

# 4. Format the partition with the ext4 file system
sudo mkfs.ext4 -L data /dev/disk/azure/scsi1/lun0-part1

# 5. Create the mount point and register the disk in /etc/fstab by its UUID
sudo mkdir -p /data
UUID=$(sudo blkid -s UUID -o value /dev/disk/azure/scsi1/lun0-part1)
echo "UUID=$UUID /data ext4 defaults,nofail 0 2" | sudo tee -a /etc/fstab

# 6. Mount and check
sudo mount -a
df -h /data

Step-by-step explanation:

  1. lsblk lists the block devices. You will see the system disk (with its partitions mounted on /), sometimes a temporary disk, and the new 32 GB disk with no partitions.
  2. In Azure images, system rules create links with stable names per LUN in /dev/disk/azure/scsi1/. Using lun0 instead of /dev/sdc stops you picking the wrong disk, because the sdX letters can change between boots. (On VM sizes with NVMe disks the path is different; in that case identify the disk with lsblk by its size.)
  3. parted ... mklabel gpt creates a GPT partition table; mkpart data ext4 0% 100% creates a partition that takes up the whole disk. --script avoids interactive questions. partprobe asks the system to re-read the partitions.
  4. mkfs.ext4 -L data formats the partition with ext4 and the label data. This command erases anything that was on the partition: make sure you are pointing at the new disk.
  5. /etc/fstab is the file that says what to mount at each boot. The UUID (the file system's unique identifier) is used instead of the device name, for the same reason as before. The nofail option is important in the cloud: if one day the disk is not attached, the VM still boots instead of hanging. tee -a appends the line to the end of the file with administrator permissions.
  6. mount -a mounts everything defined in /etc/fstab; df -h /data should show around 31 GB available on /data.

Optional: measure the disk's IOPS. With fio you can check that the disk performs according to its type, as we saw in 02-02:

sudo fio --name=test-iops --directory=/data --rw=randread --bs=4k \
    --size=512M --iodepth=16 --direct=1 --ioengine=libaio \
    --runtime=30 --time_based --group_reporting | grep -E "IOPS"
  • --rw=randread --bs=4k: random 4 KB reads, the typical pattern of a database.
  • --direct=1: bypassing the operating system cache, to measure the real disk.
  • --runtime=30 --time_based: for 30 seconds.
  • The result should be around the IOPS limit of a small Standard SSD disk, of the order of a few hundred. It is an empirical way to check what the tables say and to understand why the ERP needs a Premium SSD.

  1. Step 7: check the software installed

Still inside the VM:

cloud-init status --wait
cat /var/log/hortalia-lab.log
htop --version && jq --version && fio --version
timedatectl | grep "Time zone"
  • cloud-init status --wait waits for cloud-init to finish and shows status: done. If it shows error, check /var/log/cloud-init-output.log, which holds the output of everything it ran.
  • The line in the /var/log/hortalia-lab.log file confirms that runcmd ran.
  • The three --version calls confirm that the packages are installed.
  • timedatectl must show Europe/Madrid.

Leave the VM with exit.

  1. Step 8: create a snapshot

Before a risky change (such as an ERP update), Laura will always take a snapshot. Practise it with the data disk:

DISK_ID=$(az disk show --resource-group $RG --name disk-$VM-datos --query id --output tsv)

az snapshot create --resource-group $RG --name snap-$VM-datos-01 \
    --source $DISK_ID --incremental true \
    --tags proyecto=erp entorno=laboratorio motivo=antes-de-cambio

az snapshot list --resource-group $RG \
    --query "[].{Name:name, SizeGB:diskSizeGb, Incremental:incremental, State:provisioningState}" \
    --output table
  • az disk show ... --query id gets the disk's full identifier, which is what the snapshot needs as its source.
  • --incremental true: an incremental snapshot, which only stores the blocks changed since the previous one. It is cheaper and it is the recommended option.
  • The motivo (reason) tag documents why it was taken; in three months nobody will remember.
  • az snapshot list must show the snapshot with the state Succeeded.

Remember what we saw in 02-02: this snapshot lives in the same resource group as the disk and is crash consistent. It is useful for rolling back after a change, but it does not replace backups kept somewhere else.

  1. Step 9: deallocate and check the state

az vm deallocate --resource-group $RG --name $VM

az vm get-instance-view --resource-group $RG --name $VM \
    --query "instanceView.statuses[?starts_with(code, 'PowerState/')].displayStatus" \
    --output tsv
  • az vm deallocate stops the VM and releases its CPU and memory: compute stops being billed (the disks, the snapshot, and the Standard public IP are still billed).
  • az vm get-instance-view gets the detailed state. The JMESPath query filters, among the statuses, the one starting with PowerState/ and shows its text. It must say VM deallocated.

To see the difference with the Stopped state we saw in 02-01, you can start it (az vm start), stop it with az vm stop, and query again: you will see VM stopped and a CLI warning reminding you that billing continues. If you do, finish with az vm deallocate.

  1. Step 10: final verification

Before deleting, go over everything you have created:

az resource list --resource-group $RG \
    --query "[].{Name:name, Type:type}" --output table

az vm show --resource-group $RG --name $VM \
    --query "{VM:name, Size:hardwareProfile.vmSize, OS:storageProfile.osDisk.osType, DataDisks:length(storageProfile.dataDisks), Tags:tags}" \
    --output json

Expected output of the first command (the order may vary):

Name                       Type
-------------------------  ---------------------------------------
vnet-hortalia-lab          Microsoft.Network/virtualNetworks
nsg-snet-lab               Microsoft.Network/networkSecurityGroups
pip-vm-lab-erp             Microsoft.Network/publicIPAddresses
vm-lab-erpVMNic            Microsoft.Network/networkInterfaces
vm-lab-erp                 Microsoft.Compute/virtualMachines
vm-lab-erp_OsDisk_1_...    Microsoft.Compute/disks
disk-vm-lab-erp-datos      Microsoft.Compute/disks
snap-vm-lab-erp-datos-01   Microsoft.Compute/snapshots

Note that a "VM" is really eight resources, exactly as we anticipated in Definition and Characteristics of IaaS. Note too that the network interface and the system disk have automatically generated names; with Terraform (02-05) you would control those names as well.

The second command summarises the VM: size, operating system, number of data disks (1), and tags.

  1. Step 11: clean-up

az group delete --name $RG --yes --no-wait

# A few minutes later, check that it no longer exists
az group exists --name $RG
  • az group delete deletes the group and every resource it contains: VM, disks, snapshot, IP, network, and NSG. --yes skips the confirmation and --no-wait returns control without waiting (the deletion takes a few minutes).
  • az group exists returns false once the deletion has finished.

Two final checks worth doing:

  • In the portal, review All resources in case you created something outside the group (for example, in a failed attempt in another region).
  • You may see a group called NetworkWatcherRG: Azure creates it automatically when you create networks in a region, for its network diagnostics service. It does not generate a cost in itself.
  • If you generated SSH keys with --generate-ssh-keys, they are still in ~/.ssh/ on your machine or in Cloud Shell; you can keep them for future labs.

  1. The Windows version for the real ERP

For vm-erp-01, Laura follows the same steps, with these differences. She builds on the network, the NSG, and the VPN she created in rg-hortalia-erp in 02-02:

az vm create \
    --resource-group rg-hortalia-erp --name vm-erp-01 \
    --location spaincentral --zone 1 \
    --image MicrosoftSQLServer:sql2022-ws2022:standard-gen2:latest \
    --size Standard_D4s_v5 \
    --vnet-name vnet-hortalia-spaincentral --subnet snet-erp \
    --private-ip-address 10.20.1.10 \
    --public-ip-address "" --nsg "" \
    --admin-username laura --admin-password "$ADMIN_PWD" \
    --storage-sku Premium_LRS \
    --data-disk-sizes-gb 256 --data-disk-caching ReadOnly \
    --os-disk-delete-option Delete --nic-delete-option Delete \
    --tags proyecto=erp entorno=prototipo propietario=laura

Differences from the lab:

  • --zone 1: the VM is pinned to zone 1 of the region, as decided in 02-02.
  • --image MicrosoftSQLServer:sql2022-ws2022:standard-gen2:latest: Windows Server 2022 with SQL Server 2022 Standard and the license included in the hourly price (not the Developer edition: this is the real ERP).
  • --private-ip-address 10.20.1.10: the fixed IP that erp.hortalia.internal points to.
  • --public-ip-address "": no public IP. The ERP is not exposed to the internet; it is reached over the warehouse VPN or through Azure Bastion. Remember that, with no public IP, the VM needs the NAT Gateway from 02-02 to download updates.
  • --admin-password "$ADMIN_PWD": Windows uses a username and password. The password is stored in a variable, read from a secrets manager, never written in the command.
  • --storage-sku Premium_LRS and --data-disk-sizes-gb 256: a Premium SSD system disk and a 256 GB data disk (P15) for SQL Server, with read-only caching.

The data disk is initialised with PowerShell. Since the VM has no public IP, Laura does it without connecting, with Azure's remote run command:

az vm run-command invoke \
    --resource-group rg-hortalia-erp --name vm-erp-01 \
    --command-id RunPowerShellScript \
    --scripts "Get-Disk | Where-Object PartitionStyle -eq 'RAW' | Initialize-Disk -PartitionStyle GPT -PassThru | New-Partition -DriveLetter F -UseMaximumSize | Format-Volume -FileSystem NTFS -NewFileSystemLabel 'SQLData' -AllocationUnitSize 65536 -Confirm:\$false"
  • az vm run-command invoke --command-id RunPowerShellScript runs a PowerShell script inside the VM through the Azure agent, with no need for direct network access.
  • The script is the same one we saw in the Terraform extension in 02-05: it initialises the disk as GPT, creates the F: drive, and formats it as NTFS with 64 KB blocks, the recommendation for SQL Server. The backslash in \$false stops bash from interpreting $false as a variable.

To connect over RDP, Laura has two routes: from the warehouse, over the VPN, against erp.hortalia.internal; or from anywhere through Azure Bastion, from the portal (the Connect > Bastion button) or with the CLI (az network bastion rdp, which needs the bastion extension and the Standard SKU or above). The snapshot, the deallocation, and the verification are identical to the lab. What she will not do with vm-erp-01 is Step 11: that VM is the prototype module 5 will evaluate. For it, what you learned in 02-04 about backups, schedules, and disaster recovery applies.

Cost: a D4s_v5 VM with Windows and SQL Server Standard with the license included, its premium disk and, if used, Azure Bastion, cost of the order of several hundred euros a month running 24/7 (an illustrative figure). If you create it to practise, delete it as soon as you finish.

  1. The same route from the portal

Everything above can be done from the Azure web portal. A summary of the Create a virtual machine wizard:

Wizard tab What to configure (the equivalent of the CLI steps)
Basics Subscription; resource group (rg-hortalia-lab); name (vm-lab-erp); region; availability options (no redundancy in the lab, zone 1 for the ERP); image (Ubuntu Server 24.04 LTS or SQL Server 2022 on Windows Server 2022); size; authentication type (SSH key or password); public inbound ports: None (the rules are handled by our NSG)
Disks OS disk type (Standard SSD or Premium SSD); Create and attach a new disk for the data disk; the option to delete the disk with the VM
Networking Existing virtual network and subnet; public IP (new in the lab, None for the ERP); NIC network security group: None; tick Delete public IP and NIC when VM is deleted
Management Auto-shutdown (useful in labs); in production, patching options
Advanced Custom data: paste the contents of cloud-init.yaml
Tags proyecto, entorno, propietario, caducidad
Review + create Review the summary and the estimated hourly price; the Download a template for automation option

That last link is revealing: the portal generates an ARM template with everything you have just configured. Every click in the portal is, underneath, an API call (01-02), and it can be turned into code (02-05). The snapshot is created from the disk (Create snapshot), the deallocation with the VM's Stop button, and the clean-up with Delete resource group, typing its name to confirm.

Common Mistakes and Tips

  • Exceeding the quota (QuotaExceeded or OperationNotAllowed). Check az vm list-usage first; free up vCPUs by deallocating other VMs or request an increase.
  • A size not available in the region (SkuNotAvailable). Check az vm list-skus, choose another small size or another region, and remember that the network must be in the same region as the VM.
  • Opening SSH or RDP to 0.0.0.0/0 or to *. Within minutes the automated access attempts will start. Limit the source to your IP, use Bastion or a VPN. And beware: az vm create without --nsg "" creates an NSG that opens SSH (or RDP on Windows) to any source.
  • Forgetting to state the network in az vm create. A new VNet will be created with default values, outside your design.
  • The SSH connection hangs. Your IP changed: update the NSG rule. If SSH responds but rejects the key, check that you are using the same machine (or Cloud Shell) where the key was generated.
  • Formatting the wrong disk. Identify it by LUN (/dev/disk/azure/scsi1/lun0) or by size; never by the sdX letter blindly.
  • Forgetting nofail in /etc/fstab. If the disk is missing, the VM may fail to boot and you will have to repair it with the serial console.
  • Shutting down from inside the OS and believing you are not billed. The state will be Stopped, not Deallocated.
  • Forgetting to delete. The most expensive mistake in the exercise. One resource group per lab, an expiry tag, auto-shutdown, and a budget with an alert.
  • Tip: save every command you have used in a lab.sh file. It is the first step towards Infrastructure as Code and it will let you repeat the exercise in minutes.

Exercises

Exercise 1: resize the VM. Repeat the lab up to Step 7 and resize vm-lab-erp from Standard_B1s to Standard_B2s (or the nearest available size). Check first that the size is compatible, verify the change, and explain what happens to the VM during the operation.

Exercise 2: automate with Terraform. Adapt the code from Automating IaaS: Infrastructure as Code to create this lab (network, NSG with SSH from your IP, public IP, interface, and a Linux VM with cloud-init). Say which resources change compared with the Windows version.

Exercise 3: restore from the snapshot. After Step 8, simulate a disaster: delete (inside the VM) a file you created in /data. Recover the file by creating a new disk from the snapshot and mounting it in another folder.

Solutions

Solution 1.

az vm list-vm-resize-options --resource-group $RG --name $VM \
    --query "[?name=='Standard_B2s']" --output table

az vm resize --resource-group $RG --name $VM --size Standard_B2s

az vm show --resource-group $RG --name $VM \
    --query hardwareProfile.vmSize --output tsv

The first command checks that Standard_B2s is among the sizes compatible with the current hardware (if the list comes up empty, deallocate the VM and query again: a deallocated VM can be moved to another type of host). The second resizes it: the VM restarts, so there will be a few minutes of downtime (on the ERP, this has to be done in an agreed window). The third must return Standard_B2s. Inside the VM, nproc will show 2 CPUs and free -h around 4 GB of memory. Remember to check the quota: you go from 1 to 2 vCPUs.

Common mistake: trying to resize to a size that does not support the disk type or the image generation. Always check list-vm-resize-options first.

Solution 2 (main fragments). The resource group, the network, the subnet, the NSG (with the SSH rule from var.my_ip instead of RDP/SQL from the warehouse), and the association stay the same. These resources change or are added:

resource "azurerm_public_ip" "lab" {
  name                = "pip-vm-lab-erp"
  location            = azurerm_resource_group.lab.location
  resource_group_name = azurerm_resource_group.lab.name
  allocation_method   = "Static"
  sku                 = "Standard"
  tags                = local.tags
}

resource "azurerm_network_interface" "lab" {
  name                = "nic-vm-lab-erp"
  location            = azurerm_resource_group.lab.location
  resource_group_name = azurerm_resource_group.lab.name

  ip_configuration {
    name                          = "internal"
    subnet_id                     = azurerm_subnet.lab.id
    private_ip_address_allocation = "Dynamic"
    public_ip_address_id          = azurerm_public_ip.lab.id
  }
}

resource "azurerm_linux_virtual_machine" "lab" {
  name                  = "vm-lab-erp"
  location              = azurerm_resource_group.lab.location
  resource_group_name   = azurerm_resource_group.lab.name
  size                  = "Standard_B1s"
  admin_username        = "laura"
  network_interface_ids = [azurerm_network_interface.lab.id]
  custom_data           = base64encode(file("${path.module}/cloud-init.yaml"))
  tags                  = local.tags

  admin_ssh_key {
    username   = "laura"
    public_key = file("~/.ssh/id_rsa.pub")
  }

  os_disk {
    caching              = "ReadWrite"
    storage_account_type = "StandardSSD_LRS"
  }

  source_image_reference {
    publisher = "Canonical"
    offer     = "ubuntu-24_04-lts"
    sku       = "server"
    version   = "latest"
  }
}

Key differences: azurerm_linux_virtual_machine instead of the Windows version; authentication with admin_ssh_key (the public key, never the private one) instead of a password; custom_data with the cloud-init encoded in Base64 (base64encode(file(...))); an azurerm_public_ip resource associated with the interface through public_ip_address_id; and the Ubuntu image. If you generated the key with --generate-ssh-keys, its path is ~/.ssh/id_rsa.pub (adjust it if you use another key type). The data disk and its attachment would be identical to those in 02-05. When you finish: terraform destroy.

Solution 3.

# Create a new disk from the snapshot
az disk create --resource-group $RG --name disk-$VM-restaurado \
    --source snap-$VM-datos-01 --sku StandardSSD_LRS

# Attach it to the VM in another slot
az vm disk attach --resource-group $RG --vm-name $VM \
    --name disk-$VM-restaurado --lun 1

Inside the VM:

sudo mkdir -p /restored
sudo mount -o ro /dev/disk/azure/scsi1/lun1-part1 /restored
ls -l /restored
sudo cp /restored/<file> /data/

The restored disk contains the partition exactly as it was when the snapshot was taken, so it must not be formatted (doing so would erase precisely what you want to recover). It is mounted read-only (-o ro) so as not to alter it, the file is copied and, afterwards, it is unmounted (sudo umount /restored), detached (az vm disk detach --resource-group $RG --vm-name $VM --name disk-$VM-restaurado), and the restored disk is deleted. This is, on a small scale, the restore test Laura committed to doing every quarter: a backup that has never been restored is not a reliable backup.

Common mistake: mounting the restored disk with an entry in /etc/fstab by UUID: since it is a clone, it has the same UUID as the original and the system could mount the wrong disk. Mount it by hand, by its LUN path.

Conclusion

In this exercise you have gone through the complete life cycle of a virtual machine in IaaS: you have prepared the session and checked the subscription, created a tagged resource group, a network with an NSG that only admits your IP, verified size and quota, created the VM with cloud-init, connected securely, added, formatted, and mounted a data disk, created a snapshot, deallocated the VM, verified all its resources, and deleted the lab. You have also seen the Windows with SQL Server version that Laura will use for vm-erp-01 and the same route in the portal.

With this exercise we close module 2. You have learned what IaaS is and what its characteristics are, its compute, storage, and networking pieces, the providers that offer it, its use cases, and how to automate it with code. Laura now has a solid prototype for getting the ERP out of the warehouse cabinet: a Windows VM with no public IP in spaincentral, protected by the VPN and a restrictive NSG, with immutable backups, a test environment that only runs during office hours, and a recovery plan in another region. But she has also seen how much work is still hers: patches, disks, networks, backups, schedules. That work makes sense for a legacy ERP that cannot be touched; for a new application, written by the company itself, perhaps not. Now it is Marc's turn, who wants to spend his time writing the hortalia-shop store and not patching servers, and who needs it to take the jump from 300 to 6,000 visits per hour at Christmas without breaking a sweat. In module 3 we will move one step up the stack to study Platform as a Service, starting with Definition and Characteristics of PaaS.

© Copyright 2026. All rights reserved