Linux Hour 3: Towards the cloud platform (Azure)

Moving the Linux skills learned on local VMs in Lessons 1–2 to Azure: images and specifications, cloud-init first boot, managed disks, Entra ID login, monitoring, patching, troubleshooting and costs
Ubuntu 26.04 LTS (primary) / 24.04 LTSAzure CLI 2.8xcloud-init · AADSSHLoginForLinux · AMAVerified by learn.microsoft.com · 2026-11-17
Overall learning objectives
  • Be able to read and select Azure Linux image URN (Publisher:Offer:Sku:Version) and VM specification name (such as The meaning of each letter in Standard_D2ads_v5), know the differences and applicable scenarios of Ubuntu LTS, Azure Linux, and RHEL images.
  • Describe the complete link for first boot of a Linux VM on Azure: UEFI firmware → shim/GRUB → kernel and initramfs → systemd → cloud-init five stages (get configuration from IMDS and provisioning ISO) → report readiness to the platform → walinuxagent processing extension → can log in; and use cloud-init to connect myapp with redis-server is automatically deployed as a systemd service.
  • Distinguish between OS disks, data disks (managed disks) and temporary disks, securely mount data disks (UUID + nofail), know which operations will lose temporary disk data, and the v6 specification NVMe temporary disk "bare disk, need to be formatted by yourself" changes.
  • Use Microsoft Entra ID to log in to Linux VM (AADSSHLoginForLinux extension + az ssh vm + VM login role), understand how the token of the managed identity reaches the process in the VM via IMDS; master the choice of SSH keys, Azure Bastion, and JIT.
  • Use Azure Monitor Agent + Data Collection Rules (DCR) to collect syslog and performance counters; use Azure Update Manager to evaluate and install patches.
  • When SSH cannot be accessed, skillfully use boot diagnosis, serial console, Run Command to deal with common faults such as fstab missing nofail, disk fullness, sshd configuration error, NSG interception, etc.; finally estimate the cost and thoroughly clean up rg-linux-lab.

1-hour time allocation table

#TimeModuleCore contentAnimation/InteractionLab (Azure, rg-linux-lab / canadacentral)
0Pre-classWarm-up and Azure preparationAzure CLI Login, subscriptions and quotas, resource groups, SSH keys, connection to Lesson 2Environment self-checkCreate rg-linux-lab
100–05Image, VM Specifications and selectionURN and aliases, Ubuntu / Azure Linux / RHEL, Gen1/Gen2, Trusted Launch, specification naming, quotaURN constructor + specification name decoderQuery image and specifications
205–13cloud-init and VM extensionProvisioning agent, customData vs userData, cloud-init five phases, walinuxagent and extension, Custom ScriptCore animation: Linux VM first startup processcloud-init deployment myapp + redis-server
313–21Managed disk, temporary disk and file systemOS/data/temp disk, disk type, LUN and /dev/disk/azure, parted/mkfs/fstab, online expansion, NVMeTemporary disk life cycle + fstab emulatorMount data disk to Redis Persistence
421–29Identity and AccessEntra ID login, VM login role, az ssh vm, managed identities and IMDS tokens, SSH keys, Bastion, JITCore Animation: How the managed identity token reaches the VM via IMDSEntra login + get token inside VM
529–37Azure Monitor Agent and DCRAMA architecture, DCR/DCRA, syslog facilities and levels, performance counters, KQL, costA syslog journeyCollecting myapp logs and CPU/memory
637–45Azure Update ManagerPeriodic evaluation, on-demand installation, maintenance configuration, patch orchestration mode, restart settings, relationship with unattended-upgradesPatch window timelineEvaluate and install security patches
745–54Cloud troubleshootingBoot diagnostics, serial console, Run Command, ALAR, fstab / disk full / sshd / NSG"Which channel can still be used" fault simulatorDeliberately destroy fstab and save it
854–60Cost, cleanup and self-testBilling structure, stop vs deallocate, automatic shutdown, label, budget, delete resource groupCost estimator + troubleshooting decision treeComplete cleanup
—After classCheatsheet · Comprehensive labDelivery of a "production-ready" myapp VM from scratchFinal exam (12 Question)Comprehensive experiment

Knowledge Coverage Matrix

Target skillsM1M2M3M4M5M6M7M8Key commandsExperiment
Select image and specifications✓·✓····✓az vm image list, az vm list-skusM1
First boot automation (cloud-init)·✓✓···✓·--custom-data, cloud-init statusMyapp automatic deployment
VM extension and VM agent·✓·✓✓✓✓·az vm extension list/setM2/M4/M5
Disk and file system··✓···✓✓az vm disk attach, parted, blkidRedis data disk
Identity and access (Entra / MI / Bastion / JIT)···✓✓·✓·az ssh vm, az role assignmentEntra login
Logs and Metrics····✓·✓✓az monitor data-collection rule, KQLSyslog table
Patch management·····✓··az vm assess-patches, install-patchesM6
Troubleshooting without SSH·✓✓✓··✓✓Serial console, az vm run-command invoke, az vm repairfstab rescue
Cost and cleanup✓·✓✓✓··✓az vm deallocate, az group deleteM8

What this lesson does not cover (and where to learn)

TopicsWhy not in this lessonWhere to learn
Linux basic commands, permissions, processes, systemd unit writing, LVM, network troubleshootingThis lesson is assumed to be mastered by you and will only be reused on the cloudLesson 1 · Lesson 2
Similar topics on AWS (AMI, user data, IMDSv2, SSM)Different platforms provide better comparative learning effectsLesson 4: Going to the cloud platform (AWS)
Batch creation and configuration of VMs with Terraform / AnsibleInfrastructure as code and configuration managementTerraform class · Ansible class
Prometheus / Grafana monitoring myappThis lesson only uses Azure native AMA + Log AnalyticsPrometheus & Grafana lesson
VM Scale Sets (VMSS), Load Balancing, Availability Zone High Availability ArchitectureBelongs to the architecture topic and exceeds 1 hourVMSS Official documentation
Containerized deployment of myapp (Docker/AKS)This lesson adheres to the "native systemd service" routeDocker lesson · AKS course

How to use this courseware

10 pages for each module
Principle · Diagram · Animation · Command · Experiment · Production case · Troubleshooting · Quizzes · Voice · Video. It is recommended to read the "Principle" and "Animation" first, and then do the "Experiment" on Azure.
Learning Progress
Test score ≥ 70% or click "Mark this module completed" will be counted into the progress and saved in this browser (it will be cleared after refreshing when local storage is disabled).
Chinese Voice
The "Voice" tab uses the browser's built-in Web Speech API (en-US) to read the transcript; when there is no Chinese voice package, the transcript can still be read or handed over to the TTS tool.
Release NotesThis lesson focuses on Ubuntu Server 26.04 LTS (Azure Marketplace image Canonical:ubuntu-26_04-lts:server:latest, kernel 7.0, released in 2026-04), and is related to chapters 1–2 The local lab VM used in this course is consistent; the differences between Ubuntu 24.04 LTS (Canonical:ubuntu-24_04-lts:server:latest) are noted in the relevant positions. All Azure facts verified on 2026-11-17 against learn.microsoft.com. All commands in this lesson require a real Azure subscription to run, and the "expected outputs" are examples (see the known limitations of the source page for details).
Cost and Security TipsThis lesson creates resources that are billed by the hour (VM, Managed Disk, Public IP, Log Analytics workspace, optional Bastion). The entire experiment lasts about 1–2 hours, and the cost is usually less than US$1 when 2 vCPUs are selected for VM specifications (based on the Price Calculator);Bastion Standard Edition is billed by the hour and is significantly higher than the experimental VM itself, delete it immediately after completion. Be sure to perform Module 8 az group delete -n rg-linux-lab at the end of the course. Required permissions: Contributor (Create Resource) + permission to assign a role (Role Based Access Control Administrator or Owner for the Entra login role) on the subscription or resource group.

Module 0 · Warm-up and Azure preparation (completed before class)

Log in to Azure, confirm subscription and quota, prepare SSH key and resource group, and "package" the myapp deployment method of Lesson 2 into a form that can be handed over to the cloud
Before class ≈ 10 minutesrg-linux-lab · canadacentral
Prerequisite
  • Completed Lesson 1 and Lesson 2: know how to use it apt, systemctl, journalctl, understand the native deployment of myapp - system user myapp, installation directory /opt/myapp (code /opt/myapp/app/, virtual environment /opt/myapp/venv, unit WorkingDirectory=/opt/myapp/app), configuration /etc/myapp/myapp.env, systemd unit myapp.service, port 5000, health check /healthz, Redis uses the release version of redis-server.
  • An Azure subscription (free trial or pay-as-you-go) that creates resources. Install Azure CLI on this machine (or local lab VM linuxlab); you can also use Azure Cloud Shell (pre-installed CLI and ssh extension).
  • This lesson uses the following uniformly: resource group rg-linux-lab, region canadacentral, VM name vm-linux-lab, administrator labadmin, and working directory ~/linuxlab.

Step 1: Log in and confirm subscription

az version --query '"azure-cli"' -o tsv
az login                         # Browser interactive login; use az login --use-device-code if there is no browser
az account show --query "{name:name, id:id, user:user.name}" -o table
# Explicit selection for multiple subscriptions:
# az account set --subscription ""
2.87.0
Name               Id                                    User
-----------------  ------------------------------------  ----------------------
Pay-As-You-Go Lab  00000000-0000-0000-0000-000000000000  labuser@contoso.com

Step 2: Set unified variables, check quotas, create resource groups

mkdir -p ~/linuxlab/azure && cd ~/linuxlab/azure
cat > env.sh <<'EOF'
export RG=rg-linux-lab
export LOC=canadacentral
export VM=vm-linux-lab
export ADMIN=labadmin
export IMAGE=Canonical:ubuntu-26_04-lts:server:latest
export SIZE=Standard_D2ads_v5
EOF
source env.sh

# vCPU quota for DSv5/Dadsv5 series in this region (Limit - CurrentValue must be ≥ 2)
az vm list-usage -l $LOC -o table | grep -Ei "Total Regional|DADSv5"

az group create -n $RG -l $LOC --tags course=linux-8h part=3 owner=$(whoami)
Name                                     CurrentValue    Limit
---------------------------------------  --------------  -------
Total Regional vCPUs                     0               10
Standard DADSv5 Family vCPUs             0               10
{
  "location": "canadacentral",
  "name": "rg-linux-lab",
  "properties": { "provisioningState": "Succeeded" },
  "tags": { "course": "linux-8h", "owner": "labuser", "part": "3" }
}
Why choose Standard_D2ads_v52 vCPU / 8 GiB, with one block 75 GiB SCSI local temporary disk (verified) to facilitate module 3 to explain the classic /mnt temporary disk behavior; if your subscription does not have Dadsv5 quota in this region, it can be replaced Standard_D2s_v5 (no temporary disk) or v6 specifications (NVMe temporary disk, need to be formatted by yourself, see module 3).

Step 3: Prepare SSH keys

ls ~/.ssh/id_ed25519.pub 2>/dev/null || ssh-keygen -t ed25519 -C "labadmin@linux-lab" -f ~/.ssh/id_ed25519 -N ""
cat ~/.ssh/id_ed25519.pub

Azure Linux VM supports RSA and Ed25519 public keys. This lesson uses --ssh-key-values ​​~/.ssh/id_ed25519.pub to explicitly pass it in to avoid --generate-ssh-keys from accidentally generating/reusing keys you don’t know. Module 4 will further switch to using Entra ID to log in, and then daily login will no longer rely on this key.

Connection with the previous lesson: Turn "manual deployment" into "declarative first startup configuration"

Lesson 2 manual work on linuxlabWho will do this lessonModule
apt install redis-server python3-venvcloud-init packages:2
useradd --system myappcloud-init users:2
Write /opt/myapp/app/app.py, /etc/myapp/myapp.env, myapp.servicecloud-init write_files:(defer: true)2
systemctl enable --now myappcloud-init runcmd:2
LVM/extra disk mountManaged data disk + UUID + nofail3
journalctl -u myappSame as above, plus AMA sends syslog to Log Analytics5
apt upgrade / unattended-upgradesAzure Update Manager6
Local console (Multipass / Hyper-V window)Serial console + startup diagnostics7

Warm-up: answer from memory (30 seconds)

What is the difference between After=redis-server.service and Wants=redis-server.service in the systemd unit?

After= only stipulates the startup sequence and will not pull up redis; Wants= means "start it by the way when I start it" (weak dependency). The two are usually written together. myapp.service written by cloud-init in this lesson is written like this.

/etc/fstab What happens if I write it wrong?

systemd generates .mount units for each line at startup; when the data disk does not exist and there is no nofail, the local-fs.target dependency fails and the system enters emergency mode. On the local VM you can see the console; on the cloud - you can't SSH in, which is what Module 7 is about to solve.

Who configured the IP, host name, and user of the local lab VM?

Multipass is also injected via cloud-init (NoCloud data source). The same cloud-init on Azure is replaced with Azure Data Source, fetching configuration from IMDS and provisioning ISO - Core Animation of Module 2.

Environment self-check list

Module 1 · Linux on Azure: Images, VM specifications and selection

00:00 – 05:00 · “Which distribution to use, which version, and what machine to run on” – these three decisions correspond to URN, Generation and Selection respectively on Azure Size
5 minutesUbuntu 26.04 LTS is availableAzure Linux 4.0 Preview★★★★☆
Learning Objectives
  • Understand the image URN Publisher:Offer:Sku:Version, will use az vm image list / list-skus / show to find the image and determine whether you need to accept the Marketplace terms.
  • Compare the package management, support and cost differences between Ubuntu LTS, Azure Linux, and RHEL images to make a choice for myapp.
  • Decode the specification name (such as Standard_D2ads_v5) and know the constraints of Gen1/Gen2, Trusted Launch, x64/Arm64 on image selection.
Prerequisite knowledge:Distribution and kernel concepts in Lesson 1. Importance:★★★★☆ (Selecting the wrong image/specification is the most common reason for "creation failure")

What: Image (Image) and URN

Azure Marketplace Each image in is identified by four segments, together called URN: Publisher:Offer:Sku:Version. For example Canonical:ubuntu-26_04-lts:server:latest. Version Write latest to get the latest released image version (Canonical will regularly release new patched images). Azure CLI also has built-in Alias (UrnAlias) for commonly used images, such as Ubuntu2204, Ubuntu2404, AzureLinux4 - the alias list changes with the CLI version, and it is recommended to write the complete URN in scripts and IaC.

SegmentMeaningUbuntu 26.04 Example
PublisherPublisherCanonical
OfferA set of related imagesubuntu-26_04-lts (unified offer, including Server and Minimal; Pro version is ubuntu-pro-26_04-lts)
SkuSpecific variant (Gen2/Gen1/Arm64/CVM/Minimal)server (x64 Gen2, default), server-gen1, server-arm64, minimal-arm64, server-cvm
VersionImage versionlatest or specific date version number

Why: How to choose three common types of Linux images

Ubuntu Server LTSAzure LinuxRHEL (and Rocky/Alma comparison)
Example URNCanonical:ubuntu-26_04-lts:server:latest
Canonical:ubuntu-24_04-lts:server:latest
microsoftazurelinux:azurelinux-4:4:latest (4.0, Preview)
3.0 is the GA version (URN is queried with az vm image list --publisher MicrosoftCBLMariner --all)
RedHat:RHEL:9-lvm-gen2:latest (Example; use list-skus to query 10.x SKUs)
Package managementapt(deb822 .sources)dnf / tdnf(RPM)dnf(RPM), SELinux enforcing
Image feesNon-Pro images are freeFreeRHEL images with subscription fee (PAYG) or BYOS
SuitableUniversal, consistent with the local lab VM (preferred for this course)Microsoft's own streamlined RPM distribution: AKS node, container host, pursuing small attack surfaceEnterprise compliance, requires Red Hat support
cloud-initYesYesYes (RHEL 7.7+/8.1+ with cloud-init provisioning)

Microsoft Learn's Endorsed Releases list (verified 2026-11) includes Ubuntu 22.04/24.04/26.04 LTS (incl. Pro), RHEL, SLES, Debian, Oracle Linux, AlmaLinux, Rocky, Flatcar, etc. Azure Linux 4.0 will enter public preview in mid-2026, and the official clarification is that it is "for evaluation only and not recommended for production"; this lesson will not use it as the main line.

How: VM specification (Size) naming

Specification name format: [Series][Subseries][Number of vCPUs][Limited vCPU][Additional Features][Accelerator][Version]. Take Standard_D2ads_v5 as an example: D General Purpose · 2 vCPUs · a AMD processor · d with local scratch disk · s supports advanced SSDs · v5 5th generation. Common additional feature letters: a AMD, p Arm (Ampere/Cobalt), d local temporary disk, s advanced storage, l low memory ratio, m memory intensive, i isolation, b block storage performance enhancements.

SeriesPositioningLinux Typical Usage
B (burstable)Low baseline CPU + points burstDevelopment testing, low-load spring machine (note that the speed will be limited after the points are exhausted)
D (general)CPU: memory ≈ 1:4Web/API (myapp), small and medium-sized database
E (memory optimization)≈ 1:8Redis, Elasticsearch, large cache
F (computing optimization)≈ 1:2Batch processing, compilation
L (storage optimization)High-capacity local NVMeCassandra, log index
N(GPU)AcceleratorAI inference/training

When: Generation, Trusted Launch and architectural constraints

  • Gen2 = UEFI startup (the first startup animation of module 2 takes Gen2 as an example); Gen1 = BIOS startup. The new image defaults to Gen2; some old specifications only support Gen1. In this case, select a SKU such as server-gen1.
  • Trusted Launch (Secure Boot + vTPM) is enabled by default when creating a new VM on Azure and requires a Gen2 image; third-party kernel modules need to be signed, otherwise they will be refused to load by Secure Boot.
  • Arm64 images (such as server-arm64) must be equipped with Arm specifications (named with p, such as Standard_D2ps_v5), and vice versa - this is the source of errors such as "The selected VM size is not supported by the image".
  • v6 and newer specifications disks and temporary disks use the NVMe interface. The image requires NVMe drivers and udev rules (the new Ubuntu image already has them), and the device name changes from /dev/sdX to /dev/nvmeXnY (module 3).

Comparison with similar technologies

AzureAWS (Lesson 4)On-prem Multipass (Lesson 1)
Image IdentificationURN / Alias / Compute Library Image IDAMI ID (unique within region)Alias (such as 26.04)
SpecificationsStandard_D2ads_v5t3.medium / m7g.large--cpus --memory
First startup configurationcustomData / userData → cloud-inituser data → cloud-init--cloud-init → cloud-init
Common misconception① “latest is the latest Ubuntu version" - no, it is justthe latest image version of that SKU, 26.04 latest will always be 26.04. ② "Ubuntu Pro images are as free as regular images" - Pro images come with additional billing. ③ "Aliases are always available" - old aliases (such as UbuntuLTS) have been removed and scripts will suddenly fail. ④ "Newer specifications are cheaper" - Not necessarily, check by regional price list.

Architecture diagram: from URN to a running VM

Marketplace image Canonical : ubuntu-26_04-lts: server : latestGen2 · x64 · cloud-init ready Copy Managed OS disk Default is about 30 GiBPremium / Standard SSDOnline expansion available (module 3) VM: Standard_D2ads_v5 2 vCPU · 8 GiB · 75 GiB SCSI temporary disk UEFI + Secure Boot + vTPM(Trusted Launch) NIC → VNet/Subnet → NSG → Public IP System assigned managed identity (module 4) Constraint check (on creation) Image schema = Spec schema? Does the region have quotas (images with plan)? data-xlt-id="T18">Common failures Common failures SkuNotAvailable · QuotaExceeded image/size incompatibility · MarketplacePurchaseEligibilityFailed
Figure 1-1 URN determines "what system to install", Size determines "what hardware to run on", the two must match in architecture, Generation and region

Specification name disassembly

Standard_ D 2 a d s _v5 LevelGeneral purpose2 vCPUAMDTemporary diskAdvanced SSDNo. 5 Generation Comparison: Standard_D2s_v5Intel · No temporary disk Comparison: Standard_D2ads_v6NVMe Temporary disk (bare disk, needs to be formatted)
Figure 1-2 Each letter of the specification name is meaningful; only with d there is a local temporary disk

Interaction: URN constructor + specification compatibility check

Select the release version, architecture and specifications, and az will be generated below vm create's --image and --size parameters, and simulates the compatibility check done by Azure Resource Manager before creation.

Release
Architecture / Generation
Specifications
Click the button after selecting the combination
$ az vm create ...

Common commands

# 1) List Canonical's Ubuntu 26.04 images (--all will query the complete directory online, which is slower)
az vm image list -p Canonical -f ubuntu-26_04-lts -l canadacentral --all -o table
# 2) View only SKU
az vm image list-skus -l canadacentral -p Canonical -f ubuntu-26_04-lts -o table
# 3) View the details of an image version (whether there is a plan, Generation, architecture)
az vm image show --urn Canonical:ubuntu-26_04-lts:server:latest -l canadacentral \
  --query "{gen:hyperVGeneration, arch:architecture, plan:plan, features:features[].name}"
# 4) Built-in alias table (changes with CLI version)
az vm image list -o table
# 5) RHEL / Azure Linux
az vm image list-skus -l canadacentral -p RedHat -f RHEL -o table
az vm image list -p microsoftazurelinux --all -l canadacentral -o table
# 6) Available specifications and restrictions in a certain region (Restrictions is not empty = your subscription cannot be used)
az vm list-skus -l canadacentral --resource-type virtualMachines --size Standard_D2a -o table
az vm list-sizes -l canadacentral --query "[?name=='Standard_D2ads_v5']" -o table
# 7) Third-party images with plan accept the terms first
az vm image terms show   --urn <publisher>:<offer>:<sku>:latest
az vm image terms accept --urn <publisher>:<offer>:<sku>:latest
Offer             Publisher    Sku            Urn                                              Version
----------------  -----------  -------------  -----------------------------------------------  ---------------
ubuntu-26_04-lts  Canonical    server         Canonical:ubuntu-26_04-lts:server:26.04.202610…  26.04.202610…
ubuntu-26_04-lts  Canonical    server-arm64   Canonical:ubuntu-26_04-lts:server-arm64:26.04…   26.04.202610…
ubuntu-26_04-lts  Canonical    server-gen1    Canonical:ubuntu-26_04-lts:server-gen1:26.04…    26.04.202610…
{ "arch": "x64", "features": ["SecurityType","IsAcceleratedNetworkSupported","DiskControllerTypes",…], "gen": "V2", "plan": null }
CommandFunctionNote
az vm image list --allFull directory queryDo not add --all Only the built-in alias table (offline cache) is returned
az vm image showSee plan / Generation / architectureplan is not null. terms accept
az vm list-skusAvailability and limitations of specifications in regions/availability zonesRestrictions column appears NotAvailableForSubscription, that is, it is unavailable
az vm list-usageQuotaCalculated at the two levels of "series vCPU" and "regional total vCPU"

Experiment: for myapp selected image and specifications (about 4 minutes, only query, no charge)

Confirm that the 26.04 image exists and there is no plan
source ~/linuxlab/azure/env.sh
az vm image show --urn $IMAGE -l $LOC --query "{gen:hyperVGeneration, arch:architecture, plan:plan}" -o json
{ "arch": "x64", "gen": "V2", "plan": null }
Confirm that the specifications are available in canadacentral
az vm list-skus -l $LOC --size $SIZE --query "[].{name:name, zones:locationInfo[0].zones, restrictions:restrictions}" -o json
[ { "name": "Standard_D2ads_v5", "restrictions": [], "zones": ["1","2","3"] } ]

restrictions Empty means your subscription is available. If NotAvailableForSubscription appears, return to env.sh and replace it with Standard_D2s_v5.

(Contrast) Comparison of URNs for 24.04 with Azure Linux
az vm image list-skus -l $LOC -p Canonical -f ubuntu-24_04-lts -o tsv --query "[].name"
az vm image list -p microsoftazurelinux --all -l $LOC --query "[].urn" -o tsv | sort -u | head
Record decision: Write "Ubuntu 26.04" in ~/linuxlab/azure/decision.md LTS (consistent with the local lab VM, free image, cloud-init ready) + Standard_D2ads_v5 (2 vCPU/8 GiB, with temporary disk for teaching)".

Case 1: The automated script suddenly reported "Invalid image"

Problem: The deployment script written many years ago said --image UbuntuLTS, and the error was reported after upgrading the CLI. Cause: The alias table is built into the CLI and the old aliases have been removed. Method: Change all scripts and Terraform to complete URN, and add az vm image show --urn... to the CI for pre-checking; when repeatable builds are required, replace latest with a fixed version number.

Case 2: Arm64 cost reduction migration

Problem: The team wants to migrate myapp to Arm specifications to save costs. How to do it: Pure Python applications do not need to change the code, but the image must be changed to the server-arm64 SKU and the specification to the Dps series; if the pip dependency contains C extension, you need to confirm that there is aarch64 wheel. First run a stress test in the test environment, and then replace them in batches.

Case 3: RHEL Compliance Requirements

Issue: The audit requires that production servers use a vendor-supported enterprise distribution. How to do it: Choose RHEL PAYG image (subscription fee is billed with VM) or BYOS + Red Hat Cloud Access; note that SELinux default enforcing, myapp's systemd unit and port require corresponding policies (rhellab comparison in Lessons 1–2).

Common errors and solutions

(SkuNotAvailable) The requested VM size for resource 'Following SKUs have failed for Capacity Restrictions: Standard_D2ads_v5' is currently not available in location 'canadacentral'.

Reason: This specification is limited or has insufficient capacity for your subscription in this region/availability zone.

az vm list-skus -l canadacentral --size Standard_D2ads_v5 --query "[].restrictions" -o json

Fix: Change the specification (Standard_D2s_v5), change the availability zone, or change the region; the production environment can use capacity reservation in advance.

Operation could not be completed as it results in exceeding approved Total Regional Cores quota.

Reason: Insufficient vCPU quota (any insufficient region total or series quota will fail).

az vm list-usage -l canadacentral -o table | grep -Ei "Total Regional|Family"

Fix: Delete unused VMs (deallocated VMs do not occupy vCPU quota, but still account for disk charges) or request an increase on the portal Quotas page.

The selected VM size 'Standard_D2ps_v5' cannot boot Hypervisor Generation '2' image with architecture 'x64'.

Cause:Arm specs come with x64 images (or vice versa).

Fix:Arm specs match server-arm64 SKU; x64 specs match server. Preflight with az vm image show --query architecture.

MarketplacePurchaseEligibilityFailed / You have not accepted the legal terms on this subscription

Reason: The third-party image comes with a plan, and you need to accept the terms first (or the subscription type does not allow the purchase of Marketplace products).

az vm image terms accept --urn <publisher>:<offer>:<sku>:latest
Loading of self-compiled kernel module under Secure Boot failed: Key was rejected by service

Reason:Trusted Launch enables Secure Boot by default, and unsigned modules are rejected.

Fix: Use a distribution-signed DKMS package and register the MOK, or create the VM with --security-type Standard after explicitly assessing the risk (not recommended).

Command line operation questions
1. Use one command to view the Generation and architecture of the latest version of the Ubuntu 26.04 x64 image.
az vm image show --urn Canonical:ubuntu-26_04-lts:server:latest -l canadacentral --query "{gen:hyperVGeneration,arch:architecture}"
2. List all Arm specification names with "ps_v5" in canadacentral.
az vm list-sizes -l canadacentral --query "[?contains(name,'ps_v5')].name" -o tsv
Scenario analysis question
The same Terraform can create a VM in eastus, but fails in canadacentral and reports SkuNotAvailable. What is your order of investigation?

① az vm list-skus -l canadacentral --size … Look at restrictions and zones (maybe not available in this availability zone); ② list-usage Look at quotas; ③ Confirm that the image is released in this region (image show -l); ④ If it is a capacity problem, change to similar specifications of the same generation or remove zone fixation; ⑤ Long-term solution: Maintain a specification list for each zone in a variable.

Verified instructional video

▶
Creating your first Azure VM! — John Savill's Technical Training
English · Each option to create a VM (image, specification, disk, network) is explained step by step from the portal, suitable for getting started
▶
Azure Master Class v3 - Part 7 - VMs and VMSS — John Savill's Technical Training
English · Long system course: VM series and specifications, Generation, maintenance, VMSS
▶
Azure Master Class v2 - Module 7 - VM and VMSS — John Savill's Technical Training
English · Previous edition of the same theme course, for comparison

Official document

Video storyboard script (about 75 seconds)

Shot 1 · 0–20s
Screen: URN four pieces put together like building blocks: Canonical / ubuntu-26_04-lts / server / latest.
Narration: On Azure, a Linux image consists of four segments: publisher, product, SKU and version, which are collectively called URN.
Lens 2 · 20–45s
Screen: The specification name Standard_D2ads_v5 lights up letter by letter and an explanation pops up.
Narration: Every letter in the specification name has meaning: D is for general purpose, 2 is for two vCPUs, a is for AMD, d means with local temporary disk, and s supports advanced SSD.
Lens 3 · 45–75s
Screen: A red cross appears when stitching Arm specs and x64 images.
Aside: The image and specs must match on architecture, generation, and region quotas, otherwise the creation phase will fail.
Or score ≥ 70% on the Quiz

Module 2 · cloud-init and VM extension: first startup automation

05:00 – 13:00 · Let the VM install redis-server and create myapp on its first boot User, write the unit file and start the service - no need to log in once
8 minutesCore AnimationcustomData ≠ userData★★★★★
Learning objectives
  • Explain Azure's two pre-configured agents (cloud-init and Azure Linux Agent / walinuxagent) division of labor: cloud-init is responsible for first startup configuration, and walinuxagent is responsible for VM expansion and heartbeat.
  • Tell in order what the five stages of cloud-init (generator → local → init(network) → config → final) do, where the data comes from (ovf-env.xml, IMDS in the provisioning ISO), and when to "report readiness" to the platform.
  • Write a #cloud-config that can deploy myapp + redis-server, and use cloud-init status/analyze/schema and log troubleshooting; also use Custom Script extension for "post-creation" configuration.
Prerequisite knowledge:The systemd unit and startup process of Lesson 2. Importance:★★★★★ (the starting point of all automation in the cloud)

What: provisioning (provisioning) with two agents

"Provisioning" is how Azure puts you in az vm The host name, administrator user name, SSH public key, and custom data given in create are passed to the VM, and the provisioning agent in the VM consumes these values, configures the system, and reports the completed process to the platform. Azure supports two provisioning agents: cloud-init and Azure Linux Agent (WALA, package name walinuxagent). In endorsed images such as Ubuntu and RHEL, cloud-init is responsible for provisioning; WALA is still installed and running, but has turned off its own provisioning code and is only responsible for processing VM extensions (cloud-init cannot handle extensions).

cloud-initwalinuxagent(WALA)
When to runRun at every startup, but most modules are executed "once per instance"Resident systemd service (Ubuntu: walinuxagent.service)
What to doNetwork, host name, user and SSH key, disk/mount, software package, write file, runcmdGet "target status" from WireServer (168.63.129.16), download and execute the extension, report heartbeat and extension status
InputcustomData/userData (#cloud-config and other formats)Extended settings/protectedSettings
TimeoutNo time limit, no deployment failure due to timeoutIf WALA is used to process customData, the total provisioning time cannot exceed 40 minutes
Log/var/log/cloud-init.log, cloud-init-output.log/var/log/waagent.log, /var/log/azure//

customData and userData: two "custom data"

customData(--custom-data)userData(--user-data)
Transfer channelProvisioning ovf-env.xmlIMDS: /metadata/instance/compute/userData
Can it be read/modified after creation?Cannot be read back from IMDS; modifications require rebuilding the VMIt can be read at any time in the VM; it can be read at any time through az vm update Update (will not automatically rerun)
Whether cloud-init is processedYes (first startup)Yes (cloud-init 21.2+ can also be provisioned via IMDS when there is no UDF driver)
Put it confidential? Do not put passwords/keys - they can be read by processes with permissions in the VM, and customData will be saved in locations such as /var/lib/waagent. Managed Identity + Key Vault for Secrets (Module 4).

How: Five stages of cloud-init on Azure

  1. Generator: The systemd generator determines whether cloud-init is required for this startup (ds-identify identifies Azure through DMI). datasource_list: [ Azure ] is usually hardcoded in the image to save time.
  2. Local (cloud-init-local.service, before the network is up): Load the Azure data source, mount the provisioned ISO, read ovf-env.xml (host name, username, public key, customData), access IMDS through temporary DHCP to obtain the network configuration, and write out the netplan network configuration.
  3. Init/Network (cloud-init.service): Run cloud_init_modules——bootcmd, write_files, growpart/resizefs, disk_setup/mounts (format and mount the temporary disk to /mnt), set_hostname, users_groups, ssh. After this stage, cloud-init sends a "provisioning success" signal to the Azure platform - az vm create therefore returns, but the software package may not be installed yet!
  4. Config (cloud-config.service): Run cloud_config_modules, such as apt configuration, ntp, time zone, runcmd (just write the command as a script).
  5. Final (cloud-final.service, close to multi-user.target): Run cloud_final_modules——package_update_upgrade_install (package), write_files_deferred (defer: true file), scripts_user (actually execute runcmd), final_message. Scripts under /var/lib/cloud/scripts/per-boot|per-instance|per-once will also be executed.
Why should myapp's files defer: truewrite_files run in the Init phase, earlier than users_groups create myapp user, if you write here owner: root:myapp will fail because the group does not exist. Add defer: true to allow the file to be written in the Final stage (the user has created it and the package has been installed).

When: cloud-init, extension, image, where are they used?

RequirementsPreferredReason
First boot, install package, create user, write configurationcloud-init(customData)Out-of-the-box, cross-release, no timeout
VM is already running, you need to add configuration/run scriptCustom Script extension or Run Commandcloud-init will not rerun existing instances by default
Platform capabilities (Entra login, monitoring agent, patch)Dedicated VM Extensions (AADSSHLoginForLinux, AzureMonitorLinuxAgent...)Maintained version and automatic upgrade by Microsoft
Start time-sensitive, large number of identical VMsPre-made image (Packer + Azure Compute Gallery)Put packaging into the build phase, and only do a small amount of personalization at startup
Continuous configuration drift managementAnsible and other configuration managementSee Ansible Lesson

Comparison with similar technologies

AzureAWS (Lesson 4)Local Multipass
Data SourceAzure(ovf-env.xml + IMDS)Ec2(IMDSv2)NoCloud
Platform AgentwalinuxagentSSM Agent (optional)None
Complete signalReport ready to WireServerNo explicit signal (status check)multipass waits for cloud-init
Common misunderstanding① “az vm create Success = application has been installed" - only means that the Init phase is completed, packaging and runcmd are in the Final phase, and need to be confirmed with cloud-init status --wait . ② "runcmd Failure will cause the deployment to fail" - No, cloud-init still reports provisioning success, you must see cloud-init-output.log. ③ "Changed customData will take effect after restarting" - customData is only processed during the first startup. ④ "Choose one between cloud-init and waagent" - the two coexist, each takes care of its own share.

Architecture diagram: where the configuration comes from when first booting

Azure host/platform Provisioning ISO (UDF optical drive)ovf-env.xml: User/PublicKey/customData IMDS 169.254.169.254Instance Metadata/Network/userData/Token WireServer 168.63.129.16Report Ready · Extended Goal Status · Heartbeat These three endpoints are only accessible from within the VM VM: vm-linux-lab(Ubuntu 26.04) cloud-init (Azure Data source)local → init → config → final walinuxagentExtensions: AADSSHLogin / AMA / CSE Results netplan network · hostnamelabadmin + authorized_keysTemporary disk → /mntredis-server · python3-venvmyapp user · /opt/myapp/app · envmyapp.service :5000The extension is installed to /var/lib/waagent ready
Figure 2-1 customData via provisioned ISO, network and userData via IMDS, ready signal and extension via WireServer

Flowchart: cloud-init stage and systemd unit

Generatords-identifyEnable cloud-init.target Localcloud-init-localData source + network configuration Init (Network)cloud-init.serviceUser/Disk/SSH → Report ready Configcloud-configruncmd written as script Finalcloud-finalPackaging · defer file · runcmd ← network-online.target Before | After → Cloud-final is written to /var/lib/cloud/instance/boot-finished after completion
Figure 2-2 az vm create returns after the Init phase; whether the application is ready must wait for Final

Core animation: the first startup of a Linux VM on Azure

Step by step play the entire process from "the resource manager issues a creation request" to "myapp is ready on port 5000 and can log in via SSH". The highlighted box is the executor of the current step, and the terminal is the actual information you can see in the serial log / cloud-init.log (the time is for reference).

Azure Platform (outside VM) ARM/Host Distribution Provisioning ISO ovf-env.xml IMDS 169.254.169.254 WireServer 168.63.129.16 Extension repository (download ZIP) Your terminal ssh / curl VM internals (boot order →) UEFI + SB shim → GRUB Kernel 7.0 + initramfs systemd (PID 1) generatords-identify localData source/network initUser/Disk/SSH configruncmd→Script finalPackaging/Execution walinuxagent (extended processor) redis-server :6379 myapp.service :5000 sshd · labadmin (public key) OS disk / (growpart) · Temporary disk /mnt · Serial port ttyS0 → Start diagnostics
Step 0 / 0
Click "Next" or "Autoplay" to start.

Common commands

# ——Outside the VM——
az vm create ... --custom-data cloud-init.yaml      # First boot configuration (via ovf-env.xml)
az vm create ... --user-data user-data.yaml         # Provided by IMDS, read back and updateable
az vm extension image list --location canadacentral --publisher Microsoft.Azure.Extensions -o table
az vm extension list -g rg-linux-lab --vm-name vm-linux-lab -o table
az vm extension set -g rg-linux-lab --vm-name vm-linux-lab \
  --publisher Microsoft.Azure.Extensions --name CustomScript \
  --settings '{"commandToExecute":"systemctl is-active myapp"}'
az vm get-instance-view -g rg-linux-lab -n vm-linux-lab \
  --query "instanceView.{agent:vmAgent.vmAgentVersion, status:vmAgent.statuses[0].displayStatus, ext:extensions[].{n:name,s:statuses[0].displayStatus}}"

# ——Inside the VM——
cloud-init status --wait --long        # Block until final ends; --long Display data sources and errors
cloud-init analyze show                # Each stage/module takes time
cloud-init analyze blame | head
sudo cloud-init schema --system --annotate   # Verify the user-data actually used by the machine
sudo cloud-init query v1.cloud_name    # Query the metadata cached by the data source (output azure); --list-keys List queryable keys
sudo cat /var/log/cloud-init-output.log | tail -50  # runcmd/packaged stdout/stderr
systemctl status walinuxagent --no-pager
sudo tail -n 30 /var/log/waagent.log
ls /var/log/azure/                     # One log directory for each extension
status: done
extended_status: done
boot_status_code: enabled-by-generator
last_update: Tue, 17 Nov 2026 02:14:51 +0000
detail: DataSourceAzure [seed=/dev/sr0]
errors: []
recoverable_errors: {}

-- Boot Record 01 --
The total time elapsed since completing an event is printed after the "@" character.
Starting stage: init-local
|`->no cache found @00.00100s +00.00000s
|`->found local data from DataSourceAzure @00.00800s +01.81200s
Finished stage: (init-local) 01.88000 seconds
...
Finished stage: (modules-final) 74.31000 seconds
Total Time: 81.40200 seconds
CommandPurposeNote
cloud-init status --waitWaiting for the first startup to be completed in the scriptThe exit code is not 0 means there is an error (the new version returns 2 for recoverable errors)
cloud-init schemaVerify YAML syntax and key namesUse -c file locally to verify before deployment, which can avoid a complete rebuild
cloud-init clean --logsClear the status and rerun as a new instance next timeOnly for imaging or experimentation; use with caution in production
az vm extension setInstalling/updating extensionsRequires VM agent running and outbound access

Experimental: Use cloud-init to deploy myapp + redis-server in one go (about 8 minutes, start billing)

Write cloud-init configuration (Same as the native deployment method in Lesson 2: system user myapp, code /opt/myapp/app/, /opt/myapp/venv, /etc/myapp/myapp.env, myapp.service(WorkingDirectory=/opt/myapp/app))
#cloud-config
# ~/linuxlab/azure/cloud-init.yaml - Lesson 3: Deploying myapp on first launch on Azure
package_update: true
packages:
  - redis-server
  - python3-venv
  - jq
  - rsyslog            # AMA syslog collection via rsyslog/syslog-ng (module 5); no side effects when installed

users:
  - default            # Keep az vm create --admin-username (labadmin); omission will result in the administrator user not being created!
  - name: myapp
    system: true
    homedir: /opt/myapp
    no_create_home: true
    shell: /usr/sbin/nologin

write_files:
  - path: /opt/myapp/app/requirements.txt
    permissions: '0644'
    content: |
      flask==3.1.*
      redis==5.*
      gunicorn==23.*
  - path: /opt/myapp/app/app.py
    permissions: '0644'
    content: |
      import os, socket
      from flask import Flask, jsonify
      import redis

      app = Flask(__name__)
      r = redis.Redis(host=os.getenv("REDIS_HOST", "127.0.0.1"),
                      port=int(os.getenv("REDIS_PORT", "6379")), socket_connect_timeout=1)

      @app.get("/")
      def index():
          try:
              hits = r.incr("hits")
          except redis.exceptions.ConnectionError:
              hits = "N/A (redis not connected)"
          return f"Hello from {socket.gethostname()}, hits={hits}\n"

      @app.get("/healthz")
      def healthz():
          try:
              r.ping()
              return jsonify(status="ok", redis="up")
          except redis.exceptions.ConnectionError:
              return jsonify(status="degraded", redis="down"), 503
  - path: /etc/myapp/myapp.env
    owner: root:myapp
    permissions: '0640'
    defer: true          # The myapp group only exists after users_groups, and is postponed to the final stage to write
    content: |
      REDIS_HOST=127.0.0.1
      REDIS_PORT=6379
      GUNICORN_CMD_ARGS=--bind 0.0.0.0:5000 --workers 2 --access-logfile -
  - path: /etc/systemd/system/myapp.service
    permissions: '0644'
    content: |
      [Unit]
      Description=myapp (Flask + gunicorn)
      Wants=network-online.target redis-server.service
      After=network-online.target redis-server.service

      [Service]
      User=myapp
      Group=myapp
      EnvironmentFile=/etc/myapp/myapp.env
      WorkingDirectory=/opt/myapp/app
      ExecStart=/opt/myapp/venv/bin/gunicorn app:app
      SyslogIdentifier=myapp
      Restart=on-failure
      RestartSec=3
      NoNewPrivileges=true
      ProtectSystem=strict
      ProtectHome=true
      PrivateTmp=true

      [Install]
      WantedBy=multi-user.target

runcmd:
  - [python3, -m, venv, /opt/myapp/venv]
  - [/opt/myapp/venv/bin/pip, install, --no-cache-dir, -r, /opt/myapp/app/requirements.txt]
  - [systemctl, daemon-reload]
  - [systemctl, enable, --now, redis-server.service, myapp.service]

final_message: "myapp first boot finished after $UPTIME seconds"

Code directory /opt/myapp/app/ (write_files will automatically create the parent directory) and the virtual environment /opt/myapp/venv are owned by root and are read-only for myapp. The service runs as myapp - this is the least privilege approach emphasized in Lesson 2. If cloud-init is installed on this machine, you can verify it first: cloud-init schema -c cloud-init.yaml --annotate.

Create VM(Enable system-assigned managed identity, required for module 4/5; SSH only releases your current public IP)
cd ~/linuxlab/azure && source env.sh
MYIP=$(curl -s https://api.ipify.org)      # You can also fill in your public IP manually
az vm create -g $RG -n $VM -l $LOC \
  --image $IMAGE --size $SIZE \
  --admin-username $ADMIN --ssh-key-values ~/.ssh/id_ed25519.pub \
  --custom-data cloud-init.yaml \
  --assign-identity \
  --public-ip-sku Standard \
  --nsg-rule SSH \
  --tags course=linux-8h part=3 \
  --query "{ip:publicIpAddress, state:powerState}" -o table
az network nsg rule update -g $RG --nsg-name ${VM}NSG -n default-allow-ssh --source-address-prefixes $MYIP/32
az vm boot-diagnostics enable -g $RG -n $VM     # Do not specify a storage account = use managed storage (required for module 7)
Ip              State
--------------  ----------
20.151.88.123   VM running
Wait for cloud-init to complete and verify
IP=$(az vm show -d -g $RG -n $VM --query publicIps -o tsv)
ssh $ADMIN@$IP 'cloud-init status --wait --long; systemctl is-active redis-server myapp; curl -s localhost:5000/healthz; curl -s localhost:5000/'
.........................
status: done
detail: DataSourceAzure [seed=/dev/sr0]
errors: []
active
active
{"redis":"up","status":"ok"}
Hello from vm-linux-lab, hits=1
Observation phase, time-consuming and confirmation division
ssh $ADMIN@$IP 'cloud-init analyze show | grep -E "Finished stage|Total"; sudo grep -E "write_files_deferred|scripts_user|package_update" /var/log/cloud-init.log | tail -5; systemctl is-active walinuxagent; id myapp; ls -l /etc/myapp/myapp.env'
Finished stage: (init-local) 01.88000 seconds
Finished stage: (init-network) 03.91000 seconds
Finished stage: (modules-config) 01.20000 seconds
Finished stage: (modules-final) 74.31000 seconds
Total Time: 81.30000 seconds
... Running module package_update_upgrade_install ...
... Running module write_files_deferred ...
... Running module scripts_user ...
active
uid=998(myapp) gid=998(myapp) groups=998(myapp)
-rw-r----- 1 root myapp 112 Nov 17 02:14 /etc/myapp/myapp.env
(Optional) Use Custom Script extension to make "post-creation" changes
az vm extension set -g $RG --vm-name $VM --publisher Microsoft.Azure.Extensions --name CustomScript \
  --settings '{"commandToExecute":"sed -i \"s/--workers 2/--workers 3/\" /etc/myapp/myapp.env && systemctl restart myapp && systemctl is-active myapp"}'
az vm extension list -g $RG --vm-name $VM --query "[].{name:name, state:provisioningState}" -o table

CustomScript can only be installed on one instance on the same VM, and set will be replaced with the new setting again; when confidential parameters are required, put --protected-settings (encrypted transmission, not displayed on the portal).

(Optional) Open port 5000 to the outside world, only your IP
az network nsg rule create -g $RG --nsg-name ${VM}NSG -n allow-myapp-5000 --priority 1010 \
  --source-address-prefixes $MYIP/32 --destination-port-ranges 5000 --protocol Tcp --access Allow
curl -s http://$IP:5000/healthz

Case 1: The new instance of automatic expansion "looks healthy but has no traffic"

Problem: The load balancing health probe is on port 22. The new VM reports that it enters the backend pool immediately after successful provisioning, but myapp is still in the Final stage of pip install. Method: Change the health probe to HTTP /healthz; bake the dependency into the image (Packer) during the build phase, cloud-init only does personalization, and the first startup time is reduced from 90 seconds to 15 seconds seconds.

Case 2: Password appears in customData

Issue: Security scan found that the Redis password was written in the cloud-init configuration, which can be seen by anyone who can read the VM disk snapshot How to: Enable managed identity on the VM, and the myapp startup script uses the IMDS token from the Key Vault. Read the password (mechanism of module 4); only non-sensitive configurations are retained in customData.

Case 3: Extension stuck in "Transitioning"

Problem: All outbound traffic goes through the firewall, and walinuxagent cannot download the expansion package. How to: Check. /var/log/waagent.log, allow the outbound destination required by the Azure extension in the firewall (WireServer 168.63.129.16 itself does not go through the firewall, but the extension download and extend its own service endpoint are required); for extensions such as AADSSHLogin, endpoints such as packages.microsoft.com also need to be allowed.

Common errors and solutions

cloud-init status: error / “Failed to run module scripts_user”

Cause:A command in runcmd failed (for example, pip cannot access PyPI). The provisioning still shows success.

cloud-init status --long
sudo tail -n 80 /var/log/cloud-init-output.log
sudo grep -n "WARNING\|ERROR\|Traceback" /var/log/cloud-init.log | tail

Fix:Correct the script; the experimental environment can sudo cloud-init clean --logs --reboot Rerun the entire first startup process (SSH host keys, etc. will be regenerated, not recommended for production).

Unable to log in with labadmin: Permission denied (publickey), but VM provisioning is successful

Reason: The users: list of cloud-config is not written - default, the administrator user passed in by Azure is overwritten.

Fix: Use Run Command or VMAccess extension (az vm user update -u labadmin --ssh-key-value…) to replace the user; fix the template.

write_files: Failed to write ... owner root:myapp — group 'myapp' not found

Cause: write_files Run during Init phase, before user/group creation.

Fix:Add defer: true to this entry, or chown in runcmd.

cloud-init schema: Error: Cloud config schema errors: packages: 'redis-server' ... / The first line of YAML is not #cloud-config

Reason: The first line must be #cloud-config (cloud-init determines the input type based on the first line); Tab is used for indentation.

cloud-init schema -c cloud-init.yaml --annotate
VMExtensionProvisioningError / Provisioning state: Transitioning (the extension is not completed for a long time)
az vm get-instance-view -g rg-linux-lab -n vm-linux-lab --query "instanceView.extensions[].{n:name,s:statuses[0].message}" -o json
sudo tail -n 50 /var/log/waagent.log
sudo ls /var/log/azure/

Fixed: Confirm that walinuxagent is running and the VM can access 168.63.129.16 and outbound 443; check the logs in the corresponding extension directory; az vm extension delete and reinstall if necessary.

Command line operation questions
1. Wait for cloud-init to complete with a command and print the last 30 lines of the log when it fails.
cloud-init status --wait || sudo tail -n 30 /var/log/cloud-init-output.log
2. View the names and status of all extensions from outside the VM.
az vm get-instance-view -g rg-linux-lab -n vm-linux-lab --query "instanceView.extensions[].{name:name,status:statuses[0].displayStatus}" -o table
Scenario analysis questions
A colleague said, "I changed workers in cloud-init.yaml to 4 and then restarted az vm, why didn't it take effect?" Please explain and give two correct methods.

customData is only processed when the instance is first started (per-instance), restarting will not rerun runcmd/write_files; and modifying local files will not change the created VM. customData. Method: ① Use Custom Script extension / Run Command / Ansible to modify /etc/myapp/myapp.env and restart the service; ② Treat configuration changes as immutable infrastructure - rebuild the VM after updating the template (or VMSS rolling upgrade)

Verified instructional video

No English video verified by oEmbed specifically explaining "stages of cloud-init on Azure" was found. The following are verified relevant videos. For the cloud-init part, please refer to the official documentation and the animation of this lesson.

▶
Azure Master Class v3 - Part 7 - VMs and VMSS — John Savill's Technical Training
English · Including explanations of VM agents, extensions and VM configuration methods
▶
Creating your first Azure VM! — John Savill's Technical Training
English · "Advanced → Custom data" option in the portal creation process

Official document

Video storyboard script (about 100 seconds)

Shot 1 · 0–20s
Screen: Press Enter in the az vm create command, an empty VM appears on the host, and a CD with ovf-env.xml written on it is inserted.
Narration: Azure burns your username, public key, and custom data onto a provisioned CD and attaches it to the new VM.
Shot 2 · 20–45s
Screen: UEFI, GRUB, kernel, systemd are lit in sequence; the local phase of cloud-init reads the disc and accesses 169.254.169.254.
Narration: After the system starts, the local phase of cloud-init first reads the CD, then asks the metadata service, and configures the network.
Shot 3 · 45–70s
Screen: In the init stage, a user is created, a temporary disk is mounted, and an arrow flies to 168.63.129.16, which says Ready; az vm create returns in the terminal.
Narration: The init phase is over, cloud-init reports to the platform that it is ready, and the command line returns - but the application is not installed yet.
Lens 4 · 70–100s
Screen: Installing redis-server in the final stage, writing env files, executing runcmd, myapp turns green on port 5000; walinuxagent downloads the extension next to it.
Narration: In the final stage, package and execute your command, myapp starts; walinuxagent is responsible for all subsequent expansions.
Or score ≥ 70% on the Quiz

Module 3 · Managed disks, temporary disks and file systems

13:00 – 21:00 · Which disk data will disappear after "stop"? How to mount the data disk without bricking the VM?
8 minutesUUID + nofailv6: NVMe temporary disk is a bare disk★★★★★
Learning objectives
  • Differentiate OS Disk, data disk (managed disk, three-copy persistent) and temporary disk (host local, non-persistent), describe the operations that will cause temporary disk data to be lost.
  • Mount a new data disk: Find the device by LUN → parted partition → mkfs → Write fstab with UUID + nofail; and use systemd RequiresMountsFor= to protect services that rely on it.
  • Will expand the data disk and file system online, and understand the changes of five disk types, host cache and SCSI → NVMe.
Prerequisite knowledge: Partitions, file systems, LVM, fstab and systemd mount units in Lesson 2. Importance:★★★★★

What: three disk roles

OS diskData diskTemporary / Resource disk
Is it a managed diskYesYesNot - host-local SSD
PersistencePersistent (3 replicas; LRS 11 9 / ZRS 12 9 years durability)PersistenceRetained during normal restart; stop (deallocation), redeployment, maintenance migration, and specification change may be lost
Linux path/ (/dev/sda or /dev/nvme0n1)Press LUN: /dev/sdc…//dev/nvme0n2…Usually /dev/disk/azure/resource, cloud-init hangs to /mnt
Suitable for storageSystem and softwareApplication data (Redis RDB/AOF, database)swap, cache, temporary files - data that can be reconstructed at any time
BillingBy provisioned sizeBy provisioned size (v2/Ultra plus IOPS/throughput)Included in VM price

OS disk limit is 4,095 GiB; MBR partition table can only use 2 TiB. Standard HDD as an OS disk will be retired on 2028-09-08. Only specifications with d have temporary disks (module 1). Temporary disks with v5 and above specifications (and temporary OS disks) are encrypted at rest by default.

Why: How to choose among the five managed disk types

TypeMedia/FeaturesTypical uses
Standard HDDCheapest, high latencyBackup, cold data (OS disk is no longer recommended)
Standard SSDGetting started with SSDDevelopment test, light load Web (data disk for this lesson)
Premium SSDGiven by gear (P10/P20...) IOPS/throughput, support sudden increaseProduction of OS disk and database
Premium SSD v2Capacity, IOPS, and throughput are configured separately; OS disk cannot be producedDatabase with finely tuned performance
Ultra DiskSub-millisecond latency, performance can be adjusted online; cannot be used as OS diskSAP HANA, top-level database

VM itself also has disk IOPS/throughput upper limit (for example, Standard_D2ads_v5 is not cached. Premium SSD is about 3,750 IOPS / 82 MBps), The actual performance is the smaller of "disk upper limit" and "VM upper limit". Host caching (Host caching: ReadOnly / ReadWrite / None) defaults to ReadWrite for the OS disk; the database log disk is usually set to None.

How: From "mount to VM" to "automatically mount at boot"

  1. Azure side: az vm disk attach --new --lun 0. Disks are hot-pluggable as SCSI or NVMe devices, no reboot required.
  2. Find device: Don’t guess /dev/sdc! For SCSI, use lsblk -o NAME,HCTL,SIZE to see the fourth segment of HCTL (LUN), or use the stable link /dev/disk/azure/scsi1/lun0 generated by Azure udev rules; for NVMe models, use sudo azure-nvme-id of azure-vm-utils (output type=data, lun=0).
  3. Partitioning and formatting: parted --script mklabel gpt mkpart … → partprobe → mkfs.ext4 or mkfs.xfs (≥ 2 TiB must be GPT).
  4. fstab: UUID=… /var/lib/redis ext4 defaults,nofail 0 2. Use UUID instead of device name - the device name will change with the detection order; add nofail - it can also start when the disk is missing (otherwise it will enter emergency mode, module 7).
  5. Protect services that depend on it: systemctl edit redis-server Add RequiresMountsFor=/var/lib/redis. When the disk is not mounted, Redis will not quietly write data to the covered directory under the OS disk.

When: Correct usage of temporary disk

  • SCSI temporary disk (v5 and earlier d specification): formatted and mounted to /mnt by cloud-init on first boot, with DATALOSS_WARNING_README.txt on the disk. Suitable for swap (configured with cloud-init or waagent) and rebuildable cache.
  • NVMe temporary disk (v6 specification): Delivered as a original, unformatted NVMe disk; it may become a bare disk again after each stop/deallocation, maintenance or automatic recovery, and needs to be reinitialized and mounted with a script (the official FAQ provides an mdadm RAID0 example) at each boot.
  • Data that needs to be "sustained after restarting" should be placed on the managed data disk.

Comparison with similar technologies

AzureAWS (Lesson 4)On-premises (Lesson 2)
Persistent Block StorageManaged DisksEBS volumeVirtual disk / LVM
Local non-persistent diskTemporary disk / NVMe temporary diskInstance store (Instance store)—
Stable device name/dev/disk/azure/…, LUNVolume ID in NVMe serial number/dev/disk/by-uuid
Common misunderstandings① "Restart will empty /mnt" - normal restart will not;Stop deallocation, redeploy, and change specifications. ② "fstab writes /dev/sdc1 no problem" - it may become /dev/sdd1 next time it is started. ③ "The file system automatically becomes larger after disk expansion" - Yes growpart + resize2fs/xfs_growfs(OS root partition is processed by cloud-init's growpart at startup). ④ "LVM is useless in the cloud" - It is still useful when striping multiple disks and migrating online, but it is easier to use partitions directly in single-disk scenarios.

Architecture diagram: The location of the disk in the host and storage cluster

Physical host VM: vm-linux-lab /dev/sda → / (OS disk)/dev/sdb1 → /mnt (temporary disk)/dev/sdc1 → /var/lib/redis (data disk LUN 0)fstab: UUID=… defaults,nofail Local SSD: temporary disk 75 GiBVM host change (deallocation/redeployment/maintenance)→ Data will not be migrated Azure Storage Cluster (remote) OS disk 30 GiB3 copies data01 16 GiBStandardSSD_LRS The disk can be retained independently after the VM is deletedSnapshot / Azure Backup / Cross-VM remount Network block storage
Figure 3-1 OS disk and data disk are in the remote storage cluster, and the temporary disk is local to the host

Flow chart: fstab at boot How to turn a line into a mount

/etc/fstabUUID=… /var/lib/redis systemd-fstab-generatorvar-lib-redis.mount Waiting for dev-disk-by...deviceDefault 90 seconds timeout With nofail: skip, continue startup No nofail: local-fs.target failed emergency modesshd not started → only serial console
Figure 3-2 A nofail option determines "whether SSH login is possible when the disk is missing"

Interactive simulator: Which disk data will survive?

First "write data", then select an operation and maintenance operation, and observe the data and startup results on the three disks. Check/cancel nofail and try "Restart after detaching the data disk".

OS disk /Empty
Data disk /var/lib/redisEmpty
Temporary disk /mntEmpty
Click ① first to write data.

Common commands

# —— Azure side ——
az vm disk attach -g rg-linux-lab --vm-name vm-linux-lab --name vm-linux-lab-data01 \
  --new --size-gb 16 --sku StandardSSD_LRS --lun 0
az disk list -g rg-linux-lab --query "[].{name:name, size:diskSizeGB, sku:sku.name, state:diskState}" -o table
az vm show -g rg-linux-lab -n vm-linux-lab --query "storageProfile.dataDisks[].{lun:lun,name:name,caching:caching}" -o table
az disk update -g rg-linux-lab -n vm-linux-lab-data01 --size-gb 32      # Expansion (the data disk does not need to be shut down in most cases)
az vm disk detach -g rg-linux-lab --vm-name vm-linux-lab --name vm-linux-lab-data01
az snapshot create -g rg-linux-lab -n data01-snap --source vm-linux-lab-data01

# —— Within the VM ——
lsblk -o NAME,HCTL,SIZE,FSTYPE,MOUNTPOINTS
ls -l /dev/disk/azure/ /dev/disk/azure/scsi1/ 2>/dev/null
sudo azure-nvme-id                  # NVMe model (azure-vm-utils)
sudo parted /dev/sdc --script mklabel gpt mkpart redisdata ext4 0% 100%
sudo partprobe /dev/sdc
sudo mkfs.ext4 -L redisdata /dev/sdc1
sudo blkid /dev/sdc1
findmnt --verify                    # Verify whether the fstab syntax and device exist (must be run after changing fstab)
sudo mount -a
sudo growpart /dev/sdc 1 && sudo resize2fs /dev/sdc1     # Expand the partition and file system after expansion
df -hT /mnt /var/lib/redis
NAME    HCTL       SIZE FSTYPE MOUNTPOINTS
sda     0:0:0:0     30G
├─sda1             28.9G ext4   /
├─sda14               4M
├─sda15             106M vfat   /boot/efi
└─sda16             913M ext4   /boot
sdb     0:0:0:1      75G
└─sdb1               75G ext4   /mnt
sdc     1:0:0:0      16G
/dev/disk/azure/scsi1/:
lrwxrwxrwx 1 root root 12 Nov 17 02:30 lun0 -> ../../../sdc

The partition layout, HCTL number and udev link name in the output vary depending on the image version and controller type, and are subject to the actual results of lsblk and ls /dev/disk/azure.

Experiment: Give Redis a dedicated data disk (about 7 minutes)

Create and mount a 16 GiB Standard SSD to LUN 0
source ~/linuxlab/azure/env.sh
az vm disk attach -g $RG --vm-name $VM --name ${VM}-data01 --new --size-gb 16 --sku StandardSSD_LRS --lun 0
IP=$(az vm show -d -g $RG -n $VM --query publicIps -o tsv); ssh $ADMIN@$IP
Find the disk by LUN in the VM (do not guess the drive letter)
lsblk -o NAME,HCTL,SIZE,MOUNTPOINTS
DEV=$(readlink -f /dev/disk/azure/scsi1/lun0 2>/dev/null || true); echo "DEV=$DEV"
# NVMe model: sudo azure-nvme-id, find the line with type=data, lun=0, and manually set DEV=/dev/nvme0n2
[ -b "$DEV" ] && lsblk "$DEV"
DEV=/dev/sdc
NAME MAJ:MIN RM SIZE RO TYPE MOUNTPOINTS
sdc    8:32   0  16G  0 disk
Partition and format (the disk data will be cleared - confirm the DEV is correct again)
sudo parted "$DEV" --script mklabel gpt mkpart redisdata ext4 0% 100%
sudo partprobe "$DEV"; sleep 2
PART=$(lsblk -lnpo NAME "$DEV" | sed -n 2p); echo "PART=$PART"
sudo mkfs.ext4 -q -L redisdata "$PART"
UUID=$(sudo blkid -s UUID -o value "$PART"); echo "UUID=$UUID"
Migrate the Redis data directory and write to fstab (UUID + nofail)
sudo systemctl stop myapp redis-server
sudo mkdir -p /mnt/newredis && sudo mount "$PART" /mnt/newredis
sudo rsync -aHAX /var/lib/redis/ /mnt/newredis/ && sudo umount /mnt/newredis && sudo rmdir /mnt/newredis
sudo cp /etc/fstab /etc/fstab.bak.$(date +%F)
echo "UUID=$UUID  /var/lib/redis  ext4  defaults,nofail  0  2" | sudo tee -a /etc/fstab
findmnt --verify --tab-file /etc/fstab
sudo systemctl daemon-reload && sudo mount /var/lib/redis
sudo chown redis:redis /var/lib/redis && sudo chmod 750 /var/lib/redis
findmnt /var/lib/redis
UUID=3f1c…  /var/lib/redis  ext4  defaults,nofail  0  2
Success, no errors or warnings detected
TARGET         SOURCE    FSTYPE OPTIONS
/var/lib/redis /dev/sdc1 ext4   rw,relatime
Let redis-server rely on this mount point (drop-in trick in Lesson 2)
sudo mkdir -p /etc/systemd/system/redis-server.service.d
printf '[Unit]\nRequiresMountsFor=/var/lib/redis\n' | sudo tee /etc/systemd/system/redis-server.service.d/10-datadisk.conf
sudo systemctl daemon-reload && sudo systemctl start redis-server myapp
systemctl show redis-server -p RequiresMountsFor
curl -s localhost:5000/ ; redis-cli DBSIZE
RequiresMountsFor=/var/lib/redis
Hello from vm-linux-lab, hits=2
(integer) 1
Observe the temporary disk
findmnt /mnt; ls /mnt; df -h /mnt
TARGET SOURCE    FSTYPE OPTIONS
/mnt   /dev/sdb1 ext4   rw,relatime,x-systemd.after=cloud-init.service,…
DATALOSS_WARNING_README.txt  lost+found

The fstab entry of the temporary disk is generated by the mounts module of cloud-init, which comes with nofail and options that depend on cloud-init.

Restart verification: sudo reboot, SSH again after 30 seconds, and confirm that the counts of findmnt /var/lib/redis and curl localhost:5000/ continue to increase.

Case 1: Deallocation saves money, but the cache is all gone

Problem: The team automatically deallocated the development VM at night to save money, but the next day found that the build cache and temporary upload files on /mnt were all lost. How to do it:Clearly agree that the temporary disk will only store rebuildable data; migrate the cache that needs to be retained to the data disk or Azure Files; put a README in /mnt to prompt the team.

Case 2: /mnt disappeared after switching to v6 specifications

Problem: After upgrading Dadsv5 to Dadsv6, the application reported "No such file or directory: /mnt/cache". Reason: The NVMe temporary disk of v6 is delivered as a bare disk, and cloud-init's default temporary disk processing is for SCSI resource disk. Method: According to the official FAQ, write a systemd oneshot service that runs "every boot", detect Microsoft NVMe Direct Disk, group RAID0, format and mount, and apply the service After=/RequiresMountsFor= to the mount point.

Case 3: Database disk IOPS filled

Problem:PostgreSQL on disk P10 (500 IOPS) has spikes in latency during peak periods. Method: Check "Data Disk IOPS Consumed Percentage" and VM-level "VM Uncached IOPS Consumed Percentage" in Azure Monitor to confirm whether the disk or the VM is filled first; upgrade the disk to P30 or move to Premium SSD v2 to increase the IOPS individually; change to a larger VM specification if necessary (the VM upper limit also plays a role).

Common errors and solutions

Timed out waiting for device dev-disk-by\x2duuid-….device / Dependency failed for /var/lib/redis

Cause: The disk in fstab does not exist (detached, UUID written incorrectly), and there is no nofail → emergency mode.

Fix: See Module 7: Serial Console Enters Maintenance Mode, comment this line or add nofail; or az vm repair repair-button --button-command fstab.

mount: /var/lib/redis: wrong fs type, bad option, bad superblock on /dev/sdc

Cause: The entire disk is formatted but the partition is mounted (or vice versa), or the file system type is written incorrectly.

lsblk -f; sudo blkid

Fix: UUID and type in fstab must come from the same line as blkid.

(OperationNotAllowed) Disk resizing is allowed only when creating a VM or when the VM is deallocated

Cause:The disk/scenario does not meet the online expansion conditions (such as OS disk or certain disk types).

Fixed:az vm deallocate → az disk update --size-gb → az vm start; note that deallocation will clear the temporary disk.

After expansion, df still shows the old size
lsblk /dev/sdc            # The disk has become larger but the partition has not changed
sudo growpart /dev/sdc 1
sudo resize2fs /dev/sdc1   # XFS uses sudo xfs_growfs /var/lib/redis
Redis startup failed: Can't open the append-only file / Permission denied (/var/lib/redis)

Cause: The owner of the new file system root directory is root.

sudo chown redis:redis /var/lib/redis && sudo systemctl restart redis-server
journalctl -u redis-server -n 20 --no-pager
Command line operation questions
1. Find the block device (SCSI model) corresponding to LUN 0 in the VM.
readlink -f /dev/disk/azure/scsi1/lun0    # or lsblk -o NAME,HCTL | awk '$2 ~ /:0$/'
2. What verification commands must be executed after modifying fstab and before restarting?
findmnt --verify && sudo mount -a
Scenario analysis question
Operation and maintenance changed the VM from Standard_D2ads_v5 to Standard_D4ads_v5. After the change, the Redis data is still there, but the session cache in /mnt is gone. Why? How to avoid it?

Changing the specifications may move the VM to a new host. The temporary disk is the local disk of the host and will not be migrated; Redis is on the managed data disk, so it is retained. Avoid: If the session cache needs to be retained, put it in Redis (data disk) or an external cache service; the temporary disk only holds rebuildable content, and the directory can be automatically reconstructed when the application starts.

Verified instructional video

▶
Azure Managed Disks Deep Dive — John Savill's Technical Training
English · Managed disk types, performance, bursting, caching and snapshots
▶
IOPS, Throughput & Latency Explained — John Savill's Technical Training
English · Understanding the basics of disk and VM two-level performance caps

Official documentation

Video storyboard script (about 80 seconds)

Shot 1 · 0–20s
Screen: A VM in the host, two disks in the remote storage cluster on the right with the "3 copies" mark, and a red temporary disk locally in the host.
Narration: The OS disk and data disk are stored remotely, with three copies; the temporary disk is local to the host machine.
Shot 2 · 20–45s
Screen: The VM is "deallocated" and moved to another host. The connection to the remote disk follows, and the local temporary disk remains in place and is cleared.
Narration: Once the VM changes hosts, the data on the temporary disk will remain in place.
Shot 3 · 45–80s
Screen: fstab A line of text, the system stops in emergency mode when nofail is missing, and starts smoothly after adding nofail.
Narration: The data disk is mounted with UUID, and nofail must be added, otherwise the entire VM will not be able to access it when the disk is missing.
Or score ≥ 70% on the Quiz

Module 4 · Identity and Access: Entra ID Login, SSH and Bastion

21:00 – 29:00 · How does one log into a VM (Entra ID / SSH Key / Bastion / JIT), VM How can the program in access Azure (managed identity + IMDS) "as a VM"
8 minutesCore AnimationAADSSHLoginForLinuxRequires assigned role permissions★★★★★
Learning Objectives
  • Enable Microsoft Entra ID login for VM: system-assigned managed identity + AADSSHLoginForLinux extension + Virtual Machine Administrator/User Login role + az ssh vm, and explain the reason why "Owner can't log in either".
  • Explain the path to obtain the managed identity token: Process within the VM → 169.254.169.254/metadata/identity/oauth2/token (Metadata: true) → Managed identity subsystem on the host → Entra ID → Bearer token → Target service does RBAC.
  • Choose combination between SSH keys, Entra login, Azure Bastion, JIT, tighten port 22 in NSG.
Prerequisite knowledge:Users, groups, sudo in Lesson 1; sshd configuration in Lesson 2. Importance:★★★★★

What: Two types of identities, two paths

"People" log in to VM"Programs in VM" access Azure
IdentityMicrosoft Entra User/Group/Service PrincipalVM's Managed Identity (system-assigned or user-assigned)
CredentialsEntra-issued short-lived OpenSSH certificate (az ssh vm automatically obtained)OAuth access token returned by IMDS (no key/password required)
AuthorizationAzure RBAC: Virtual Machine Administrator Login (sudo available)/ Virtual Machine User LoginAzure RBAC: Assign managed identities roles on target resources (e.g. Reader, Key Vault Secrets User)
In-VM componentsaadsshlogin (and aadsshlogin-selinux), installed by the AADSSHLoginForLinux extensionNo components required - any process that can make HTTP requests

Why: Why use Entra ID instead of distributing SSH public keys

  • No longer in each VM Maintain authorized_keys on the system; if an employee resigns and disables the Entra account, all VM access rights will be lost.
  • Can be stacked with Conditional Access (MFA, compliance devices, risk detection); the application name in Conditional Access is "Azure Linux VM Sign-In".
  • Use RBAC to distinguish between "who can manage the VM" and "who can log into the VM": Owner/Contributor does not automatically have SSH login rights (intentional and audited separation).
  • Available Azure Policy forces all Linux VMs to enable Entra login, flagging unapproved local accounts.

How: Four conditions for enabling Entra login (2026-11 verification)

  1. Supported distributions: Ubuntu 16.04 to 26.04, RHEL 8.3+/9.0+/10.1, Azure Linux 3.0, Debian 9–13, AlmaLinux/Rocky 8–10, etc.
  2. VM: Enable System Assigned Managed Identity; install extension Microsoft.Azure.ActiveDirectory/AADSSHLoginForLinux (VM agent running, memory ≥ 1 GB).
  3. Network: VM has outbound 443 access to packages.microsoft.com, login.microsoftonline.com, pas.windows.net, and access to IMDS 169.254.169.254.
  4. Client: Azure CLI + ssh extension (az extension add --name ssh, Cloud Shell is pre-installed); you can also az ssh config export the certificate to any client that supports OpenSSH certificates.

Assigning login roles requires Virtual Machine Data Access Administrator or a role that contains Microsoft.Authorization/roleAssignments/write (such as Role Based Access Control Administrator). It is officially recommended to allocate within the resource group or higher range to avoid reaching the upper limit of the number of roles allocated per subscription.

Key facts for managed identity tokens

  • Endpoint: GET http://169.254.169.254/metadata/identity/oauth2/token?api-version=2018-02-01&resource=, the request header must be lowercase Metadata: true (mitigating SSRF); it cannot bring X-Forwarded-For, and cannot be proxied (curl plus --noproxy "*").
  • Returns access_token, expires_on, resource, token_type: Bearer; the aud claim of the token is resource.
  • The managed identity subsystem will cache the token, and the Entra ID will only be used when the cache misses or expires; the IMDS managed identity category is limited to 20 times/second and 5 concurrency per VM, and returns 429 if the limit is exceeded - the application itself also needs to cache.
  • The security boundary is the entire VM: any code on the VM can get a token for the managed identity of this VM. Do not grant a VM more roles than your application needs.

When: Login method combination

MethodNeed public network 22? ProsCosts/Notes
SSH keys (labadmin)Yes (or via Bastion)Simple, available offlineKey distribution and revocation are difficult; just keep it as a "broken window" account
Entra ID + az ssh vmRequires TCP connectivity to VM (public network/private network/Bastion)Centralize identity, MFA, RBAC, auditRelies on extensions and outbound networking; sshd_config's AllowGroups/DenyGroups will fail first login
Azure BastionNo - VM can have no public IPBrowser or local client access via TLS 443Developer SKU free with limited functionality; On-prem native client (az network bastion ssh) requires Standard or Premium; hourly billed; requires AzureBastionSubnet
JIT VM accessTemporarily open on demandNormally NSG rejects 22, and the specified source IP will be released for a limited time after applicationRequires Defender for Servers Plan 2
Serial consoleNoLast resort when network/SSH goes downRequires password account with VM Contributor (Module 7)

Comparison with similar technologies

AzureAWS (Module 4) class)
Workload identityManaged identity (IMDS token)Instance profile/IAM role (IMDSv2 temporary credentials)
Human loginEntra ID + az ssh vmEC2 Instance Connect / SSM Session Manager
No public network springboardAzure BastionSession Manager / EC2 Instance Connect Endpoint
Common misunderstandings① "I am a subscription owner, so of course I can log in with Entra" - No, you must have a VM login role. ② "Managed identity tokens require the certificate to be placed on the VM first" - No, the credentials are held by the platform, and the VM only gets the token through IMDS. ③ "IMDS can be accessed from the outside" - 169.254.169.254 is the link local address and is only reachable within the VM. ④ "Bastion is free" - only Developer SKU is free; Standard/Premium is billed by the hour and billing starts upon deployment.

Architecture diagram: Entra login shares IMDS with managed identity

Your terminalaz login(MFA)az ssh vm → short-term certificate Microsoft Entra IDIssue SSH certificateIssue managed identity token vm-linux-lab sshd + aadsshloginVerification certificate · Check RBAC myapp / curlGET …/oauth2/token IMDS 169.254.169.254 (host side, link local)Metadata: true · Without proxy · Managed identity category 20 rps System assigned managed identity (credentials are held by the platform, not on the VM disk) pas.windows.netIf the user hasVM login role? ARM / Key VaultBearer token+ RBAC authorization :22
Figure 4-1 Human login and program access are based on Entra ID, and the VM obtains its own token through IMDS

Comparison of network entrances

Public IP + NSG 22The source address is limited to your IP/32Maximum exposureThe experiment in this lesson is by default (tightened)JIT can achieve "normal shutdown" Azure BastionVM has no public IPTLS 443 → Bastion → VM private network 22Standard+: az network bastion sshPremium: session recording / private only Private network + VPN / ExpressRouteCommon enterprise practicesaz ssh vm --ip 10.x.x.xOverlay Entra login and conditional accessNSG only allows management network segments
Figure 4-2 Identity (who can log in) and network entrance (where can be connected) are two independent things, and they must be tightened at the same time in production

Core animation: How the managed identity token reaches the VM via IMDS · Entra SSH login

Select the scene and play it step by step. The gray box is outside the VM and the blue dashed box is the VM boundary. The process is drawn according to the components and endpoints described in official documents; internal implementation details (such as cache locations) are conceptual expressions.

VM Boundary (vm-linux-lab) Your terminal Process/curl sshdaadsshlogin IMDS 169.254.169.254Managed identity endpoint · Token cache Entra IDIssue token/certificate ARM / Key VaultRBAC Check pas.windows.netLogin Role Query Conditional AccessMFA/Device Compliance

Common commands

# —— Managed Identity——
az vm identity assign -g rg-linux-lab -n vm-linux-lab                  # Enable system-assigned identity
az vm show -g rg-linux-lab -n vm-linux-lab --query identity.principalId -o tsv
az role assignment create --assignee-object-id <principalId> --assignee-principal-type ServicePrincipal \
  --role Reader --scope $(az group show -n rg-linux-lab --query id -o tsv)

# —— Entra ID login——
az vm extension set -g rg-linux-lab --vm-name vm-linux-lab \
  --publisher Microsoft.Azure.ActiveDirectory --name AADSSHLoginForLinux
az role assignment create --role "Virtual Machine Administrator Login" \
  --assignee $(az ad signed-in-user show --query id -o tsv) --scope $(az group show -n rg-linux-lab --query id -o tsv)
az extension add --name ssh
az ssh vm -g rg-linux-lab -n vm-linux-lab                  # Automatically obtain certificate and connect
az ssh config --file ~/.ssh/config -g rg-linux-lab -n vm-linux-lab   # Export to normal ssh You can also run the same command using a
az ssh vm -g rg-linux-lab -n vm-linux-lab --local-user labadmin --private-key-file ~/.ssh/id_ed25519   # local account

# —— Get the token in the VM ——
curl -s --noproxy "*" -H Metadata:true \
  "http://169.254.169.254/metadata/identity/oauth2/token?api-version=2018-02-01&resource=https%3A%2F%2Fmanagement.azure.com%2F" | jq '{token_type, expires_on, resource}'

# —— SSH key and VMAccess ——
az vm user update -g rg-linux-lab -n vm-linux-lab -u labadmin --ssh-key-value "$(cat ~/.ssh/id_ed25519.pub)"
az vm user reset-ssh -g rg-linux-lab -n vm-linux-lab      # Put sshd Configuration reset to default (for rescue)

# —— Bastion (Standard, optional, billed by the hour)——
az network vnet subnet create -g rg-linux-lab --vnet-name vm-linux-labVNET -n AzureBastionSubnet --address-prefixes 10.0.1.0/26
az network public-ip create -g rg-linux-lab -n pip-bastion --sku Standard
az network bastion create -g rg-linux-lab -n bas-linux-lab --vnet-name vm-linux-labVNET \
  --public-ip-address pip-bastion --sku Standard --enable-tunneling true -l canadacentral
az network bastion ssh -g rg-linux-lab -n bas-linux-lab \
  --target-resource-id $(az vm show -g rg-linux-lab -n vm-linux-lab --query id -o tsv) --auth-type AAD
CommandsFunctionNote
az ssh vmEntra certificate login (default) or local account loginCLI requires ssh extension; re-az login
az ssh configGenerate configuration and certificate for OpenSSH / VS Code RemoteCertificate is valid for a short period of time and will be regenerated after expiration
az vm user update/reset-sshReset key/password/sshd via VMAccess extensionRequires VM agent to be normal
az network bastion sshLocal native client login via BastionStandard/Premium + Enable Native Client Support

Experimental: Entra ID login + calling ARM with managed identity within VM (~7 minutes)

Confirm managed identity (Module 2) Already created --assign-identity) and installed the extension
source ~/linuxlab/azure/env.sh
az vm show -g $RG -n $VM --query "identity.{type:type, principalId:principalId}" -o table
az vm extension set -g $RG --vm-name $VM --publisher Microsoft.Azure.ActiveDirectory --name AADSSHLoginForLinux
az vm extension show -g $RG --vm-name $VM -n AADSSHLoginForLinux --query provisioningState -o tsv
Type            PrincipalId
--------------  ------------------------------------
SystemAssigned  7d1f…
Succeeded
Assign yourself a login role (resource group scope)
RGID=$(az group show -n $RG --query id -o tsv)
ME=$(az ad signed-in-user show --query id -o tsv)
az role assignment create --role "Virtual Machine Administrator Login" --assignee-object-id $ME --assignee-principal-type User --scope $RGID -o none
az extension add --name ssh --upgrade -y 2>/dev/null || true
Log in with Entra ID, confirm identity and sudo
az ssh vm -g $RG -n $VM -- -o StrictHostKeyChecking=accept-new 'whoami; id; sudo -n true && echo "sudo OK"'
labuser@contoso.com
uid=1203710981(labuser@contoso.com) gid=1203710981(labuser@contoso.com) groups=1203710981(labuser@contoso.com),…
sudo OK

If "Azure role not assigned" is displayed Or the connection is closed: role assignment has propagation delay, wait 1–2 minutes and try again; check if assignment is in the correct range.

Grant the resource group Reader to the managed identity of the VM, and get the token in the VM to call ARM
MI=$(az vm show -g $RG -n $VM --query identity.principalId -o tsv)
az role assignment create --assignee-object-id $MI --assignee-principal-type ServicePrincipal --role Reader --scope $RGID -o none
az ssh vm -g $RG -n $VM
# ——The following is executed within the VM——
IMDS=http://169.254.169.254/metadata
SUB=$(curl -s --noproxy "*" -H Metadata:true "$IMDS/instance/compute/subscriptionId?api-version=2025-04-07&format=text")
TOKEN=$(curl -s --noproxy "*" -H Metadata:true \
  "$IMDS/identity/oauth2/token?api-version=2018-02-01&resource=https%3A%2F%2Fmanagement.azure.com%2F" | jq -r .access_token)
echo "$TOKEN" | cut -d. -f2 | tr '_-' '/+' | base64 -d 2>/dev/null | jq '{aud, iss, oid, exp}'
curl -s -H "Authorization: Bearer $TOKEN" \
  "https://management.azure.com/subscriptions/$SUB/resourceGroups/rg-linux-lab/resources?api-version=2021-04-01" | jq -r '.value[].name'
# What happens without the Metadata header?
curl -s --noproxy "*" "$IMDS/identity/oauth2/token?api-version=2018-02-01&resource=https%3A%2F%2Fmanagement.azure.com%2F"; echo
{ "aud": "https://management.azure.com/", "iss": "https://sts.windows.net/<tenant>/", "oid": "7d1f…", "exp": 1794880000 }
vm-linux-lab
vm-linux-lab_OsDisk_1_…
vm-linux-lab-data01
vm-linux-labNSG
vm-linux-labPublicIP
vm-linux-labVNET
vm-linux-labVMNic
{"error":"invalid_request","error_description":"Required metadata header not specified"}

The payload segment of the JWT is base64url encoded, base64 -d An error may be reported due to lack of padding but the content can still be output; this is only used to observe the statement, do not print the token to the log.

Tighten the entry: Confirm that NSG port 22 is only open to your IP; with Defender for Servers Plan 2, you can enable JIT for this VM in the portal.
az network nsg rule list -g $RG --nsg-name ${VM}NSG --query "[].{name:name,port:destinationPortRange,src:sourceAddressPrefix,access:access}" -o table
(Optional, about $0.3/hour, delete as soon as done) Bastion native client: Execute the Bastion section in the "Commands" tab, then az network bastion delete -g $RG -n bas-linux-lab and delete the pip-bastion.

case 1: The public keys of resigned employees are still on 200 VMs

Problem: The audit found that the public keys of multiple resigned employees are still on authorized_keys. Method: All Linux VMs are deployed with Azure Policy AADSSHLoginForLinux, and VM User/Administrator Login is assigned at the resource group scope by team group; the local labadmin key is only saved in the keystore as a broken window account; conditional access requires MFA + compliant devices.

Case 2: The service principal key in the application configuration file expires

Problem:myapp uses the service principal key to access Key Vault. The key expires after one year, causing an early morning failure. How to do it: Switch to managed identity: the VM identity gets the Key Vault Secrets User role, and the application uses Azure SDK's ManagedIdentityCredential (the bottom layer is the IMDS token endpoint), and there is no key rotation problem.

Case 3: SSRF vulnerability and IMDS

Problem: Penetration testing found that the web application has SSRF and can request arbitrary URLs. Analysis: IMDS requires the Metadata: true header and rejects requests with X-Forwarded-For. It is difficult for ordinary SSRF to obtain the token directly; but if the attacker can control the request header, he can still obtain the token identified by the VM. How to do: Fix SSRF; VM identification is least privileged; available host firewall restricts only processes of specific users (such as myapp) from accessing 169.254.169.254.

Common errors and solutions

Connection closed by 20.151.88.123 port 22 (disconnected immediately after az ssh vm authentication)

Reason: The user does not have the VM Administrator/User Login role, or The VM's system-assigned managed identity is disabled.

az role assignment list --assignee  --all --query "[?contains(roleDefinitionName,'Virtual Machine')].{role:roleDefinitionName,scope:scope}" -o table
az vm show -g rg-linux-lab -n vm-linux-lab --query identity.type

Fix: Back-assign roles; wait a few minutes after re-enabling the identity.

AADSSHLoginForLinux: Non-zero exit code: 22 / 23 (extension stopped at Transitioning)

Reason: 22 = No system assigned managed identity; 23 = The old AADLoginForLinux extension is still there.

az vm extension delete -g rg-linux-lab --vm-name vm-linux-lab -n AADSSHLoginForLinux
az vm identity assign -g rg-linux-lab -n vm-linux-lab
az vm extension set -g rg-linux-lab --vm-name vm-linux-lab --publisher Microsoft.Azure.ActiveDirectory --name AADSSHLoginForLinux
Entra user fails to log in for the first time, there are AllowGroups in sshd_config

Cause:Official known issues: AllowGroups/DenyGroups will cause Entra user to fail to log in for the first time.

Repair: Delete these two items, or move into the Match User section and exclude the Entra user; complete the change sudo sshd -t && sudo systemctl reload ssh.

{"error":"invalid_request","error_description":"Required metadata header not specified"}

Cause: Missing Metadata: true header (or wrong case).

Token request returns 400 identity not found / unauthorized_client

Cause: The VM does not have managed identities enabled; or the VM has multiple user-assigned identities without specifying client_id/object_id/msi_res_id.

curl access 169.254.169.254 timed out

Cause: The HTTP proxy in the environment variable forwarded the request (IMDS does not support proxy), or the host firewall blocked it.

env | grep -i proxy; curl -v --noproxy "*" -H Metadata:true "http://169.254.169.254/metadata/instance?api-version=2025-04-07" -o /dev/null
Command line operation questions
1. Obtain a managed identity token for Key Vault within the VM (only output expires_on).
curl -s --noproxy "*" -H Metadata:true "http://169.254.169.254/metadata/identity/oauth2/token?api-version=2018-02-01&resource=https%3A%2F%2Fvault.azure.net" | jq -r .expires_on
2. Grant the VM normal user login rights to the group "linux-ops" at the resource group scope.
az role assignment create --role "Virtual Machine User Login" \
  --assignee-object-id $(az ad group show -g linux-ops --query id -o tsv) --assignee-principal-type Group \
  --scope $(az group show -n rg-linux-lab --query id -o tsv)
Scenario analysis questions
Company requirements: VM must not have a public IP; operation and maintenance must be logged in with MFA and able to sudo; development can only be logged in with read-only access; all sessions must be recorded. Give a plan.

VM is not assigned a public IP; Bastion Premium is deployed (session recording, private deployment only); VM is enabled with System Identity + AADSSHLoginForLinux; Operations group is assigned Virtual Machine Administrator Login, Development group is assigned Virtual Machine User Login (resource group scope); Conditional Access requires MFA for "Azure Linux VM Sign-In"; NSG only allows AzureBastionSubnet Visit 22; keep the key of a local broken account in Key Vault. Note: The native client connection currently does not support session recording. Sessions that require screen recording must be done through the portal.

Verified instructional video

▶
Microsoft Azure Managed Identity Deep Dive — John Savill's Technical Training
English · System/user allocation identification, token acquisition and RBAC
▶
Examination of options to connect to Azure VMs — John Savill's Technical Training
English · Comparison of public IP, VPN, Bastion, JIT and other connection methods
▶
Azure Just-in-time VM Access — John Savill's Technical Training
English · JIT Working principle and configuration (recorded earlier, licensing requirements are subject to Defender for Servers Plan 2 of the official document)

Official document

Video storyboard script (about 90 seconds)

Shot 1 · 0–25s
Screen: A process in the VM sends a request to 169.254.169.254, with "Metadata: true" on the header of the request.
Narration: The program in the VM does not need any password. It only needs a token from the metadata service at the link local address and brings the Metadata header.
Shot 2 · 25–50s
Screen: IMDS hands the request to the managed identity subsystem on the host, which exchanges the token for the Entra ID and caches it, returning a JWT that reads aud=management.azure.com.
Narration: The platform stores the credentials for the VM and exchanges the access token for the Entra ID. The audience of the token is the resource you requested.
Shot 3 · 50–90s
Screen: Operation and maintenance runs az ssh vm on the terminal and gets a short-term certificate to log in; sshd asks the user whether he has a VM login role, and after passing, sudo success is displayed.
Narration: When a person logs in, Entra ID issues a short-term SSH certificate, and the VM then checks whether you have the virtual machine login role. Owner must also be granted separately.
OR score ≥ 70% on the Quiz

Module 5 · Monitoring and logging: Azure Monitor Agent and DCR

29:00 – 37:00 · Send the myapp logs and CPU, memory, and disk indicators in journald / rsyslog to Log Analytics, using KQL Query
8 minutesAzureMonitorLinuxAgentBilled by imported GB★★★★☆
Learning objectives
  • Explain AMA clearly Architecture: The extension only installs agents and does not collect data; what is collected and where it is sent is defined by Data Collection Rules (DCR) and is bound to the VM through DCR Association (DCRA).
  • Understand the syslog collection link on Linux: journald → rsyslog → omfwd TCP 127.0.0.1:28330 → AMA → Log Analytics Syslog table; performance counters enter the Perf table.
  • Use CLI to create workspace, DCR, association, and write KQL to troubleshoot myapp; control the collection volume to control costs.
Prerequisite knowledge:The journald, rsyslog, and syslog facilities and levels of Lesson 2. Importance:★★★★☆

What: AMA, DCR, DCRA, Log Analytics

ComponentWhat isExample of this lesson
Azure Monitor Agent(AMA)VM extension Microsoft.Azure.Monitor / AzureMonitorLinuxAgent, runs on Linux as the azuremonitoragent service (process mdsd)Installed in vm-linux-lab, uses system-assigned managed identity authentication
Data Collection Rules (DCR)Azure Resources: Data Source (syslog facility + minimum level, performance counters, text logs...) + target + data flowdcr-linux-lab
DCR Association (DCRA)Put DCR Bind to a machine; a machine can be associated with multiple DCRsvm-linux-lab ↔ dcr-linux-lab
Log Analytics workspaceDestination for storing logs; tables Syslog, Perf, Heartbeat…law-linux-lab

Install AMA via CLI/extension No DCR will be created automatically - no data will be collected if you don't create a DCR; AMA will be installed when you "Create DCR" in the portal. Installing/upgrading/uninstalling AMA does not require restarting the VM. AMA will create system accounts without login shells such as azuremonitoragent on Linux, and security scans can be released.

Why: Why not look at journalctl directly

  • When the VM is deleted or cannot be logged in, the log is still in the workspace; the logs of multiple VMs can be queried, alerted, and made into a workbook together.
  • Correlation analysis with Azure activity logs, NSG flow logs, and Defender alarms.
  • Use RBAC to control who can read the logs without giving them VM login rights.

How: The path of a syslog message

  1. myapp (gunicorn) writes stdout → systemd into journald, identified as SyslogIdentifier=myapp, and the facility defaults to daemon.
  2. rsyslog is read from journald (or via /dev/log socket) and processed according to rules.
  3. After syslog is enabled in DCR, AMA writes forwarding rules (omfwd, TCP 127.0.0.1:28330, disk buffer queue) in /etc/rsyslog.d/10-azuremonitoragent-omfwd.conf and automatically restarts rsyslog; SELinux environments can use the Unix socket /run/azuremonitoragent/default_syslog.socket instead. The syslog-ng environment is written to /etc/syslog-ng/conf.d/.
  4. AMAs are filtered by DCR's Facility + Minimum Level and batches are sent to the Azure Monitor engine via HTTPS, falling into the workspace Syslog tables (Facility, SeverityLevel, ProcessName, SyslogMessage...).
  5. Performance counters are sampled directly by AMA (such as Processor(*)\% Processor Time) and entered into the Perf table; AMA writes Heartbeat every minute.

Levels from low to high: Debug · Info · Notice · Warning · Error · Critical · Alert · Emergency. Select "Lowest level Warning" to collect Warning and more serious messages. Note: If rsyslog uses multiple rulesets, only input from the default ruleset will be forwarded to AMA; semicolons in Syslog messages will be removed during import.

When: What to collect (cost-conscious)

DataRecommendationsReasons
auth / authprivInfo and aboveSecurity audit (SSH login, sudo)
daemon (including myapp, redis)Production Warning+; temporary Info+ during troubleshooting periodThe access log volume is large and billed by GB
kernWarning+OOM, disk I/O errors
Performance counter60 seconds sampling, few key items of CPU/memory/disk/networkThe denser the sampling, the higher the cost
Full application access logConsider text log DCR + basic log layer or sampling on the application sideCost control

Comparison with similar technologies

AzureAWS (4th Class)Open source
AgentAMACloudWatch AgentPrometheus node_exporter / Fluent Bit
Collection configurationDCR (Azure resources, centralized management)Agent JSON configuration (always put SSM parameters)Local configuration file
QueryKQLLogs Insights query syntaxPromQL / LogQL (see Prometheus class)
Common misunderstandings① "If AMA is installed, there will be data" - there must be DCR and association. ② "AMA read journald" - Linux syslog collection is forwarded by rsyslog/syslog-ng; without these two daemons, syslog cannot be received. ③ "Log Analytics agent (MMA/OMS) can still be used" - the old agent has been retired, and the new deployment only uses AMA. ④ "There is no problem in cloning a VM with AMA installed" - Officially, cloning a machine with AMA installed is not supported. Use Policy or IaC deployment.

Architecture diagram: AMA + DCR data flow

vm-linux-lab myapp / redisstdout · syslog() journaldSyslogIdentifier rsyslog10-azuremonitoragent… AMA (mdsd):28330 TCPDCR filteringperf sampling /proc · /sys DCRsyslog / perf / target Azure MonitorImport pipeline Log AnalyticsSyslogPerfHeartbeatKQL · Alarm · Workbook Delivery configuration (MI authentication) HTTPS
Figure 5-1 DCR is the "control plane", AMA is the "data plane"; syslog needs to go through rsyslog forwarded to local port 28330

Interaction: Will a log enter Log Analytics?

Set the facility and level of a message, then set the lowest level of the facility in the DCR, then send it, watching every hop along the path (and where it gets dropped).

Message facility
Message level
The lowest level of this facility in DCR

Common commands

# Workspace
az monitor log-analytics workspace create -g rg-linux-lab -n law-linux-lab -l canadacentral
# Install AMA (system assigned managed identity)
az vm extension set -g rg-linux-lab --vm-name vm-linux-lab --name AzureMonitorLinuxAgent \
  --publisher Microsoft.Azure.Monitor --enable-auto-upgrade true
# DCR (may prompt to install monitor-control-service extension, select Y)
az monitor data-collection rule create -g rg-linux-lab -n dcr-linux-lab -l canadacentral --rule-file dcr.json
az monitor data-collection rule association create --name dcra-vm-linux-lab \
  --rule-id $(az monitor data-collection rule show -g rg-linux-lab -n dcr-linux-lab --query id -o tsv) \
  --resource $(az vm show -g rg-linux-lab -n vm-linux-lab --query id -o tsv)
az monitor data-collection rule association list --resource $(az vm show -g rg-linux-lab -n vm-linux-lab --query id -o tsv) -o table
# Query (requires workspace customerId)
WS=$(az monitor log-analytics workspace show -g rg-linux-lab -n law-linux-lab --query customerId -o tsv)
az monitor log-analytics query -w $WS --analytics-query "Heartbeat | where TimeGenerated > ago(10m) | summarize max(TimeGenerated) by Computer" -o table

# Inside VM
systemctl status azuremonitoragent --no-pager
ls /etc/rsyslog.d/ | grep -i azuremonitor
sudo ss -ltnp | grep 28330
logger -p daemon.warning -t myapp "test warning from $(hostname)"

Commonly used KQL

// Myapp recent alarms and above logs
Syslog
| where Computer == "vm-linux-lab" and ProcessName == "myapp"
| where SeverityLevel in ("warning", "err", "crit", "alert", "emerg")
| project TimeGenerated, SeverityLevel, SyslogMessage
| order by TimeGenerated desc

// SSH login failure (auth/authpriv)
Syslog
| where Facility in ("auth", "authpriv") and (SyslogMessage has "Failed password" or SyslogMessage has "Invalid user")
| summarize attempts = count() by bin(TimeGenerated, 15m), Computer

// CPU average every 5 minutes
Perf
| where Computer == "vm-linux-lab" and ObjectName == "Processor" and CounterName == "% Processor Time" and InstanceName == "_Total"
| summarize avg(CounterValue) by bin(TimeGenerated, 5m)
| render timechart

// Root partition usage
Perf
| where ObjectName == "Logical Disk" and CounterName == "% Used Space" and InstanceName == "/"
| summarize arg_max(TimeGenerated, CounterValue) by Computer

SeverityLevel is stored in lowercase abbreviations in the Syslog table (such as info, warning, err, crit); the object name/instance name of the performance counter shall be subject to the actual data, and Perf | distinct ObjectName, CounterName, InstanceName View.

Experiment: Collect myapp logs and CPU/memory/disk metrics (~8 minutes, data arrival takes 5–10 minutes)

Create workspace and install AMA
source ~/linuxlab/azure/env.sh
az monitor log-analytics workspace create -g $RG -n law-linux-lab -l $LOC -o none
LAW_ID=$(az monitor log-analytics workspace show -g $RG -n law-linux-lab --query id -o tsv)
az vm extension set -g $RG --vm-name $VM --name AzureMonitorLinuxAgent --publisher Microsoft.Azure.Monitor --enable-auto-upgrade true -o none
Write DCR (syslog + performance counters)
cat > dcr.json <<EOF
{
  "location": "$LOC",
  "kind": "Linux",
  "properties": {
    "dataSources": {
      "syslog": [
        { "name": "sec", "streams": ["Microsoft-Syslog"], "facilityNames": ["auth", "authpriv"],
          "logLevels": ["Info", "Notice", "Warning", "Error", "Critical", "Alert", "Emergency"] },
        { "name": "app", "streams": ["Microsoft-Syslog"], "facilityNames": ["daemon", "kern", "syslog", "user"],
          "logLevels": ["Warning", "Error", "Critical", "Alert", "Emergency"] }
      ],
      "performanceCounters": [
        { "name": "perf60", "streams": ["Microsoft-Perf"], "samplingFrequencyInSeconds": 60,
          "counterSpecifiers": [
            "Processor(*)\\\\% Processor Time",
            "Memory(*)\\\\% Used Memory",
            "Logical Disk(*)\\\\% Used Space",
            "Network(*)\\\\Total Bytes Received" ] }
      ]
    },
    "destinations": { "logAnalytics": [ { "name": "law", "workspaceResourceId": "$LAW_ID" } ] },
    "dataFlows": [ { "streams": ["Microsoft-Syslog", "Microsoft-Perf"], "destinations": ["law"] } ]
  }
}
EOF
python3 -m json.tool dcr.json > /dev/null && echo "JSON OK"

heredoc is not quoted, $LOC, $LAW_ID will be expanded; \\\\ becomes \\ in heredoc, which is a backslash in JSON.

Create DCR and associate to VM
az monitor data-collection rule create -g $RG -n dcr-linux-lab -l $LOC --rule-file dcr.json -o none
DCR_ID=$(az monitor data-collection rule show -g $RG -n dcr-linux-lab --query id -o tsv)
VM_ID=$(az vm show -g $RG -n $VM --query id -o tsv)
az monitor data-collection rule association create --name dcra-$VM --rule-id $DCR_ID --resource $VM_ID -o none
Verify within VM that agent has taken over rsyslog forwarding and make logs
az ssh vm -g $RG -n $VM -- 'systemctl is-active azuremonitoragent rsyslog; ls /etc/rsyslog.d/ | grep -i azure; sudo ss -ltn | grep 28330;
logger -p daemon.warning -t myapp "lab warning: cache miss storm"; for i in $(seq 1 20); do curl -s -o /dev/null localhost:5000/; done'
active
active
10-azuremonitoragent-omfwd.conf
LISTEN 0  4096  127.0.0.1:28330  0.0.0.0:*
Query with KQL after 5–10 minutes
WS=$(az monitor log-analytics workspace show -g $RG -n law-linux-lab --query customerId -o tsv)
az monitor log-analytics query -w $WS -o table --analytics-query \
 'Syslog | where ProcessName == "myapp" | project TimeGenerated, SeverityLevel, SyslogMessage | take 5'
az monitor log-analytics query -w $WS -o table --analytics-query \
 'Perf | where CounterName == "% Processor Time" | summarize avg(CounterValue) by bin(TimeGenerated, 5m) | take 5'
SeverityLevel    SyslogMessage                       TableName      TimeGenerated
---------------  ----------------------------------  -------------  ----------------------------
warning          lab warning: cache miss storm       PrimaryResult  2026-11-17T03:02:11.000Z

gunicorn access logs are Info level (daemon facility) and will not be collected according to the "daemon minimum Warning" of this DCR - this is an intentional cost control. If you want to temporarily view the access log, add Info and Notice to the logLevels of the app data source and create again (overwrite the same name).

Case 1: Log Analytics suddenly doubled in the bill

Problem: Someone transferred the daemon facility to Debug and then forgot to change it back. How to do:Usage | where TimeGenerated > ago(7d) | summarize sum(Quantity) by DataType Find the big users; restore the DCR level; set daily caps and cost alarms for the workspace; switch to the basic log layer or sample on the application side for a large number of access logs.

Case 2: New VM does not have any logs

Issue: Terraform created the VM and AMA extension, but there is no Heartbeat in the workspace. Cause: The DCRA was not created; or the VM does not have a managed identity. How to do it: Use the Azure Policy built-in plan "Configure AMA and DCR association for Linux virtual machines" to unify management, and all new VMs will be automatically installed and associated.

Case 3: SELinux intercepts forwarding

Problem: rsyslog forwarding to 28330 on RHEL 9 is rejected by SELinux. How to: Use the Unix socket mode configuration provided by the AMA (omuxsock → /run/azuremonitoragent/default_syslog.socket), or adjust the policy according to the official instructions instead of turning off SELinux.

Common errors and solutions

The VM does not exist in the Heartbeat table
az vm extension show -g rg-linux-lab --vm-name vm-linux-lab -n AzureMonitorLinuxAgent --query provisioningState
az monitor data-collection rule association list --resource <VM_ID> -o table
az vm show -g rg-linux-lab -n vm-linux-lab --query identity.type

Fix:Add DCRA; enable managed identity; check outbound 443 to Azure Monitor endpoint (requires AMPLS and DCE for private link scenarios).

There is Heartbeat and Perf, but no Syslog
systemctl is-active rsyslog
ls -l /etc/rsyslog.d/*azuremonitor*
sudo ss -ltn | grep 28330
logger -p daemon.err -t probe "probe"

Cause:rsyslog is not installed/not running, the message level is lower than the DCR setting, or rsyslog uses a non-default ruleset. Fix: Install and enable rsyslog, reassociate DCR and let AMA rewrite the forwarding configuration.

(InvalidPayload) Data collection rule is invalid: 'counterSpecifiers' ... / logLevels value not allowed

Cause: The backslashes in JSON are not escaped correctly, or the level name is in wrong case (should be Info, Warning, etc. with the first letter capitalized).

python3 -m json.tool dcr.json
AMA extension installation failed: Extension operation failed … Enable failed (disk is full)

Cause: The root partition or /var has insufficient space, and the agent cannot decompress and establish a local cache.

df -h / /var; sudo du -xh /var/log | sort -h | tail

Retry after cleaning (Module 7 "disk full" scenario).

Command line operation questions
1. Send a test log of local0.err level and identified as backup in the VM.
logger -p local0.err -t backup "nightly backup failed"
2. Write KQL: the number of Syslog entries for each machine in the past hour, in descending order of quantity.
Syslog | where TimeGenerated > ago(1h) | summarize n = count() by Computer | order by n desc
Scenario analysis question
The security team requires the collection of all sudo records, while the operation and maintenance team only wants application logs with Error and above, and the two teams use different workspaces. How to design?

Create two DCRs: DCR-sec (auth/authpriv Info+ → security workspace), DCR-ops (daemon/kern Error+ and performance counters → operation and maintenance workspace), both associated with the same VM - one machine can be associated with multiple DCRs. Automatically associate all Linux VMs with Azure Policy. Avoid duplicate import costs caused by sending one DCR to two workspaces.

Verified teaching video

▶
Microsoft Azure Monitor Agent (AMA) and Data Collection Rule (DCR) Overview — John Savill's Technical Training
English · Relationship, association, migration between AMA and DCR
▶
Azure Monitor Logs Log Types — John Savill's Technical Training
English · Analysis log, basic log, etc. table plan and cost

Official document

Video storyboard (about 75 seconds)

Shot 1 · 0–20s
Screen: AMA is installed on the VM, but the Log Analytics next to it is blank; a card with DCR flying over and connected.
Narration: Installing the agent is only the first step, the data collection rules determine what is collected and where to send it.
Lens 2 · 20–50s
Screen: A myapp log flows from journald to rsyslog, then enters the local 28330 port, and is filtered by AMA by level.
Aside: On Linux, syslog is forwarded by rsyslog to the machine's proxy port, and the proxy is filtered by facility and lowest level.
Shot 3 · 50–75s
Screen: KQL query result table and CPU line chart.
Narration: Querying Syslog and Perf tables with KQL in Log Analytics. Remember, you are charged based on the amount of data you import.
OR score ≥ 70% on the Quiz

Module 6 · Patches and Updates: Azure Update Manager

37:00 – 45:00 · From "each machine has its own apt upgrade" to "unified assessment, installation according to maintenance windows, auditable"
8 minutesNo Log Analytics / Automation requiredOne ​​machine only uses one automatic update mechanism★★★★☆
Learning objectives
  • Name the capabilities of Azure Update Manager: periodic assessment (every 24 hours), on-demand assessment/installation, maintenance configuration (scheduled), dynamic scope, reporting and alerting; it is based on VM extensions and does not rely on Log Analytics and Azure Automation.
  • Differentiate patch orchestration modes: ImageDefault (automated guest patching by the OS itself, such as unattended-upgrades), AutomaticByPlatform (automatic guest patching by Azure Security Orchestration), customer-managed schedules (AutomaticByPlatform + bypassPlatformSafetyChecksOnUserSchedule=true + maintenance configuration).
  • Use az vm assess-patches / install-patches and az maintenance to complete an assessment and installation, and handle restarts.
Prerequisite knowledge:Apt, software source in Lesson 1; systemd timers (apt-daily, unattended-upgrades) in Lesson 2. Importance:★★★★☆

What: Azure Update Manager does

  • Unified view: Windows and Linux update compliance for Azure VMs and Arc Servers (on-premises/other clouds), one pane view.
  • Assessment: On-demand (assessPatches) or Periodic Assessment (automatically checks for available updates every 24 hours).
  • Installation: Install immediately (installPatches, you can set the maximum duration, restart policy, classification, package name mask), or install within the plan window according to maintenance configuration (InGuestPatch range); available dynamic ranges (by subscription/RG/label, etc.) decide which machines to include at runtime.
  • Linux classification: Critical, Security, Other; packageNameMasksToInclude/Exclude can also be used (such as kernel*, redis-server).
  • Based on Azure native: ARM operation + RBAC, licensed by resource granularity; no additional charge for Azure VM (Arc Server is billed monthly, as shown on the pricing page). The old Azure Automation update management (which relied on the Log Analytics agent) was retired in 2024-08.

Why: Why not just rely on unattended-upgrades

unattended-upgrades(ImageDefault)Azure Update Manager
ScopeSingle machine, only security updates are installed by defaultUnified policy for hundreds of machines
VisibilityRequires login to view logsPortal/Resource Graph reports, alarms
Window and restart controlNative machine timer; additional configuration is required for restartMaintenance window + rebootSetting (IfRequired / NeverReboot / AlwaysReboot)
Cross-region security promotionNoneAutomaticByPlatform: Install in batches with "availability priority", during off-peak hours in the VM's time zone

How: Patch orchestration settings

Portal optionsAPI settings (Linux)Behavior
Image DefaultpatchMode=ImageDefaultInherit the mechanism in the image (Ubuntu: unattended-upgrades and apt-daily timer)
Azure Managed – Safe DeploymentpatchMode=AutomaticByPlatform, bypass…=falseAutomatic guest patching: the platform automatically installs Critical/Security during off-peak periods and in batches across regions
Customer Managed SchedulespatchMode=AutomaticByPlatform, bypassPlatformSafetyChecksOnUserSchedule=trueYour associated maintenance configuration determines when to install; unassociated plans will not be installed automatically (to prevent accidental upgrades)
Periodic evaluationassessmentMode=AutomaticByPlatformEvaluated every 24 hours

When: Production recommendations

  • The development/test environment is installed first (Tuesday), the production environment window is postponed (Saturday morning), and the label is used for dynamic range: patch-ring=dev|prod.
  • Exclude automatic update of the main version (packageNameMasksToExclude) for stateful services such as databases and Redis, and process them separately in the change window.
  • Kernel updates need to be restarted to take effect; Ubuntu prompts through /var/run/reboot-required, and needrestart will prompt for services that need to be restarted. Ubuntu Pro's Livepatch can patch some kernel vulnerabilities without rebooting.
  • The same machine only retains one "automatic installation" mechanism: When choosing to schedule installation by Update Manager, make sure that unattended-upgrades will not be installed secretly at other times, otherwise it will be difficult to track "who installed what".

Comparison with similar technologies

AzureAWS (Lesson 4)Open Source/Local
ServiceAzure Update ManagerSystems Manager Patch Managerunattended-upgrades / dnf-automatic / Ansible
WindowMaintain ConfigurationMaintenance Windowscron / systemd timer
BaselineClassification + Package name maskPatch BaselinesCustomized
Common misunderstandings① "Turn on periodic evaluation and it will be installed automatically" - the evaluation only checks, not installs. ② "The maintenance window must end within 2 hours if it lasts 2 hours" - the service will reserve time for restart, and some updates will be skipped if the window is too short (recommended ≥ 1.5 hours). ③ "Update Manager requires AMA" - No, it uses its own VM extension. ④ "Security updates will not damage the application" - this also needs to be verified in a test environment first.

Architecture Diagram: Control Path for Assessment and Installation

You/Plans/PolicyassessPatches · installPatchesMaintain Configuration + Dynamic Range Azure Update ManagerARM Operations · RBACThe results are written to Resource Graph vm-linux-lab walinuxagent → Patch extensionLinuxPatchExtension (automatically deployed by the platform) apt / dnf / zypperSelect updates by category and package name mask rebootSettingIfRequired / NeverReboot / AlwaysReboot Reports and AlertsResource Graph: patchassessmentresources / patchinstallationresourcesAzure Workbooks · Alert Rules
Figure 6-1 Update Manager calls the release package manager in the guest through the VM agent and patch extension

The name and deployment method of the patch extension are managed by the platform (visible on the "Extensions" page of the portal), and this lesson does not directly operate it.

Interaction: When will the patch be installed within a week?

Select the arrangement mode and maintenance window, and click "Play for a week". On the timeline: 🔍 cycle assessment, 📦 new security update release, 🛠 installation, 🔁 reboot.

Orchestration Mode
Maintenance Window (CMS only)
Restart settings

Common commands

# On-demand assessment and installation (REST: assessPatches / installPatches)
az vm assess-patches -g rg-linux-lab -n vm-linux-lab
az vm install-patches -g rg-linux-lab -n vm-linux-lab --maximum-duration PT1H \
  --reboot-setting IfRequired --classifications-to-include-linux Security Critical

# Switch to "Customer-managed plan" and turn on periodic assessment (ARM property path)
az vm update -g rg-linux-lab -n vm-linux-lab --set \
  osProfile.linuxConfiguration.patchSettings.patchMode=AutomaticByPlatform \
  osProfile.linuxConfiguration.patchSettings.assessmentMode=AutomaticByPlatform \
  osProfile.linuxConfiguration.patchSettings.automaticByPlatformSettings.bypassPlatformSafetyChecksOnUserSchedule=true
az vm show -g rg-linux-lab -n vm-linux-lab --query osProfile.linuxConfiguration.patchSettings

# Maintain configuration (every Saturday 02:00 Eastern, 3 hours) and association
az maintenance configuration create -g rg-linux-lab --resource-name mc-linux-weekly -l canadacentral \
  --maintenance-scope InGuestPatch --maintenance-window-duration "03:00" \
  --maintenance-window-recur-every "Week Saturday" \
  --maintenance-window-start-date-time "2026-11-21 02:00" --maintenance-window-time-zone "Eastern Standard Time" \
  --install-patches-linux-parameters classifications-to-include="Security" \
  --reboot-setting IfRequired --extension-properties InGuestPatchMode="User"
az maintenance assignment create -g rg-linux-lab -l canadacentral --resource-name vm-linux-lab \
  --resource-type virtualMachines --provider-name Microsoft.Compute --configuration-assignment-name mc-linux-weekly \
  --maintenance-configuration-id $(az maintenance configuration show -g rg-linux-lab --resource-name mc-linux-weekly --query id -o tsv)

# Resource Graph report
az graph query -q "patchassessmentresources | where type =~ 'microsoft.compute/virtualmachines/patchassessmentresults' | project vm=tostring(split(id,'/')[8]), status=properties.status, crit=properties.availablePatchCountByClassification.critical, sec=properties.availablePatchCountByClassification.security"

# Inside VM (Ubuntu)
apt list --upgradable 2>/dev/null | head
systemctl list-timers 'apt-*' --no-pager
cat /var/run/reboot-required 2>/dev/null; cat /var/run/reboot-required.pkgs 2>/dev/null
{
  "assessmentActivityId": "8c2f…",
  "availablePatches": [ { "classifications": ["Security"], "name": "openssl", "version": "3.5.…" }, … ],
  "criticalAndSecurityPatchCount": 4,
  "otherPatchCount": 9,
  "rebootPending": false,
  "startDateTime": "2026-11-17T03:20:11Z",
  "status": "Succeeded"
}

az graph requires the resource-graph extension (you will be prompted to install it for the first time). The parameter format of the maintenance configuration (especially --install-patches-linux-parameters and --maintenance-window-recur-every) is subject to az maintenance configuration create -h.

Experimental: Evaluate and install security patches, then schedule patches instead (~7 minutes)

Evaluate on-demand
source ~/linuxlab/azure/env.sh
az vm assess-patches -g $RG -n $VM --query "{status:status, critSec:criticalAndSecurityPatchCount, other:otherPatchCount, reboot:rebootPending}" -o table
Status     CritSec    Other    Reboot
---------  ---------  -------  --------
Succeeded  4          9        False
Only install Security + Critical, reboot if needed
az vm install-patches -g $RG -n $VM --maximum-duration PT1H --reboot-setting IfRequired \
  --classifications-to-include-linux Security Critical \
  --query "{status:status, installed:installedPatchCount, failed:failedPatchCount, reboot:rebootStatus}" -o table
Status     Installed    Failed    Reboot
---------  -----------  --------  -----------
Succeeded  4            0         NotNeeded
Verify that myapp is not affected
az vm run-command invoke -g $RG -n $VM --command-id RunShellScript \
  --scripts "systemctl is-active redis-server myapp; curl -s localhost:5000/healthz; tail -n 5 /var/log/apt/history.log" --query "value[0].message" -o tsv
Switch to customer-managed planning + periodic evaluation: Execute az vm update --set …, az maintenance configuration create With assignment create; In the portal Update Manager → Machine List confirm that the "Patching Business Process" shows Customer Managed Schedules and "Periodic Assessment" is enabled.
(Discussion) Relationship with unattended-upgrades:
az vm run-command invoke -g $RG -n $VM --command-id RunShellScript --scripts "apt-config dump | grep -E 'Unattended-Upgrade \"|Periodic::Unattended'; systemctl is-enabled apt-daily-upgrade.timer" --query "value[0].message" -o tsv

If you want to completely control the installation time by the plan, you can set APT::Periodic::Unattended-Upgrade "0"; (write /etc/apt/apt.conf.d/20auto-upgrades) and document this decision in a team document.

Case 1: Redis restart caused cache avalanche on Monday morning

Problem:unattended-upgrades upgraded redis-server at 06:00 on Monday and automatically restarted the service, cold cache hit the database. Method: Exclude redis* from automatic upgrade for the Redis host; change to a customer-managed plan and install it within the Saturday window; enable Redis persistence and warm up after the upgrade.

Case 2: Window is too short and kernel updates never install

Issue: Maintenance window is set to 1 hour and reports show kernel-related updates repeatedly "not installed". Reason: The service needs to reserve time for restarting, and updates that require restarting will be skipped when the window is insufficient. Method: Extend the window to 3 hours; put restart-sensitive machines into separate rings.

Case 3: Compliance audit requires "repair high-risk vulnerabilities within 30 days"

Method: Enable periodic evaluation; Resource Graph queries criticalAndSecurityPatchCount > 0 for machines whose evaluation time exceeds N days; use Azure Workbooks to make compliance reports, and automatically notify the person in charge with alarms.

Common errors and solutions

assess-patches failed: VM agent is not ready / Extension operation failed
az vm get-instance-view -g rg-linux-lab -n vm-linux-lab --query "instanceView.vmAgent.statuses[0]"

Fix: Ensure that walinuxagent is running and can access WireServer; VM must be running.

E: Could not get lock /var/lib/dpkg/lock-frontend. It is held by process 1234 (unattended-upgr)

Cause: unattended-upgrades is running, conflicting with the Update Manager installation.

ps -fp 1234; systemctl list-timers 'apt-*'

Repair: Waiting for completion; unified update mechanism (see principle page).

The schedule ran, but the machine showed "Not patched" / is not in the run list

Cause: The patch schedule of the VM is not Customer Managed Schedules (AutomaticByPlatform + bypass=true); or the dynamic range conditions (tag/RG) do not match at run time.

az vm show -g rg-linux-lab -n vm-linux-lab --query osProfile.linuxConfiguration.patchSettings
Myapp failed to start after the update: ModuleNotFoundError (python3 upgrade caused venv to become invalid)

Reason: The interpreter link of the old virtual environment failed after the release Python minor version was upgraded (rare in LTS, common in cross-version upgrades).

sudo python3 -m venv --clear /opt/myapp/venv && sudo /opt/myapp/venv/bin/pip install -r /opt/myapp/app/requirements.txt && sudo systemctl restart myapp
Command line operation questions
1. Only install updates with names matching openssl* without restarting.
az vm install-patches -g rg-linux-lab -n vm-linux-lab --maximum-duration PT30M --reboot-setting NeverReboot \
  --classifications-to-include-linux Other --package-name-masks-to-include "openssl*"
2. Determine whether a restart is needed in the Ubuntu VM and which packages are causing the problem.
[ -f /var/run/reboot-required ] && cat /var/run/reboot-required.pkgs || echo "no reboot needed"
Scenario Analysis Question
You manage 3 environments (dev/stage/prod) with a total of 60 Ubuntu VMs. It is required that prod be installed on dev for 5 days before installing the same batch of patches. How to do this with Update Manager?

All VMs are set to Customer Managed Schedules + periodic evaluation; create three maintenance configurations and dynamic ranges according to the tag patch-ring: dev Tuesday, stage Thursday, and prod next Sunday. In order to ensure that prod installs the "dev-verified batch", set maxPatchPublishDate (only install patches released before a certain date) or package name mask in the prod plan; combine Resource Graph report and alarm tracking failure.

Verified instructional video

▶
Azure Update Manager 2023 Edition — John Savill's Technical Training
English · Rewritten Update Manager: evaluation, planning, dynamic range, pricing (recorded in 2023, interface subject to change)
▶
Azure Update Management — John Savill's Technical Training
English · Old version of Automation Update management (retired), only used for understanding evolution and comparison

Official documentation

Video storyboard (about 75 seconds)

Shot 1 · 0–20s
Screen: Dashboard of 60 VMs, the magnifying glass icon automatically lights up every morning.
Narration: Periodic evaluation checks for available updates every 24 hours, only checking, not installing.
Shot 2 · 20–50s
Screen: The three windows of dev, stage, and prod on the calendar light up the wrench icons in sequence.
Narration: Use maintenance configurations and labels to divide machines into different batches and install them in their own windows.
Shot 3 · 50–75s
Screen: The restart icon appears after the kernel package is installed, and the window time bar leaves a restart margin.
Narration: Kernel updates require a restart. Allow sufficient time for maintenance windows and choose appropriate restart settings.
Or score ≥ 70% on the Quiz

Module 7 · Troubleshooting on the cloud: serial console, startup diagnosis and common faults

45:00 – 54:00 · There is no such thing as "walking to the computer room to plug in the monitor" on the cloud - what channels do you have when SSH cannot enter?
9 minutesBoot diagnostics · Serial Console · Run CommandSerial console requires password account★★★★★
Learning Objectives
  • Know what each of the four "out-of-band" channels depends on: Start Diagnostics (read-only: Serial Log + screenshot), Serial Console (interactive, relies on boot diagnostics + password account + VM Contributor), Run Command (relies on VM agent and outbound network), Offline Repair (az vm repair / ALAR, mounts a copy of the OS disk to the rescue VM).
  • Click "Symptoms → Channel → Command" to handle four typical types of failures: fstab missing nofail, disk full, sshd configuration error, NSG interception.
  • Network Watcher's IP flow verification and effective security rules will be used to determine "whether it is a network problem or a problem within the VM."
Prerequisites: Modules 2–4; Lesson 2’s systemd startup target, emergency/rescue mode, journalctl. Importance:★★★★★

What: Four out-of-band channels

ChannelWhat can it doDepends on Limitations
Boot diagnostics Boot diagnosticsView serial port output logs (kernel, systemd, cloud-init messages) and screenshots (Linux displays login prompt)VM Enable boot diagnostics (managed storage accounts are enabled by default on portal creation; CLI requires az vm boot-diagnostics enable)Read-only; stops writing when total managed storage reaches 1 GB; premium/ZRS storage accounts are not supported
Serial Console Serial ConsoleInteractive access ttyS0: login, entering GRUB, single-user mode, SysRqBoot diagnostics are enabled; there is a user with password in the VM; you have Virtual Machine Contributor or higherMainly used through the portal; paste length 2048 characters; disconnection will not log out automatically (setting TMOUT); the entered content will appear in the startup diagnostic log
Run CommandRun the script as root and return the output (RunShellScript)VM running, VM Agent OK, outbound 443 reachableOutput retains only last 4,096 bytes; one at a time; up to 90 minutes; non-interactive, non-cancelable; minimum ~20 seconds
Offline repair az vm repair / ALARHang a copy of the failed OS disk to the rescue VM for repair and then replace it; ALAR can automatically repair fstab, kernel, initrd, etc.vm-repair CLI extension; permission to create temporary resourcesRequires downtime; will temporarily create resource groups and VM (incurring fees)

Why: Why must it be prepared in advance

Most of these channels need to meet conditions in advance: startup diagnostics must be enabled first; the serial console must have a password account (pure key VM can be temporarily created with "Reset Password"); the GRUB menu and SysRq must be configured in advance before they can be used. The official recommendation is to "proactively ensure access to GRUB and sysrq." In addition, once the VM agent that Run Command relies on hangs up with the system (such as emergency mode), only the serial console and offline repair are left.

How: Four types of typical faults

FaultsSymptomsChannels that can still be usedFix points
fstab is missing nofail, the data disk is detached/UUID is wrongSSH timeout; serial log: Timed out waiting for device …, Dependency failed for /var/lib/redis, Welcome to emergency mode!, Give root password for maintenanceStart diagnostics, serial console, offline repair (Run Command is not available: the system is not multi-user)Serial console enters maintenance mode → Comment this line or add nofail → mount -a Verify → reboot -f; or az vm repair repair-button --button-command fstab
Root partition fullSSH login is slow or fails; apply 500; No space left on device; Extension installation failedRun Command (usually available), serial consoledf -h, du -xh Find a big one; journalctl --vacuum-size=200M, apt-get clean, clean the log; expand the OS disk if necessary
sshd configuration errorConnection refused (ssh is not started) or Permission denied (if it is set by mistake) PubkeyAuthentication no)Run Command, Serial Console, VMAccess (az vm user reset-ssh)sshd -t Find the wrong line → Remove the wrong sshd_config.d/*.conf → Restart ssh (Ubuntu uses ssh.socket socket activation by default, and the socket must be adjusted synchronously when changing the port)
NSG interceptionSSH timeout, but the VM runs normally and the serial log is normalAll Channels within the VM are available - the problem is outside the VMaz network watcher test-ip-flow Locate interception rules; az network nic list-effective-nsg Look at the combined results of subnet + NIC two-level NSG

When: Troubleshooting sequence (outside first, inside first, read first then write)

  1. VM status and resource health: az vm get-instance-view Look at the power status and agent status; the portal "Resource Operation Status" looks at platform events.
  2. Network: Timeout (timeout) may be network/NSG; rejection (refused) indicates that the packet arrived at the VM but the port was not monitored.
  3. Startup diagnostics: Read the last 100 lines of the serial log to determine whether it is stuck in the startup phase.
  4. Run Command: The fastest non-interactive method when the system is started.
  5. Serial console: When the system is not fully started and interaction is required.
  6. Offline repair/redeployment: az vm repair; when there is a platform host problem az vm redeploy (moving to a new host, temporary disk data is lost).

Comparison to similar technologies

AzureAWS (Lesson 4)On-premises (Lessons 1–2)
Read-only console logStart diagnostic serial logGet system log / screenshotVirtual machine window
Interactive consoleSerial consoleEC2 Serial ConsoleHyper-V/VirtualBox Console
Remote ExecutionRun CommandSSM Run Command—
Offline Repairaz vm repair / ALARMount root volume to rescue instanceMount ISO
Common misunderstandings① "Run Command can be used at any time" - when the system is stuck in emergency mode and the VM agent is not started, Run Command will time out. ② "Serial console can be logged in with SSH key" - only username + password. ③ "Restarting can solve everything" - fstab error remains the same no matter how many times it is restarted. ④ "Redeployment (redeploy) is the same as restarting" - redeploy will be moved to a new host, the temporary disk data will be lost, and the dynamic IP may be replaced.

Decision chart: When SSH cannot connect

ssh labadmin@IP failed Connection timed outThe package did not arrive at sshd Connection refusedArrived at the VM, 22 no monitoring Permission deniedsshd running, authentication failed IP flow verificationNSG Rules → Fix Boot diagnostic logStuck on startup? Run Commandsshd -t · Log Key/role/AllowUsersaz vm user update · RBAC emergency mode / kernel panicSerial console → single user; or az vm repair (ALAR) The system is normal but sshd is bad/the disk is fullRun Command repair · reset-ssh
Figure 7-1 First distinguish "Network/Service/Authentication/" based on the error text "Start" four types of questions, then select the channel

Interactive simulator: Which channel can still be used under this fault?

Select a fault, and the simulator will try each channel in turn and display the results and reasons, and finally give a recommended repair path.

Select a fault scenario.

Common commands

#  - Status and Boot Diagnostics -
az vm get-instance-view -g rg-linux-lab -n vm-linux-lab --query "instanceView.{power:statuses[1].displayStatus, agent:vmAgent.statuses[0].displayStatus}" -o table
az vm boot-diagnostics enable -g rg-linux-lab -n vm-linux-lab          # Managed Storage
az vm boot-diagnostics get-boot-log -g rg-linux-lab -n vm-linux-lab | tail -n 60
az vm boot-diagnostics get-boot-log-uris -g rg-linux-lab -n vm-linux-lab   # Temporary URI for screenshots and logs

#  - Serial Console (Portal: VM → Help → Serial Console; CLI requires serial-console Extension) ——
az vm user update -g rg-linux-lab -n vm-linux-lab -u labadmin -p '<strong-password>'   # Prepare password for serial console
az serial-console connect -g rg-linux-lab -n vm-linux-lab

# —— Run Command ——
az vm run-command invoke -g rg-linux-lab -n vm-linux-lab --command-id RunShellScript \
  --scripts "df -h /; sshd -t; systemctl --failed --no-pager" --query "value[0].message" -o tsv

# —— VMAccess / Offline Repair / Platform Operations ——
az vm user reset-ssh -g rg-linux-lab -n vm-linux-lab
az extension add -n vm-repair
az vm repair repair-button --button-command 'fstab' --verbose -g rg-linux-lab -n vm-linux-lab
az vm repair create -g rg-linux-lab -n vm-linux-lab --verbose        # Manual: Build rescue VM and mount OS disk copy
az vm repair restore -g rg-linux-lab -n vm-linux-lab --verbose       # Replace the repaired OS Disk
az vm redeploy -g rg-linux-lab -n vm-linux-lab                        # Move to new host (temporary disk data is lost)

# —— Network ——
az network watcher test-ip-flow -g rg-linux-lab --vm vm-linux-lab --direction Inbound --protocol TCP \
  --local 10.0.0.4:22 --remote 203.0.113.10:50000
az network nic list-effective-nsg -g rg-linux-lab -n vm-linux-labVMNic --query "value[].effectiveSecurityRules[?destinationPortRange=='22-22']"

# —— Within VM ——
journalctl -b -p err --no-pager | tail -n 30
systemctl --failed
sudo sshd -t
df -h; sudo du -xh / --max-depth=2 2>/dev/null | sort -h | tail -n 15
sudo journalctl --vacuum-size=200M
[  TIME  ] Timed out waiting for device dev-disk-by\x2duuid-3f1c….device - /dev/disk/by-uuid/3f1c….
[DEPEND] Dependency failed for var-lib-redis.mount - /var/lib/redis.
[DEPEND] Dependency failed for local-fs.target - Local File Systems.
You are in emergency mode. After logging in, type "journalctl -xb" to view
system logs, "systemctl reboot" to reboot, or "exit" to continue bootup.
Give root password for maintenance
(or press Control-D to continue):
Access    RuleName
--------  ------------------------------------------
Deny      securityRules/deny-all-ssh-lab

emergency mode prompt text is slightly different depending on the systemd version (the official document example is "Welcome to emergency mode!…"). Ubuntu's root account is locked by default. At this time, the prompt may be "Cannot open access to console, the root account is locked". You need to edit the kernel parameters through GRUB to enter (the official "Serial Console Access to GRUB and Single-User Mode" document gives steps according to the release version).

Experiment: Deliberately break it and then save it (about 9 minutes)

Only do it on the experimental VMThe following steps will make the VM temporarily unavailable for login. First confirm that startup diagnostics are enabled (module 2 executed az vm boot-diagnostics enable).
Scenario 1: NSG interception (first outside then inside)
source ~/linuxlab/azure/env.sh
az network nsg rule create -g $RG --nsg-name ${VM}NSG -n deny-all-ssh-lab --priority 100 \
  --direction Inbound --access Deny --protocol Tcp --destination-port-ranges 22 -o none
IP=$(az vm show -d -g $RG -n $VM --query publicIps -o tsv); PRIV=$(az vm show -d -g $RG -n $VM --query privateIps -o tsv)
timeout 10 ssh -o ConnectTimeout=5 $ADMIN@$IP true || echo "SSH timeout"
az network watcher test-ip-flow -g $RG --vm $VM --direction Inbound --protocol TCP --local $PRIV:22 --remote $(curl -s https://api.ipify.org):50000 -o table
az network nsg rule delete -g $RG --nsg-name ${VM}NSG -n deny-all-ssh-lab

When you use Network Watcher for the first time, this area in the subscription will automatically create NetworkWatcherRG (free).

Scenario 2: sshd configuration error → Use Run Command to repair
az vm run-command invoke -g $RG -n $VM --command-id RunShellScript \
  --scripts "echo 'PermitRootLogin maybe' > /etc/ssh/sshd_config.d/99-broken.conf; systemctl restart ssh; systemctl is-active ssh" --query "value[0].message" -o tsv
ssh -o ConnectTimeout=5 $ADMIN@$IP true || echo "SSH failed"
az vm run-command invoke -g $RG -n $VM --command-id RunShellScript \
  --scripts "sshd -t; rm -f /etc/ssh/sshd_config.d/99-broken.conf; sshd -t && systemctl restart ssh && systemctl is-active ssh" --query "value[0].message" -o tsv
[stdout]
failed
SSH failed
[stdout]
active
[stderr]
/etc/ssh/sshd_config.d/99-broken.conf line 1: unsupported option "maybe".
Scenario 3: fstab is missing nofail + separate data disk → emergency mode
# 1) Remove nofail (simulate "copying online tutorials")
az vm run-command invoke -g $RG -n $VM --command-id RunShellScript \
  --scripts "sed -i 's/defaults,nofail/defaults/' /etc/fstab; grep redis /etc/fstab" --query "value[0].message" -o tsv
# 2) Prepare a password for the serial console, then deallocate, detach the data disk, and start
az vm user update -g $RG -n $VM -u $ADMIN -p 'Lab-Pa55w0rd-ChangeMe!' -o none
az vm deallocate -g $RG -n $VM
az vm disk detach -g $RG --vm-name $VM -n ${VM}-data01
az vm start -g $RG -n $VM --no-wait; sleep 150
az vm boot-diagnostics get-boot-log -g $RG -n $VM | grep -E "Timed out|Dependency failed|emergency" | head
Rescue method A: Serial console(Portal → vm-linux-lab → Help → Serial console). When Ubuntu root is locked, restart the VM in the console, press e in the GRUB menu, add linux line (or follow the official single-user mode documentation), and systemd.unit=rescue.target at the end of the labadmin After logging in with password:
sudo sed -i '/\/var\/lib\/redis/ s/defaults/defaults,nofail/' /etc/fstab
sudo findmnt --verify
sudo systemctl daemon-reload && sudo reboot -f
Rescue method B: ALAR offline repair(no interaction required)
az extension add -n vm-repair 2>/dev/null; az extension update -n vm-repair
az vm repair repair-button --button-command 'fstab' --verbose -g $RG -n $VM

ALAR will temporarily create the rescue resource group and VM, back up and comment out the data disk entries that are not necessary for startup, and automatically delete the temporary resources after completion. Remember to add back the nofail entry after repair.

Recover the data disk and verify
az vm disk attach -g $RG --vm-name $VM -n ${VM}-data01 --lun 0
az vm run-command invoke -g $RG -n $VM --command-id RunShellScript \
  --scripts "mount -a; findmnt /var/lib/redis; systemctl restart redis-server myapp; curl -s localhost:5000/" --query "value[0].message" -o tsv
az vm user update -g $RG -n $VM -u $ADMIN -p "$(openssl rand -base64 24)" -o none   # Change the experimental password to a random value
Scenario 4 (optional): Disk full
az vm run-command invoke -g $RG -n $VM --command-id RunShellScript \
  --scripts "fallocate -l \$(( \$(df --output=avail -B1 / | tail -1) - 50*1024*1024 )) /var/tmp/fill.bin; df -h /; curl -s -o /dev/null -w '%{http_code}\n' localhost:5000/" --query "value[0].message" -o tsv
az vm run-command invoke -g $RG -n $VM --command-id RunShellScript \
  --scripts "du -xh /var --max-depth=2 2>/dev/null | sort -h | tail -5; rm -f /var/tmp/fill.bin; df -h /" --query "value[0].message" -o tsv

Case 1: 30 VMs cannot start after routine patching

Problem: fstab pair in image template The NFS share does not have nofail/_netdev, and the NFS server happened to be under maintenance when the patch was restarted. Method: Use az vm repair repair-button --button-command fstab for batch repair; the template is changed to _netdev,nofail,x-systemd.automount; Policy checks the new image.

Case 2: The log fills up the root partition, and the monitoring agent also fails

Problem: The application debug log fills up /, the AMA local cache cannot be written, and the alarm is not issued. Method: Run Command to clean and journalctl --vacuum-size; set SystemMaxUse= for journald, put the application log on the data disk and configure logrotate; set an indicator alarm for "% Used Space > 85%" in Azure Monitor (from another path, not just syslog).

Case 3: All members lost contact after changing the SSH port

Problem: On Ubuntu, only Port 2222 of sshd_config was changed, and NSG also released 2222, but still could not connect. Reason: Ubuntu uses ssh.socket socket activation, and the listening port is determined by the socket unit. Method:Run Command executes systemctl daemon-reload && systemctl restart ssh.socket (the new version of sshd-socket-generator will generate a listening port according to the configuration); test the VM drill before making changes, and keep the serial console available.

Common errors and solutions

Serial console: "The serial console requires boot diagnostics to be enabled" / black screen with no output

Repair:az vm boot-diagnostics enable; press several times after connecting Enter; the custom image needs to have console=ttyS0 in the kernel parameters and run serial-getty@ttyS0.

Serial console login: Login incorrect (only SSH key is configured)
az vm user update -g rg-linux-lab -n vm-linux-lab -u labadmin -p ''

The serial console only supports username + password; change back to a random password or delete the password after use.

Run Command: “Run command extension execution is pending” / Timeout and no output

Cause: The VM is not fully started (emergency mode) or the VM agent is unavailable, and outbound 443 is blocked (the script may be executed but the results cannot be returned).

az vm get-instance-view -g rg-linux-lab -n vm-linux-lab --query "instanceView.vmAgent.statuses[0]"

Fix: Use serial console instead or offline repair; Linux side log is in /var/log/azure/run-command/handler.log.

(The entity was not found in this Azure location) az vm run-command invoke --command-id RunShellscript

Cause: --command-id spelling/case error, available values ​​for Linux are RunShellScript, ifconfig.

az vm repair create: failed to create repair VM (quota/image/encrypted disk)

Cause: The region vCPU quota is insufficient, or the OS disk has ADE encryption enabled and requires additional parameters.

Repair: Release the quota; follow the encryption parameter instructions of az vm repair create -h; or follow the official "Manually mount the OS disk to the rescue VM + chroot" step.

Command line operation questions
1. Without logging into the VM, check the recent systemd failure information in the serial log.
az vm boot-diagnostics get-boot-log -g rg-linux-lab -n vm-linux-lab | grep -E "FAILED|Dependency failed|emergency" | tail
2. Use Run Command to check the sshd configuration syntax and list the failed units.
az vm run-command invoke -g rg-linux-lab -n vm-linux-lab --command-id RunShellScript --scripts "sshd -t; systemctl --failed --no-pager" --query "value[0].message" -o tsv
Scenario analysis question
Early morning alarm: myapp is unavailable. SSH times out, Run Command hangs, and the portal shows the VM is running and the agent status is "Not Ready". What's next for you?

SSH Timeout + Agent Not Ready means the system may not be fully started (or there may be a problem with the network stack). ① Look at startup diagnostic screenshots and serial logs (whether emergency mode, kernel panic, file system check); ② If it is an fstab/file system problem, use the serial console to enter maintenance mode to repair, or az vm repair repair-button --button-command fstab; ③ If the log shows that the system is normal, check NSG/routing (IP flow verification) and VM internal firewall; ④ If you are unable to determine and you suspect a host problem, consider az vm redeploy. Later additions: data disk nofail, account with broken password, and disk usage alarm.

Verified instructional videos

No English video verified by oEmbed specifically demonstrating Azure serial console repairing Linux fstab was found. The following are verified relevant videos; the troubleshooting steps are subject to official documents and experiments in this lesson.

▶
Examination of options to connect to Azure VMs — John Savill's Technical Training
English · Various connection channels and their dependencies, helping to understand "which road is still open"
▶
Azure Master Class v3 - Part 7 - VMs and VMSS — John Savill's Technical Training
English · Content related to VM maintenance, redeployment and availability

Official documents

Video storyboard script (about 90 Seconds)

Lineage 1 · 0–20s
Screen: ssh is stuck in the terminal; the camera zooms out, and there are four doors outside the VM: startup diagnostics, serial console, Run Command, and offline repair.
Narration: When SSH cannot enter, there are four out-of-band channels on the cloud, each with its own prerequisites.
Shot 2 · 20–50s
Screen: Boot diagnostic log scrolls to "Dependency failed for /var/lib/redis" and "emergency mode".
Narration: Read the startup diagnostic log first. When you see the dependency failure and emergency mode, you know it is a problem with fstab.
Shot 3 · 50–90s
Screen: Enter GRUB and rescue mode in the serial console, edit fstab and add nofail, system restart, SSH recovery.
Narration: Use the serial console to enter rescue mode, add nofail, and then restart. Remember next time: the data disk must be written nofail.
Or score ≥ 70% on the Quiz

Module 8 · Cost, Cleanup and Self-Test

54:00 – 60:00 · "Stop" does not mean "no billing"; the experiment is completed only when the resource group is deleted
6 MinutesStopped ≠ DeallocatedInteractive Troubleshooting Tree★★★★☆
Learning Objectives
  • List the billing items for this lesson's lab (Compute, Managed Disk, Public IP, Log Analytics, Bastion, Snapshot, Outbound Traffic) and know which ones are still billed after "deallocation".
  • Distinguish between shutdown in the OS (Stopped, still charged according to calculation) and az vm deallocate (Stopped (deallocated), no charge calculated); automatic shutdown, label and budget will be configured.
  • Clean rg-linux-lab safely and thoroughly, and use the interactive troubleshooting tree to review all fault types in this lesson.
Prerequisite knowledge:Modules 1–7. Importance:★★★★☆

What: The billing structure of this lesson's experiment

ResourcesBilling methodAfter deallocationWhether this lesson is created
VM calculation (Standard_D2ads_v5)Running time (in seconds, hourly price)No billingYes
OS disk/data disk (managed disk)According to provisioned capacity (independent of usage)Continue billingYes (30 + 16 GiB)
Standard Public IPHourlyContinue billing (static allocation)Yes
Log AnalyticsBy import GB (+ retention fee beyond free retention period)No new data generatedYes
Azure Bastion(Standard)By hour (billed as deployed) + egress trafficNot related to VM, Billed until deletedOptional
SnapshotBased on used capacityContinue billingOptional
Boot diagnostics (managed storage)Currently not billed—Yes
Update Manager(Azure VM)No additional charge—Yes
Ubuntu non-Pro imageFree (RHEL, Ubuntu Pro excluded)—Yes

Why: Stopped and Stopped (deallocated)

  • Execute sudo shutdown -h now or az vm stop in the VM: status Stopped, the VM still occupies host resources, and continues to be billed by calculation.
  • az vm deallocate or portal "Stop" button: status Stopped (deallocated), host resources are released, computing charges are no longer charged; dynamic public IP will be released (Standard SKU public IP is static, reserved and billed); temp disk data is lost (Module 3).

How: Means of cost control

MeansCommand/LocationInstructions
Automatic shutdownaz vm auto-shutdown -g … -n … --time 1900Deallocation is scheduled every day (time is UTC), suitable for development/experimentation VM
Tag--tags course=linux-8h owner=…Cost analysis is grouped by tag; it is also convenient to retrieve resources
Budget and AlarmPortal Cost Management → BudgetSending emails/triggering action groups when thresholds are exceeded
Appropriate specifications and disksModules 1, 3Standard SSD for experimentation; production will go to Premium
Reserved Instances / Savings PlanPortalSignificant price reductions for long-term stable loads (1 year/3 year commitment)
Log volumeDCR Level, table planModule 5

When: Clean list

  1. Confirm that there is no data that needs to be retained (snapshot/export first if necessary - note that snapshots are also billed and placed in other resource groups).
  2. az group delete -n rg-linux-lab --yes: Delete VM, disk, NIC, public IP, NSG, VNet, workspace, DCR, maintenance configuration, role assignments for this scope.
  3. Check whether there are any residues in az resource list --tag course=linux-8h (such as snapshots and Bastion in other resource groups).
  4. NetworkWatcherRG is a subscription-level shared resource, free and can be reserved.
  5. Local: Delete the entries and certificate directories generated by az ssh config in ~/.ssh/config.

Comparison with similar technologies

AzureAWS (Lesson 4)
Stop not billeddeallocatestop (EBS still billed)
One-click cleanupDelete resource groupNo resource group concept: cleanup by tag/CloudFormation stack
Public IPStandard public IP By the hourPublic IPv4 by the hour
Common misunderstandings① "It doesn't cost money when the VM is shut down" - shutdown within the OS is still billed by calculation, and the disk and public IP are always billed. ② "Deleting a VM will delete its disk" - CLI defaultwill notdelete OS/data disk, NIC, public IP (unless the delete option is set when creating), deleting the resource group is the cleanest way. ③ "Bastion is only billed when connected" - deployment is billed by the hour.

VM power state and billing

RunningCompute ✓ Disk ✓ IP ✓ StoppedCompute ✓ (still billed!) Disk ✓ Stopped (deallocated)Compute ✗ Disk ✓ Std IP ✓ The resource group has been deletedAll ✗ shutdown / az vm stop az vm deallocate deallocate az group delete
Figure 8-1 Only "deallocate" will stop the calculation and billing; only "delete" will stop all billing

Interaction: Experimental Cost Estimator

Please fill in the unit price after querying the actual price of canadacentral from Azure Price Calculator; the default value is only a example number for demonstration purposes, not a quotation.

VM unit price (USD/hour)
Hours of operation
2 h
Number of days retained after deallocation
0 Days
Total monthly disk price (USD/month, 30+16 GiB)
Public IP (USD/hour)
Log import (GB) × unit price (USD/GB)

Common commands

# Status related to billing
az vm list -d -g rg-linux-lab --query "[].{name:name, power:powerState}" -o table
az vm deallocate -g rg-linux-lab -n vm-linux-lab
az vm start -g rg-linux-lab -n vm-linux-lab
az vm auto-shutdown -g rg-linux-lab -n vm-linux-lab --time 2300        # UTC 23:00 (approximately 18:00/19:00 in Toronto)
# Find all resources for this lesson
az resource list --tag course=linux-8h --query "[].{name:name, type:type, rg:resourceGroup}" -o table
az resource list -g rg-linux-lab --query "[].{name:name, type:type}" -o table
# Cost (requires Cost Management Read permission; data is delayed)
az consumption usage list --start-date 2026-11-16 --end-date 2026-11-18 \
  --query "[?contains(instanceName,'linux-lab')].{res:instanceName, cost:pretaxCost, cur:currency}" -o table
# Cleaning
az network bastion delete -g rg-linux-lab -n bas-linux-lab 2>/dev/null
az group delete -n rg-linux-lab --yes --no-wait
az group wait --deleted -n rg-linux-lab
az group exists -n rg-linux-lab
Name          Power
------------  ------------------
vm-linux-lab  VM deallocated
false

The availability and fields of az consumption usage list depend on the subscription type (some subscription types require the Cost Management portal or az costmanagement), and expense data is often delayed by several hours.

Experiment: deallocate, find all resources, clean up completely (about 5 minutes)

Comparison of two stops
source ~/linuxlab/azure/env.sh
az vm stop -g $RG -n $VM; az vm show -d -g $RG -n $VM --query powerState -o tsv
az vm deallocate -g $RG -n $VM; az vm show -d -g $RG -n $VM --query powerState -o tsv
VM stopped
VM deallocated

az vm stop will prompt "… will continue to be billed…" - this is the point of this module.

List all resources with course tags and resources in the resource group
az resource list -g $RG --query "[].{name:name,type:type}" -o table
az resource list --tag course=linux-8h -o table
Name                         Type
---------------------------  ---------------------------------------------
vm-linux-labVNET             Microsoft.Network/virtualNetworks
vm-linux-labNSG              Microsoft.Network/networkSecurityGroups
vm-linux-labPublicIP         Microsoft.Network/publicIPAddresses
vm-linux-labVMNic            Microsoft.Network/networkInterfaces
vm-linux-lab                 Microsoft.Compute/virtualMachines
vm-linux-lab_OsDisk_1_…      Microsoft.Compute/disks
vm-linux-lab-data01          Microsoft.Compute/disks
law-linux-lab                Microsoft.OperationalInsights/workspaces
dcr-linux-lab                Microsoft.Insights/dataCollectionRules
mc-linux-weekly              Microsoft.Maintenance/maintenanceConfigurations
…
If you want to keep the VM before continuing with Lesson 4: Set up automatic shutdown
az vm auto-shutdown -g $RG -n $VM --time 2300
Delete the resource group and verify
az group delete -n $RG --yes
az group exists -n $RG
az resource list --tag course=linux-8h -o table      # should be empty
grep -n "vm-linux-lab" ~/.ssh/config 2>/dev/null   # If you have used az ssh config: find the corresponding Host segment and delete it manually
false

Case 1: A "shutdown" GPU in the end-of-month bill VM

Problem: The engineer executed shutdown in the VM, thinking that it would no longer be billed. As a result, the GPU unit price was billed for the entire month. Practice: Team standard "Always use deallocate to stop VMs"; enable automatic shutdown for development subscriptions; check the "Shut down or adjust underutilized VMs" recommendation in Azure Advisor; budget alarm thresholds 50%/80%/100%.

Case 2: The disk is still being charged after deleting the VM

Problem: The script used az vm delete to clean the test VM, and after a few months hundreds of orphaned disks and public IPs were found. Method: Experiment with one resource group each time and end the deletion; or set --os-disk-delete-option Delete --data-disk-delete-option Delete --nic-delete-option Delete when creating a VM; use Resource Graph to regularly query the disk with diskState == 'Unattached'.

Case 3: Log cost exceeds VM cost

Problem: A small-sized VM costs tens of dollars per month, but Log Analytics costs hundreds. What to do: See Module 5: Converging DCR levels, switching to a basic log layer for access logs, and setting daily caps.

Interactive troubleshooting tree (covering all modules of this course)

Select step by step starting from the symptoms, and the leaf nodes give diagnostic commands and repair directions.

Common errors related to cleanup

(ScopeLocked) The scope '/subscriptions/…/resourceGroups/rg-linux-lab' cannot perform delete operation because following scope(s) are locked
az lock list -g rg-linux-lab -o table
az lock delete -g rg-linux-lab -n 
The resource group has been deleted for a long time and is still Deleting/failed: InUseSubnetCannotBeDeleted

Reason: The subnet is still being used by resources in other resource groups (such as those created elsewhere) NIC, Bastion, private endpoint) used.

az network vnet subnet show -g rg-linux-lab --vnet-name vm-linux-labVNET -n vm-linux-labSubnet --query ipConfigurations[].id
(AuthorizationFailed) does not have authorization to perform action 'Microsoft.Resources/subscriptions/resourcegroups/delete'

Cause: Contributor/Owner on the resource group is missing. Please ask an authorized administrator to delete it, or apply for temporary permission (PIM).

Command line operation questions
1. List all unattached managed disks in the subscription.
az disk list --query "[?diskState=='Unattached'].{name:name, rg:resourceGroup, size:diskSizeGB}" -o table
2. Delete the resource group and wait for confirmation that it does not exist.
az group delete -n rg-linux-lab --yes && az group exists -n rg-linux-lab
Scenario analysis question
You want to do an experiment for 1 hour every night for two consecutive weeks. How can you minimize the cost without rebuilding the VM?

Every time you end az vm deallocate (or set up automatic shutdown), you only pay for the disk and Standard public IP; you can also use no public IP and use az ssh vm + Bastion Developer (if the region is available) or temporary public IP; DCR downgrade or delete the DCR association between experiments; do not deploy Bastion Standard; delete the resource group after two weeks. If you can use cloud-init to rebuild within 2 minutes every time, "deleting the group after completion" will be more economical and cleaner.

Verified instructional video

▶
Azure Cost Optimization Deep Dive — John Savill's Technical Training
English · Cost analysis, reservation, savings plan, adjustment of specifications and shutdown

Official document

Video storyboard script (about 60 seconds)

Shot 1 · 0–20s
Screen: The VM icon changes from green to yellow (Stopped), the billing counter is still jumping; then to blue (Deallocated), the calculation counter stops, and the disk counter continues.
Narration: When the system is shut down, the computing fee will still be charged; the calculation and billing will stop when the system is deallocated, but the disk and public IP are still billed.
Shot 2 · 20–60s
Screen: The resource group folder is dragged into the recycle bin, the VM, disk, IP, and workspace inside disappear together, and the counter returns to zero.
Narration: The experiment is over, delete the entire resource group, and use labels to confirm that nothing is missing.
Or score ≥ 70% on the Quiz

Command cheat sheet

All key commands in this lesson, grouped by scenario (unified variables: RG=rg-linux-lab · LOC=canadacentral · VM=vm-linux-lab · ADMIN=labadmin)
Images and specifications (M1)
az vm image list -p Canonical -f ubuntu-26_04-lts -l $LOC --all -o table
az vm image show --urn Canonical:ubuntu-26_04-lts:server:latest -l $LOC
az vm list-skus -l $LOC --size Standard_D2ads_v5 -o table
az vm list-usage -l $LOC -o table
az vm image terms accept --urn P:O:S:latest
Creation and cloud-init (M2)
az vm create -g $RG -n $VM --image $IMAGE --size $SIZE \
  --admin-username $ADMIN --ssh-key-values ~/.ssh/id_ed25519.pub \
  --custom-data cloud-init.yaml --assign-identity --public-ip-sku Standard
cloud-init status --wait --long
cloud-init analyze show
sudo cloud-init schema --system --annotate
sudo tail /var/log/cloud-init-output.log
sudo tail /var/log/waagent.log
Extensions (M2/M4/M5)
az vm extension list -g $RG --vm-name $VM -o table
az vm extension set -g $RG --vm-name $VM --publisher Microsoft.Azure.Extensions --name CustomScript --settings '{"commandToExecute":"…"}'
az vm extension set -g $RG --vm-name $VM --publisher Microsoft.Azure.ActiveDirectory --name AADSSHLoginForLinux
az vm extension set -g $RG --vm-name $VM --publisher Microsoft.Azure.Monitor --name AzureMonitorLinuxAgent --enable-auto-upgrade true
az vm extension delete -g $RG --vm-name $VM -n 
Disk (M3)
az vm disk attach -g $RG --vm-name $VM --name $VM-data01 --new --size-gb 16 --sku StandardSSD_LRS --lun 0
readlink -f /dev/disk/azure/scsi1/lun0     # NVMe: sudo azure-nvme-id
sudo parted /dev/sdc --script mklabel gpt mkpart data ext4 0% 100%
sudo mkfs.ext4 -L data /dev/sdc1; sudo blkid /dev/sdc1
UUID=…  /var/lib/redis  ext4  defaults,nofail  0  2
findmnt --verify && sudo mount -a
az disk update -g $RG -n $VM-data01 --size-gb 32; sudo growpart /dev/sdc 1; sudo resize2fs /dev/sdc1
Identity and Access (M4)
az vm identity assign -g $RG -n $VM
az role assignment create --role "Virtual Machine Administrator Login" --assignee-object-id <id> --scope <rgId>
az extension add --name ssh
az ssh vm -g $RG -n $VM
az ssh config --file ~/.ssh/config -g $RG -n $VM
curl -s --noproxy "*" -H Metadata:true "http://169.254.169.254/metadata/identity/oauth2/token?api-version=2018-02-01&resource=https%3A%2F%2Fmanagement.azure.com%2F"
az vm user update -g $RG -n $VM -u $ADMIN --ssh-key-value "$(cat ~/.ssh/id_ed25519.pub)"
az network bastion ssh -g $RG -n bas-linux-lab --target-resource-id <vmId> --auth-type AAD
Monitoring (M5)
az monitor log-analytics workspace create -g $RG -n law-linux-lab -l $LOC
az monitor data-collection rule create -g $RG -n dcr-linux-lab -l $LOC --rule-file dcr.json
az monitor data-collection rule association create --name dcra --rule-id <dcrId> --resource <vmId>
az monitor log-analytics query -w <customerId> --analytics-query 'Syslog | take 10'
systemctl status azuremonitoragent; ss -ltn | grep 28330
logger -p daemon.warning -t myapp "test"
Patching (M6)
az vm assess-patches -g $RG -n $VM
az vm install-patches -g $RG -n $VM --maximum-duration PT1H --reboot-setting IfRequired --classifications-to-include-linux Security Critical
az vm update -g $RG -n $VM --set osProfile.linuxConfiguration.patchSettings.patchMode=AutomaticByPlatform …
az maintenance configuration create … --maintenance-scope InGuestPatch
az maintenance assignment create …
cat /var/run/reboot-required.pkgs
Troubleshooting (M7)
az vm get-instance-view -g $RG -n $VM --query instanceView.vmAgent.statuses[0]
az vm boot-diagnostics enable -g $RG -n $VM
az vm boot-diagnostics get-boot-log -g $RG -n $VM | tail -60
az vm run-command invoke -g $RG -n $VM --command-id RunShellScript --scripts "sshd -t; df -h"
az vm user reset-ssh -g $RG -n $VM
az vm repair repair-button --button-command 'fstab' -g $RG -n $VM
az network watcher test-ip-flow -g $RG --vm $VM --direction Inbound --protocol TCP --local 10.0.0.4:22 --remote <ip>:50000
az vm redeploy -g $RG -n $VM
Cost & Cleanup (M8)
az vm deallocate -g $RG -n $VM          # Not az vm stop!
az vm auto-shutdown -g $RG -n $VM --time 2300
az resource list --tag course=linux-8h -o table
az disk list --query "[?diskState=='Unattached'].name" -o tsv
az group delete -n $RG --yes; az group exists -n $RG
Critical Paths & Endpoints
169.254.169.254IMDS (metadata, userData, managed identity token), requires Metadata: true
168.63.129.16WireServer: Readiness Report, Extended Goal Status
/var/log/cloud-init*.logcloud-init log
/var/log/waagent.log, /var/log/azure/VM agent and extension log
/dev/disk/azure/Azure disk stable link (resource, scsi1/lunN)
127.0.0.1:28330AMA receive rsyslog forward

Capstone Lab and Final Knowledge Check

Delivery of a "production-ready" myapp from scratch VM: automatic deployment, persistent data, keyless login, observable, patchable, rescueable, cleanable
About 45 minutesIncur charges, clean up after completion

Scenario

The team needs to Migrate myapp that was verified locally to Azure. Requirements: Anyone needs only one command and a cloud-init file to rebuild the environment; Redis data is placed on a separate data disk; personnel only use Entra ID to log in; application logs and indicators enter Log Analytics; security patches are automatically installed every Saturday; when someone changes fstab, it can be restored within 10 minutes; no billing resources are left after the experiment.

Environment and Selection: Create rg-linux-lab (canadacentral, with course/owner tag); confirm Canonical:ubuntu-26_04-lts:server:latest and Standard_D2ads_v5 Available (module 1).
One-time automatic deployment: Based on the cloud-init.yaml of module 2, added disk_setup / fs_setup / mounts to allow cloud-init to automatically deploy the The LUN 0 data disk is formatted and mounted to nofail (tip: use /var/lib/redis using /dev/disk/azure/scsi1/lun0 for the device; use --data-disk-sizes-gb 16 to create the data disk at the same time when creating a VM).
Reference fragment
disk_setup:
  /dev/disk/azure/scsi1/lun0:
    table_type: gpt
    layout: true
    overwrite: false
fs_setup:
  - device: /dev/disk/azure/scsi1/lun0
    partition: 1
    filesystem: ext4
    label: redisdata
mounts:
  - ["/dev/disk/azure/scsi1/lun0-part1", "/var/lib/redis", "ext4", "defaults,nofail", "0", "2"]
runcmd:
  - [chown, "redis:redis", /var/lib/redis]
  # ...The rest of runcmd is the same as module 2

Note: mounts is run in the Init phase and redis-server is installed in the Final phase, so the redis user does not exist at this time, chown is placed in runcmd; the Azure udev link name is in the VM ls The actual result of /dev/disk/azure/scsi1/ shall prevail. For NVMe specifications, you need to use the link provided by azure-vm-utils instead.

Create VM: --assign-identity, --data-disk-sizes-gb 16, --custom-data, SSH rules only allow your IP, enable managed boot diagnostics;cloud-init status --wait Post-authentication findmnt /var/lib/redis and /healthz.
identity: Install AADSSHLoginForLinux; assign yourself a Virtual Machine Administrator Login (resource group scope); use az ssh vm Log in and sudo; assign a resource group Reader to the VM managed identity and list the resource group resources within the VM with the IMDS token (Module 4).
Observable: workspace + AMA + DCR (auth Info+, daemon Warning+, CPU/memory/disk counters); create a myapp Warning log and find it with KQL; write a "root partition usage" query (module 5).
Patch: Evaluate once; switch VM to Customer Managed Schedules + periodic evaluation; create maintenance configuration and associate every Saturday at 02:00 (Module 6).
Fault drill: Ask your peers (or yourself) to perform one of the following without telling you: remove nofail of fstab and detach the data disk / write bad sshd configuration / add NSG deny rules. You can only restore SSH and az Command and Portal to restore SSH and SSH in 10 minutes /healthz within 10 minutes using the command and portal (Module 7).
Cleaning: Record total time and estimated cost (Module 8 estimator); az group delete; Use tags to confirm no residue.
Acceptance Checklist

Open Self-Test (6 questions)

1. Describe in your own words the complete first boot link of an Azure Linux VM from "az vm create" to "myapp accessible" and indicate at which step az vm create returns.

ARM allocates the host, copies the OS disk, and mounts the provisioning ISO → UEFI/Secure Boot → shim/GRUB → kernel + initramfs → systemd → cloud-init generator → local (read ovf-env.xml, obtain network configuration via IMDS) → init (disk, user, SSH, report to WireServer as ready after completion, at this time az vm create returns) → config (runcmd writes script) → final (installs packages, deferred files, executes runcmd, and starts myapp); walinuxagent parallel processing extension.

2. Why is it said that "the security boundary of a managed identity is the entire VM"? What impact does it have on the permission design of myapp?

Any process on the VM can request a token from IMDS for the identity of that VM, so the identity's permissions are equal to the potential permissions of the least trusted code on the VM. Only grant myapp the minimum necessary roles (such as Secrets User of a Key Vault). Applications with different trust levels should not share a VM or an identity; host firewalls can be used to restrict users who access IMDS.

3. Which data of myapp are suitable for temporary disk and data disk? Adjustments for v6 specs are given.

Redis persistent files, upload files → data disk; pip cache, temporary files, swap → temporary disk. The NVMe temporary disk of v6 is a bare disk and requires an initialization script (systemd oneshot) for each startup. Services that rely on it add RequiresMountsFor=.

4. Compare SSH keys, Entra login, Bastion, JIT, and give recommended combinations for a small team versus a regulated enterprise.

Small team: Entra login + NSG limited source IP, keep a broken window key. Regulated Enterprise: No public IP + Bastion Premium (session recording) or VPN; Entra login + Conditional Access (MFA, Compliance Devices) + Group assigned login role; JIT for the few scenarios where ports must be opened; Serial console access is RBAC controlled and audited.

5. Design a log collection strategy for the myapp production environment, taking into account troubleshooting and cost.

auth/authpriv Info+ (security); daemon/kern Warning+; access logs are sampled on the application side or entered into a low-cost table schedule; performance counters for 60 seconds; temporarily increase the level during troubleshooting and set reminder recovery; workspace daily cap + cost alert; use Policy to unify DCR correlation.

6. Make a pre-preparation checklist for making the VM rescueable.

Enable boot diagnostics; all fstab data disks must be UUID + nofail; keep the window-breaking password that can be used for the serial console (stored in Key Vault, usually random); confirm that the GRUB menu/SysRq is available; VM agent and outbound 443 are normal (Run Command/Extended); install the vm-repair extension and exercise ALAR; disk usage and Heartbeat Alert.

Sources and Release Notes

Verification basis for all technical facts in this lesson (Verification date: 2026-11-17)
TopicVerification conclusionSource (Access date: 2026-11-17)
Ubuntu on AzureThe endorsed distribution includes Ubuntu 22.04/24.04/26.04 LTS (including Pro); 26.04 unified offer Canonical:ubuntu-26_04-lts (Server/Minimal, Gen2 default, and Gen1, Arm64, CVM SKU), Pro is ubuntu-pro-26_04-lts; 26.04 kernel 7.0, Azure release announcement 2026-04-24Endorsed distros · Ubuntu Discourse Announcement
Image search and aliasURN format; when --all is not added, the CLI built-in alias is returned (changes with the version); the document lists CLI 2.87.0 as an example AzureLinux4, Ubuntu2204 and other aliases; images with plan are subject to terms and conditionsFind images with Azure CLI
Azure Linux4.0 will enter public preview in mid-2026 (URN microsoftazurelinux:azurelinux-4:4:latest) and is for evaluation only; 3.0 is GA VersionSame as above · Multiple media reports (Microsoft Open Source Summit 2026)
VM specificationsStandard_D2ads_v5: 2 vCPU / 8 GiB / 75 GiB temporary disk / up to 4 data disks / Uncached Premium SSD 3,750 IOPS, 82 MBpsDadsv5 series
cloud-init and WALATwo provisioning agents; cloud-init is responsible for provisioning, WALA turns off provisioning but handles scaling; cloud-init has no timeout, and WALA has a total provisioning limit of 40 minutes when processing customData; 21.2 No UDF driver can be provisioned via IMDS (only SSH keys and userData); log /var/log/cloud-init.log; runcmd failure does not cause provisioning failurecloud-init support
cloud-init phaseGenerator / Local / Init(Network) / Config / Final; Stage formatting temporary disk, setting host name, SSH; sending a provisioning success signal to the platform after Init; Final stage packaging and running scripts; /var/lib/cloud/scripts/per-*Understanding cloud-init
IMDSCurrent api-version 2025-04-07; requires Metadata: true, without proxy, rejected X-Forwarded-For; typically 5 times/second, managed identity category 20 times/second and 5 concurrencyInstance Metadata Service
Managed Identity TokenEndpoint /metadata/identity/oauth2/token?api-version=2018-02-01&resource=…; response fields; subsystem cache token; security boundary is entire VM; retry policy (404/429/5xx, 410 up to 70 seconds)Use VM token
Entra ID login LinuxSupports Ubuntu 16.04–26.04, RHEL 8.3+/9.0+/10.1, Azure Linux 3.0, etc.; extends Microsoft.Azure.ActiveDirectory/AADSSHLoginForLinux; requires system allocation identity, ≥1 GB memory; outbound endpoint; VM Administrator/User Login Role; Owner/Contributor does not automatically log in; az extension add --name ssh; Exit code 22/23; AllowGroups issueSign in with Entra ID and OpenSSH
Azure BastionAzureBastionSubnet ≥ /26; Native client requires Standard or Premium; session recording requires Premium and native client connections do not support recording; deployment is billed by the hourConfiguration settings · Native client
JITBelongs to Defender for Servers Plan 2; maintains denial rules in NSG/Azure Firewall, and releases specified source IPs for a limited time after approvalJIT overview
DisksFive types of managed disks; OS disk maximum 4,095 GiB; Standard HDD OS disk 2028-09-08 Retired; temporary disk path /dev/disk/azure/resource, may be lost during maintenance/redeployment/stop; v5+ temporary disk encryption; data disk mounting with nofail, UUID; NVMe uses azure-nvme-idDisk Storage overview · Attach data disk
NVMe Temporary diskv6 specifications deliver original unformatted NVMe temporary disk; need to be reinitialized after stopping/deallocating/maintenance; official RAID0 initialization scriptTemp NVMe FAQ
Azure Monitor AgentExtended Microsoft.Azure.Monitor/AzureMonitorLinuxAgent, --enable-auto-upgrade; extended installation does not create DCR; no restart required; Linux account azuremonitoragent (runs mdsd); Heartbeat queryInstall and manage AMA
Syslog collectionrsyslog omfwd → TCP 127.0.0.1:28330 (Unix socket available for SELinux); configuration is at /etc/rsyslog.d/10-azuremonitoragent-omfwd.conf; forwarding only default ruleset; Syslog table; semicolon removedCollect Syslog with AMA
Azure Update ManagerPeriodic assessment every 24 hours; does not rely on Log Analytics/Automation; az vm assess-patches, install-patches (Linux classification Critical/Security/Other, rebootSetting); maintain configuration InGuestPatch associated with; planned patching requires Customer Managed SchedulesOverview · Programmatic · Dynamic scope
Serial consolePrerequisite: Enable startup diagnostics, password account, VM Contributor; Ubuntu, etc. are enabled by default; the upper limit of pasting is 2048 characters; disconnect without logging out; content is written to the startup diagnostic logSerial Console for Linux
Startup diagnosticsThe portal enables managed storage by default; CLI 2.12.0+ uses managed storage without specifying storage; managed storage data is currently not billed; stops writing after 1 GBBoot diagnostics
Run CommandOutputs the last 4,096 bytes; the minimum is about 20 seconds; runs with elevated privileges by default; one at a time; cannot interact/cancel; maximum 90 minutes; requires outbound; log /var/log/azure/run-command/handler.logAction Run Command
fstab failureSerial log feature, single user repair, ALAR az vm repair repair-button --button-command 'fstab'fstab errors
Ubuntu packageUbuntu redis-server version 8.0.5 (universe) in 26.04 (resolute)packages.ubuntu.com

Video verification instructions

The following videos were released on 2026-11-17 via YouTube oEmbed Interface (https://www.youtube.com/oembed?url=…&format=json) Verify that the title is consistent with the channel, and the channels are both John Savill's Technical Training: Creating your first Azure VM! (_UuO52KgwGk), Azure Master Class v3 - Part 7 - VMs and VMSS (KRBFVqgxyo4), Azure Master Class v2 - Module 7 - VM and VMSS (OykMc6wKMJY), Azure Managed Disks Deep Dive (2nPZyLmciN4), IOPS, Throughput & Latency Explained (HovW_gov6Qc), Microsoft Azure Managed Identity Deep Dive (rC1TV0_sIrM), Examination of options to connect to Azure VMs (R_kuXl1n4AU), Azure Just-in-time VM Access (nx25SWhh1GQ), Microsoft Azure Monitor Agent (AMA) and Data Collection Rule (DCR) Overview (Z1zDlXCwI9k), Azure Monitor Logs Log Types (lzVQ3NqMnTE), Azure Update Manager 2023 Edition (LVmNh5YgBOQ), Azure Update Management (8HPUKgKYNeY), Azure Cost Optimization Deep Dive (RjuTQvGm1zQ). Not found Verified English video specifically explaining "stages of cloud-init on Azure" and "serial console repair fstab", storyboards are provided in the corresponding pages.

Voice explanation instructions

The "Voice" page uses the browser's Web Speech API (speechSynthesis, en-US) to read the explanation script in real time. English terms are pronounced in en-US. The effect depends on the voice installed in the operating system (Windows "Microsoft Xiaoxiao/Yunxi", macOS "Tingting", etc.). This courseware does not generate MP3; the transcript can be given directly to TTS tools or dubbing personnel.

Known limitations

  • The commands in this lesson are not actually run in a real Azure subscription; all "expected output" are examples constructed based on official documents and experience, and IP, ID, version number, time, and count are all example values.
  • The Azure CLI alias of Ubuntu 26.04 (such as Ubuntu2604) has not been verified, and the complete URN will be used in this lesson; the specific SKU names of Azure Linux 3.0 and RHEL 10 have not been verified one by one, please use az vm image list-skus to query.
  • Azure udev stable link (/dev/disk/azure/scsi1/lunN, new link provided by azure-vm-utils) may be named differently on different image versions and SCSI/NVMe controllers, subject to the actual ls /dev/disk/azure in the VM.
  • In the first startup animation, the parallel timing of cloud-init and walinuxagent, the location of the managed identity token cache, and the interaction between aadsshlogin and pas.windows.net in Entra SSH login are conceptual expressions based on the components and endpoints in the official documents, and are not packet-by-packet capture results.
  • The minimum length of the Update Manager maintenance window is recommended, the patch extension name, the patch setting attribute path of az vm update --set, and the az maintenance parameter format are organized according to the API structure and document examples. The CLI details are subject to the -h output.
  • The cost-related figures (Bastion, log unit price, etc.) are only magnitude instructions or estimator example default values, not quotations; please refer to the price calculator.
  • The prompt text of emergency mode changes with the systemd version; for the specific key steps to enter single-user mode when Ubuntu root is locked, please refer to the official GRUB/single-user mode document.
  • The DCR JSON structure is organized based on official DCR examples and syslog/perf documents; the performance counter object/instance name is based on the actual data in the workspace.