Linux Hour 3: Towards the cloud platform (Azure)
- 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 inStandard_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-serveris 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 uprg-linux-lab.
1-hour time allocation table
| # | Time | Module | Core content | Animation/Interaction | Lab (Azure, rg-linux-lab / canadacentral) |
|---|---|---|---|---|---|
| 0 | Pre-class | Warm-up and Azure preparation | Azure CLI Login, subscriptions and quotas, resource groups, SSH keys, connection to Lesson 2 | Environment self-check | Create rg-linux-lab |
| 1 | 00–05 | Image, VM Specifications and selection | URN and aliases, Ubuntu / Azure Linux / RHEL, Gen1/Gen2, Trusted Launch, specification naming, quota | URN constructor + specification name decoder | Query image and specifications |
| 2 | 05–13 | cloud-init and VM extension | Provisioning agent, customData vs userData, cloud-init five phases, walinuxagent and extension, Custom Script | Core animation: Linux VM first startup process | cloud-init deployment myapp + redis-server |
| 3 | 13–21 | Managed disk, temporary disk and file system | OS/data/temp disk, disk type, LUN and /dev/disk/azure, parted/mkfs/fstab, online expansion, NVMe | Temporary disk life cycle + fstab emulator | Mount data disk to Redis Persistence |
| 4 | 21–29 | Identity and Access | Entra ID login, VM login role, az ssh vm, managed identities and IMDS tokens, SSH keys, Bastion, JIT | Core Animation: How the managed identity token reaches the VM via IMDS | Entra login + get token inside VM |
| 5 | 29–37 | Azure Monitor Agent and DCR | AMA architecture, DCR/DCRA, syslog facilities and levels, performance counters, KQL, cost | A syslog journey | Collecting myapp logs and CPU/memory |
| 6 | 37–45 | Azure Update Manager | Periodic evaluation, on-demand installation, maintenance configuration, patch orchestration mode, restart settings, relationship with unattended-upgrades | Patch window timeline | Evaluate and install security patches |
| 7 | 45–54 | Cloud troubleshooting | Boot diagnostics, serial console, Run Command, ALAR, fstab / disk full / sshd / NSG | "Which channel can still be used" fault simulator | Deliberately destroy fstab and save it |
| 8 | 54–60 | Cost, cleanup and self-test | Billing structure, stop vs deallocate, automatic shutdown, label, budget, delete resource group | Cost estimator + troubleshooting decision tree | Complete cleanup |
| — | After class | Cheatsheet · Comprehensive lab | Delivery of a "production-ready" myapp VM from scratch | Final exam (12 Question) | Comprehensive experiment |
Knowledge Coverage Matrix
| Target skills | M1 | M2 | M3 | M4 | M5 | M6 | M7 | M8 | Key commands | Experiment |
|---|---|---|---|---|---|---|---|---|---|---|
| Select image and specifications | ✓ | · | ✓ | · | · | · | · | ✓ | az vm image list, az vm list-skus | M1 |
| First boot automation (cloud-init) | · | ✓ | ✓ | · | · | · | ✓ | · | --custom-data, cloud-init status | Myapp automatic deployment |
| VM extension and VM agent | · | ✓ | · | ✓ | ✓ | ✓ | ✓ | · | az vm extension list/set | M2/M4/M5 |
| Disk and file system | · | · | ✓ | · | · | · | ✓ | ✓ | az vm disk attach, parted, blkid | Redis data disk |
| Identity and access (Entra / MI / Bastion / JIT) | · | · | · | ✓ | ✓ | · | ✓ | · | az ssh vm, az role assignment | Entra login |
| Logs and Metrics | · | · | · | · | ✓ | · | ✓ | ✓ | az monitor data-collection rule, KQL | Syslog table |
| Patch management | · | · | · | · | · | ✓ | · | · | az vm assess-patches, install-patches | M6 |
| Troubleshooting without SSH | · | ✓ | ✓ | ✓ | · | · | ✓ | ✓ | Serial console, az vm run-command invoke, az vm repair | fstab rescue |
| Cost and cleanup | ✓ | · | ✓ | ✓ | ✓ | · | · | ✓ | az vm deallocate, az group delete | M8 |
What this lesson does not cover (and where to learn)
| Topics | Why not in this lesson | Where to learn |
|---|---|---|
| Linux basic commands, permissions, processes, systemd unit writing, LVM, network troubleshooting | This lesson is assumed to be mastered by you and will only be reused on the cloud | Lesson 1 · Lesson 2 |
| Similar topics on AWS (AMI, user data, IMDSv2, SSM) | Different platforms provide better comparative learning effects | Lesson 4: Going to the cloud platform (AWS) |
| Batch creation and configuration of VMs with Terraform / Ansible | Infrastructure as code and configuration management | Terraform class · Ansible class |
| Prometheus / Grafana monitoring myapp | This lesson only uses Azure native AMA + Log Analytics | Prometheus & Grafana lesson |
| VM Scale Sets (VMSS), Load Balancing, Availability Zone High Availability Architecture | Belongs to the architecture topic and exceeds 1 hour | VMSS Official documentation |
| Containerized deployment of myapp (Docker/AKS) | This lesson adheres to the "native systemd service" route | Docker lesson · AKS course |
How to use this courseware
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.
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).
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.
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). 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)
- 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, unitWorkingDirectory=/opt/myapp/app), configuration/etc/myapp/myapp.env, systemd unitmyapp.service, port5000, health check/healthz, Redis uses the release version ofredis-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 andsshextension). - This lesson uses the following uniformly: resource group
rg-linux-lab, regioncanadacentral, VM namevm-linux-lab, administratorlabadmin, 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" }
}
/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 linuxlab | Who will do this lesson | Module |
|---|---|---|
apt install redis-server python3-venv | cloud-init packages: | 2 |
useradd --system myapp | cloud-init users: | 2 |
Write /opt/myapp/app/app.py, /etc/myapp/myapp.env, myapp.service | cloud-init write_files:(defer: true) | 2 |
systemctl enable --now myapp | cloud-init runcmd: | 2 |
| LVM/extra disk mount | Managed data disk + UUID + nofail | 3 |
journalctl -u myapp | Same as above, plus AMA sends syslog to Log Analytics | 5 |
apt upgrade / unattended-upgrades | Azure Update Manager | 6 |
| Local console (Multipass / Hyper-V window) | Serial console + startup diagnostics | 7 |
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.
Module 1 · Linux on Azure: Images, VM specifications and selection
- Understand the image URN
Publisher:Offer:Sku:Version, will useaz vm image list / list-skus / showto 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.
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.
| Segment | Meaning | Ubuntu 26.04 Example |
|---|---|---|
| Publisher | Publisher | Canonical |
| Offer | A set of related images | ubuntu-26_04-lts (unified offer, including Server and Minimal; Pro version is ubuntu-pro-26_04-lts) |
| Sku | Specific variant (Gen2/Gen1/Arm64/CVM/Minimal) | server (x64 Gen2, default), server-gen1, server-arm64, minimal-arm64, server-cvm |
| Version | Image version | latest or specific date version number |
Why: How to choose three common types of Linux images
| Ubuntu Server LTS | Azure Linux | RHEL (and Rocky/Alma comparison) | |
|---|---|---|---|
| Example URN | Canonical:ubuntu-26_04-lts:server:latestCanonical: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 management | apt(deb822 .sources) | dnf / tdnf(RPM) | dnf(RPM), SELinux enforcing |
| Image fees | Non-Pro images are free | Free | RHEL images with subscription fee (PAYG) or BYOS |
| Suitable | Universal, consistent with the local lab VM (preferred for this course) | Microsoft's own streamlined RPM distribution: AKS node, container host, pursuing small attack surface | Enterprise compliance, requires Red Hat support |
| cloud-init | Yes | Yes | Yes (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.
| Series | Positioning | Linux Typical Usage |
|---|---|---|
| B (burstable) | Low baseline CPU + points burst | Development testing, low-load spring machine (note that the speed will be limited after the points are exhausted) |
| D (general) | CPU: memory ≈ 1:4 | Web/API (myapp), small and medium-sized database |
| E (memory optimization) | ≈ 1:8 | Redis, Elasticsearch, large cache |
| F (computing optimization) | ≈ 1:2 | Batch processing, compilation |
| L (storage optimization) | High-capacity local NVMe | Cassandra, log index |
| N(GPU) | Accelerator | AI 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 withp, such asStandard_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/sdXto/dev/nvmeXnY(module 3).
Comparison with similar technologies
| Azure | AWS (Lesson 4) | On-prem Multipass (Lesson 1) | |
|---|---|---|---|
| Image Identification | URN / Alias / Compute Library Image ID | AMI ID (unique within region) | Alias (such as 26.04) |
| Specifications | Standard_D2ads_v5 | t3.medium / m7g.large | --cpus --memory |
| First startup configuration | customData / userData → cloud-init | user data → cloud-init | --cloud-init → cloud-init |
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
Specification name disassembly
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.
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 }
| Command | Function | Note |
|---|---|---|
az vm image list --all | Full directory query | Do not add --all Only the built-in alias table (offline cache) is returned |
az vm image show | See plan / Generation / architecture | plan is not null. terms accept |
az vm list-skus | Availability and limitations of specifications in regions/availability zones | Restrictions column appears NotAvailableForSubscription, that is, it is unavailable |
az vm list-usage | Quota | Calculated 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)
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 }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.
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
~/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).
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
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
Official document
- Find Azure Marketplace image information using the Azure CLI
- Endorsed Linux distributions on Azure
- Azure VM sizes naming conventions
- Dadsv5 size series
Video storyboard script (about 75 seconds)
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.
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.
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.
Module 2 · cloud-init and VM extension: first startup automation
- 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-configthat can deploy myapp +redis-server, and usecloud-init status/analyze/schemaand log troubleshooting; also use Custom Script extension for "post-creation" configuration.
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-init | walinuxagent(WALA) | |
|---|---|---|
| When to run | Run at every startup, but most modules are executed "once per instance" | Resident systemd service (Ubuntu: walinuxagent.service) |
| What to do | Network, host name, user and SSH key, disk/mount, software package, write file, runcmd | Get "target status" from WireServer (168.63.129.16), download and execute the extension, report heartbeat and extension status |
| Input | customData/userData (#cloud-config and other formats) | Extended settings/protectedSettings |
| Timeout | No time limit, no deployment failure due to timeout | If 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 channel | Provisioning ovf-env.xml | IMDS: /metadata/instance/compute/userData |
| Can it be read/modified after creation? | Cannot be read back from IMDS; modifications require rebuilding the VM | It 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 processed | Yes (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
- Generator: The systemd generator determines whether cloud-init is required for this startup (
ds-identifyidentifies Azure through DMI).datasource_list: [ Azure ]is usually hardcoded in the image to save time. - Local (
cloud-init-local.service, before the network is up): Load the Azure data source, mount the provisioned ISO, readovf-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. - Init/Network (
cloud-init.service): Runcloud_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 createtherefore returns, but the software package may not be installed yet! - Config (
cloud-config.service): Runcloud_config_modules, such as apt configuration, ntp, time zone,runcmd(just write the command as a script). - Final (
cloud-final.service, close to multi-user.target): Runcloud_final_modules——package_update_upgrade_install(package),write_files_deferred(defer: truefile),scripts_user(actually execute runcmd),final_message. Scripts under/var/lib/cloud/scripts/per-boot|per-instance|per-oncewill also be executed.
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?
| Requirements | Preferred | Reason |
|---|---|---|
| First boot, install package, create user, write configuration | cloud-init(customData) | Out-of-the-box, cross-release, no timeout |
| VM is already running, you need to add configuration/run script | Custom Script extension or Run Command | cloud-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 VMs | Pre-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 management | Ansible and other configuration management | See Ansible Lesson |
Comparison with similar technologies
| Azure | AWS (Lesson 4) | Local Multipass | |
|---|---|---|---|
| Data Source | Azure(ovf-env.xml + IMDS) | Ec2(IMDSv2) | NoCloud |
| Platform Agent | walinuxagent | SSM Agent (optional) | None |
| Complete signal | Report ready to WireServer | No explicit signal (status check) | multipass waits for cloud-init |
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
Flowchart: cloud-init stage and systemd unit
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).
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
| Command | Purpose | Note |
|---|---|---|
cloud-init status --wait | Waiting for the first startup to be completed in the script | The exit code is not 0 means there is an error (the new version returns 2 for recoverable errors) |
cloud-init schema | Verify YAML syntax and key names | Use -c file locally to verify before deployment, which can avoid a complete rebuild |
cloud-init clean --logs | Clear the status and rerun as a new instance next time | Only for imaging or experimentation; use with caution in production |
az vm extension set | Installing/updating extensions | Requires VM agent running and outbound access |
Experimental: Use cloud-init to deploy myapp + redis-server in one go (about 8 minutes, start billing)
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.
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
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=1ssh $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
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).
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/healthzCase 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.
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 tableA 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.
Official document
- cloud-init support for Linux VMs in Azure
- Understanding cloud-init (five stages)
- Azure Linux VM Agent overview
- Custom Script Extension for Linux
- cloud-init Azure datasource
Video storyboard script (about 100 seconds)
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.
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.
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.
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.
Module 3 · Managed disks, temporary disks and file systems
- 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 →
partedpartition →mkfs→ Write fstab with UUID +nofail; and use systemdRequiresMountsFor=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.
What: three disk roles
| OS disk | Data disk | Temporary / Resource disk | |
|---|---|---|---|
| Is it a managed disk | Yes | Yes | Not - host-local SSD |
| Persistence | Persistent (3 replicas; LRS 11 9 / ZRS 12 9 years durability) | Persistence | Retained 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 storage | System and software | Application data (Redis RDB/AOF, database) | swap, cache, temporary files - data that can be reconstructed at any time |
| Billing | By provisioned size | By 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
| Type | Media/Features | Typical uses |
|---|---|---|
| Standard HDD | Cheapest, high latency | Backup, cold data (OS disk is no longer recommended) |
| Standard SSD | Getting started with SSD | Development test, light load Web (data disk for this lesson) |
| Premium SSD | Given by gear (P10/P20...) IOPS/throughput, support sudden increase | Production of OS disk and database |
| Premium SSD v2 | Capacity, IOPS, and throughput are configured separately; OS disk cannot be produced | Database with finely tuned performance |
| Ultra Disk | Sub-millisecond latency, performance can be adjusted online; cannot be used as OS disk | SAP 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"
- Azure side:
az vm disk attach --new --lun 0. Disks are hot-pluggable as SCSI or NVMe devices, no reboot required. - Find device: Don’t guess
/dev/sdc! For SCSI, uselsblk -o NAME,HCTL,SIZEto see the fourth segment of HCTL (LUN), or use the stable link/dev/disk/azure/scsi1/lun0generated by Azure udev rules; for NVMe models, usesudo azure-nvme-idof azure-vm-utils (outputtype=data, lun=0). - Partitioning and formatting:
parted --script mklabel gpt mkpart …→partprobe→mkfs.ext4ormkfs.xfs(≥ 2 TiB must be GPT). - 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; addnofail- it can also start when the disk is missing (otherwise it will enter emergency mode, module 7). - Protect services that depend on it:
systemctl edit redis-serverAddRequiresMountsFor=/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
dspecification): formatted and mounted to/mntby cloud-init on first boot, withDATALOSS_WARNING_README.txton 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
| Azure | AWS (Lesson 4) | On-premises (Lesson 2) | |
|---|---|---|---|
| Persistent Block Storage | Managed Disks | EBS volume | Virtual disk / LVM |
| Local non-persistent disk | Temporary disk / NVMe temporary disk | Instance store (Instance store) | — |
| Stable device name | /dev/disk/azure/…, LUN | Volume ID in NVMe serial number | /dev/disk/by-uuid |
/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
Flow chart: fstab at boot How to turn a line into a mount
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".
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)
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@$IPlsblk -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
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"
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
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
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.
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
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
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
Official documentation
- Overview of Azure Disk Storage (including temporary disk)
- Attach a data disk to a Linux VM(SCSI/NVMe, fstab nofail)
- Temp NVMe disks FAQ
- Azure managed disk types
Video storyboard script (about 80 seconds)
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.
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.
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.
Module 4 · Identity and Access: Entra ID Login, SSH and Bastion
- 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.
What: Two types of identities, two paths
| "People" log in to VM | "Programs in VM" access Azure | |
|---|---|---|
| Identity | Microsoft Entra User/Group/Service Principal | VM's Managed Identity (system-assigned or user-assigned) |
| Credentials | Entra-issued short-lived OpenSSH certificate (az ssh vm automatically obtained) | OAuth access token returned by IMDS (no key/password required) |
| Authorization | Azure RBAC: Virtual Machine Administrator Login (sudo available)/ Virtual Machine User Login | Azure RBAC: Assign managed identities roles on target resources (e.g. Reader, Key Vault Secrets User) |
| In-VM components | aadsshlogin (and aadsshlogin-selinux), installed by the AADSSHLoginForLinux extension | No 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_keyson 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)
- 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.
- VM: Enable System Assigned Managed Identity; install extension
Microsoft.Azure.ActiveDirectory/AADSSHLoginForLinux(VM agent running, memory ≥ 1 GB). - Network: VM has outbound 443 access to
packages.microsoft.com,login.microsoftonline.com,pas.windows.net, and access to IMDS169.254.169.254. - Client: Azure CLI +
sshextension (az extension add --name ssh, Cloud Shell is pre-installed); you can alsoaz ssh configexport 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 lowercaseMetadata: true(mitigating SSRF); it cannot bringX-Forwarded-For, and cannot be proxied (curl plus--noproxy "*"). - Returns
access_token,expires_on,resource,token_type: Bearer; theaudclaim of the token isresource. - 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
| Method | Need public network 22? | Pros | Costs/Notes |
|---|---|---|---|
| SSH keys (labadmin) | Yes (or via Bastion) | Simple, available offline | Key distribution and revocation are difficult; just keep it as a "broken window" account |
Entra ID + az ssh vm | Requires TCP connectivity to VM (public network/private network/Bastion) | Centralize identity, MFA, RBAC, audit | Relies on extensions and outbound networking; sshd_config's AllowGroups/DenyGroups will fail first login |
| Azure Bastion | No - VM can have no public IP | Browser or local client access via TLS 443 | Developer SKU free with limited functionality; On-prem native client (az network bastion ssh) requires Standard or Premium; hourly billed; requires AzureBastionSubnet |
| JIT VM access | Temporarily open on demand | Normally NSG rejects 22, and the specified source IP will be released for a limited time after application | Requires Defender for Servers Plan 2 |
| Serial console | No | Last resort when network/SSH goes down | Requires password account with VM Contributor (Module 7) |
Comparison with similar technologies
| Azure | AWS (Module 4) class) | |
|---|---|---|
| Workload identity | Managed identity (IMDS token) | Instance profile/IAM role (IMDSv2 temporary credentials) |
| Human login | Entra ID + az ssh vm | EC2 Instance Connect / SSM Session Manager |
| No public network springboard | Azure Bastion | Session Manager / EC2 Instance Connect Endpoint |
Architecture diagram: Entra login shares IMDS with managed identity
Comparison of network entrances
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.
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
| Commands | Function | Note |
|---|---|---|
az ssh vm | Entra certificate login (default) or local account login | CLI requires ssh extension; re-az login |
az ssh config | Generate configuration and certificate for OpenSSH / VS Code Remote | Certificate is valid for a short period of time and will be regenerated after expiration |
az vm user update/reset-ssh | Reset key/password/sshd via VMAccess extension | Requires VM agent to be normal |
az network bastion ssh | Local native client login via Bastion | Standard/Premium + Enable Native Client Support |
Experimental: Entra ID login + calling ARM with managed identity within VM (~7 minutes)
--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
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
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.
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.
az network nsg rule list -g $RG --nsg-name ${VM}NSG --query "[].{name:name,port:destinationPortRange,src:sourceAddressPrefix,access:access}" -o tableaz 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
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)
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
Official document
- Sign in to a Linux VM by using Microsoft Entra ID and OpenSSH
- Use managed identities on a VM to acquire access token
- Bastion native client · Bastion configuration settings
- Just-in-time VM access
Video storyboard script (about 90 seconds)
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.
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.
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.
Module 5 · Monitoring and logging: Azure Monitor Agent and DCR
- 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 →
omfwdTCP127.0.0.1:28330→ AMA → Log AnalyticsSyslogtable; performance counters enter thePerftable. - Use CLI to create workspace, DCR, association, and write KQL to troubleshoot myapp; control the collection volume to control costs.
What: AMA, DCR, DCRA, Log Analytics
| Component | What is | Example 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 flow | dcr-linux-lab |
| DCR Association (DCRA) | Put DCR Bind to a machine; a machine can be associated with multiple DCRs | vm-linux-lab ↔ dcr-linux-lab |
| Log Analytics workspace | Destination 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
- myapp (gunicorn) writes stdout → systemd into journald, identified as
SyslogIdentifier=myapp, and the facility defaults todaemon. - rsyslog is read from journald (or via
/dev/logsocket) and processed according to rules. - After syslog is enabled in DCR, AMA writes forwarding rules (
omfwd, TCP127.0.0.1:28330, disk buffer queue) in/etc/rsyslog.d/10-azuremonitoragent-omfwd.confand automatically restarts rsyslog; SELinux environments can use the Unix socket/run/azuremonitoragent/default_syslog.socketinstead. The syslog-ng environment is written to/etc/syslog-ng/conf.d/. - AMAs are filtered by DCR's Facility + Minimum Level and batches are sent to the Azure Monitor engine via HTTPS, falling into the workspace
Syslogtables (Facility,SeverityLevel,ProcessName,SyslogMessage...). - Performance counters are sampled directly by AMA (such as
Processor(*)\% Processor Time) and entered into thePerftable; AMA writesHeartbeatevery 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)
| Data | Recommendations | Reasons |
|---|---|---|
| auth / authpriv | Info and above | Security audit (SSH login, sudo) |
| daemon (including myapp, redis) | Production Warning+; temporary Info+ during troubleshooting period | The access log volume is large and billed by GB |
| kern | Warning+ | OOM, disk I/O errors |
| Performance counter | 60 seconds sampling, few key items of CPU/memory/disk/network | The denser the sampling, the higher the cost |
| Full application access log | Consider text log DCR + basic log layer or sampling on the application side | Cost control |
Comparison with similar technologies
| Azure | AWS (4th Class) | Open source | |
|---|---|---|---|
| Agent | AMA | CloudWatch Agent | Prometheus node_exporter / Fluent Bit |
| Collection configuration | DCR (Azure resources, centralized management) | Agent JSON configuration (always put SSM parameters) | Local configuration file |
| Query | KQL | Logs Insights query syntax | PromQL / LogQL (see Prometheus class) |
Architecture diagram: AMA + DCR data flow
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).
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)
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
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.
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
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:*
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).
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
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
Official document
- Install and manage the Azure Monitor Agent
- Collect Syslog events with Azure Monitor Agent
- Collect performance counters
- DCR samples
Video storyboard (about 75 seconds)
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.
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.
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.
Module 6 · Patches and Updates: Azure Update Manager
- 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-patchesandaz maintenanceto complete an assessment and installation, and handle restarts.
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 (InGuestPatchrange); available dynamic ranges (by subscription/RG/label, etc.) decide which machines to include at runtime. - Linux classification:
Critical,Security,Other;packageNameMasksToInclude/Excludecan also be used (such askernel*,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 | |
|---|---|---|
| Scope | Single machine, only security updates are installed by default | Unified policy for hundreds of machines |
| Visibility | Requires login to view logs | Portal/Resource Graph reports, alarms |
| Window and restart control | Native machine timer; additional configuration is required for restart | Maintenance window + rebootSetting (IfRequired / NeverReboot / AlwaysReboot) |
| Cross-region security promotion | None | AutomaticByPlatform: Install in batches with "availability priority", during off-peak hours in the VM's time zone |
How: Patch orchestration settings
| Portal options | API settings (Linux) | Behavior |
|---|---|---|
| Image Default | patchMode=ImageDefault | Inherit the mechanism in the image (Ubuntu: unattended-upgrades and apt-daily timer) |
| Azure Managed – Safe Deployment | patchMode=AutomaticByPlatform, bypass…=false | Automatic guest patching: the platform automatically installs Critical/Security during off-peak periods and in batches across regions |
| Customer Managed Schedules | patchMode=AutomaticByPlatform, bypassPlatformSafetyChecksOnUserSchedule=true | Your associated maintenance configuration determines when to install; unassociated plans will not be installed automatically (to prevent accidental upgrades) |
| Periodic evaluation | assessmentMode=AutomaticByPlatform | Evaluated 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, andneedrestartwill 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
| Azure | AWS (Lesson 4) | Open Source/Local | |
|---|---|---|---|
| Service | Azure Update Manager | Systems Manager Patch Manager | unattended-upgrades / dnf-automatic / Ansible |
| Window | Maintain Configuration | Maintenance Windows | cron / systemd timer |
| Baseline | Classification + Package name mask | Patch Baselines | Customized |
Architecture Diagram: Control Path for Assessment and Installation
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.
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)
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
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
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
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. 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
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"
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
Official documentation
- Azure Update Manager overview
- Programmatically manage updates for Azure VMs
- Dynamic scoping (prerequisite: Customer Managed Schedules)
- Automatic VM guest patching
Video storyboard (about 75 seconds)
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.
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.
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.
Module 7 · Troubleshooting on the cloud: serial console, startup diagnosis and common faults
- 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."
What: Four out-of-band channels
| Channel | What can it do | Depends on | Limitations |
|---|---|---|---|
| Boot diagnostics Boot diagnostics | View 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 Console | Interactive access ttyS0: login, entering GRUB, single-user mode, SysRq | Boot diagnostics are enabled; there is a user with password in the VM; you have Virtual Machine Contributor or higher | Mainly 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 Command | Run the script as root and return the output (RunShellScript) | VM running, VM Agent OK, outbound 443 reachable | Output 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 / ALAR | Hang 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 resources | Requires 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
| Faults | Symptoms | Channels that can still be used | Fix points |
|---|---|---|---|
fstab is missing nofail, the data disk is detached/UUID is wrong | SSH timeout; serial log: Timed out waiting for device …, Dependency failed for /var/lib/redis, Welcome to emergency mode!, Give root password for maintenance | Start 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 full | SSH login is slow or fails; apply 500; No space left on device; Extension installation failed | Run Command (usually available), serial console | df -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 error | Connection 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 interception | SSH timeout, but the VM runs normally and the serial log is normal | All Channels within the VM are available - the problem is outside the VM | az 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)
- VM status and resource health:
az vm get-instance-viewLook at the power status and agent status; the portal "Resource Operation Status" looks at platform events. - Network: Timeout (timeout) may be network/NSG; rejection (refused) indicates that the packet arrived at the VM but the port was not monitored.
- Startup diagnostics: Read the last 100 lines of the serial log to determine whether it is stuck in the startup phase.
- Run Command: The fastest non-interactive method when the system is started.
- Serial console: When the system is not fully started and interaction is required.
- Offline repair/redeployment:
az vm repair; when there is a platform host problemaz vm redeploy(moving to a new host, temporary disk data is lost).
Comparison to similar technologies
| Azure | AWS (Lesson 4) | On-premises (Lessons 1–2) | |
|---|---|---|---|
| Read-only console log | Start diagnostic serial log | Get system log / screenshot | Virtual machine window |
| Interactive console | Serial console | EC2 Serial Console | Hyper-V/VirtualBox Console |
| Remote Execution | Run Command | SSM Run Command | — |
| Offline Repair | az vm repair / ALAR | Mount root volume to rescue instance | Mount ISO |
Decision chart: When SSH cannot connect
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.
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)
az vm boot-diagnostics enable). 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).
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".
# 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" | heade 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
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.
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 valueaz 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 tsvCase 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.
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
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.
Official documents
- Azure Serial Console for Linux
- Use Serial Console to access GRUB and single-user mode
- Azure boot diagnostics
- Run scripts with action Run Command
- Troubleshoot Linux VM boot issues due to fstab errors
Video storyboard script (about 90 Seconds)
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.
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.
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.
Module 8 · Cost, Cleanup and Self-Test
- 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-labsafely and thoroughly, and use the interactive troubleshooting tree to review all fault types in this lesson.
What: The billing structure of this lesson's experiment
| Resources | Billing method | After deallocation | Whether this lesson is created |
|---|---|---|---|
| VM calculation (Standard_D2ads_v5) | Running time (in seconds, hourly price) | No billing | Yes |
| OS disk/data disk (managed disk) | According to provisioned capacity (independent of usage) | Continue billing | Yes (30 + 16 GiB) |
| Standard Public IP | Hourly | Continue billing (static allocation) | Yes |
| Log Analytics | By import GB (+ retention fee beyond free retention period) | No new data generated | Yes |
| Azure Bastion(Standard) | By hour (billed as deployed) + egress traffic | Not related to VM, Billed until deleted | Optional |
| Snapshot | Based on used capacity | Continue billing | Optional |
| Boot diagnostics (managed storage) | Currently not billed | — | Yes |
| Update Manager(Azure VM) | No additional charge | — | Yes |
| Ubuntu non-Pro image | Free (RHEL, Ubuntu Pro excluded) | — | Yes |
Why: Stopped and Stopped (deallocated)
- Execute
sudo shutdown -h noworaz vm stopin the VM: status Stopped, the VM still occupies host resources, and continues to be billed by calculation. az vm deallocateor 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
| Means | Command/Location | Instructions |
|---|---|---|
| Automatic shutdown | az vm auto-shutdown -g … -n … --time 1900 | Deallocation 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 Alarm | Portal Cost Management → Budget | Sending emails/triggering action groups when thresholds are exceeded |
| Appropriate specifications and disks | Modules 1, 3 | Standard SSD for experimentation; production will go to Premium |
| Reserved Instances / Savings Plan | Portal | Significant price reductions for long-term stable loads (1 year/3 year commitment) |
| Log volume | DCR Level, table plan | Module 5 |
When: Clean list
- 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).
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.- Check whether there are any residues in
az resource list --tag course=linux-8h(such as snapshots and Bastion in other resource groups). NetworkWatcherRGis a subscription-level shared resource, free and can be reserved.- Local: Delete the entries and certificate directories generated by
az ssh configin~/.ssh/config.
Comparison with similar technologies
| Azure | AWS (Lesson 4) | |
|---|---|---|
| Stop not billed | deallocate | stop (EBS still billed) |
| One-click cleanup | Delete resource group | No resource group concept: cleanup by tag/CloudFormation stack |
| Public IP | Standard public IP By the hour | Public IPv4 by the hour |
VM power state and 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.
2 h
0 Days
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)
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.
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 …
az vm auto-shutdown -g $RG -n $VM --time 2300
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).
1. List all unattached managed disks in the subscription.
az disk list --query "[?diskState=='Unattached'].{name:name, rg:resourceGroup, size:diskSizeGB}" -o table2. 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
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
Official document
- States and billing status of Azure VMs
- Create and manage budgets
- Delete resource group and resources
- Azure pricing calculator
Video storyboard script (about 60 seconds)
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.
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.
Command cheat sheet
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
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
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 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
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
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"
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
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
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
169.254.169.254 | IMDS (metadata, userData, managed identity token), requires Metadata: true |
168.63.129.16 | WireServer: Readiness Report, Extended Goal Status |
/var/log/cloud-init*.log | cloud-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:28330 | AMA receive rsyslog forward |
Capstone Lab and Final Knowledge Check
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.
rg-linux-lab (canadacentral, with course/owner tag); confirm Canonical:ubuntu-26_04-lts:server:latest and Standard_D2ads_v5 Available (module 1). 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.
--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. 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). myapp Warning log and find it with KQL; write a "root partition usage" query (module 5). az Command and Portal to restore SSH and SSH in 10 minutes /healthz within 10 minutes using the command and portal (Module 7). az group delete; Use tags to confirm no residue. 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
| Topic | Verification conclusion | Source (Access date: 2026-11-17) |
|---|---|---|
| Ubuntu on Azure | The 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-24 | Endorsed distros · Ubuntu Discourse Announcement |
| Image search and alias | URN 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 conditions | Find images with Azure CLI |
| Azure Linux | 4.0 will enter public preview in mid-2026 (URN microsoftazurelinux:azurelinux-4:4:latest) and is for evaluation only; 3.0 is GA Version | Same as above · Multiple media reports (Microsoft Open Source Summit 2026) |
| VM specifications | Standard_D2ads_v5: 2 vCPU / 8 GiB / 75 GiB temporary disk / up to 4 data disks / Uncached Premium SSD 3,750 IOPS, 82 MBps | Dadsv5 series |
| cloud-init and WALA | Two 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 failure | cloud-init support |
| cloud-init phase | Generator / 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 |
| IMDS | Current 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 concurrency | Instance Metadata Service |
| Managed Identity Token | Endpoint /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 Linux | Supports 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 issue | Sign in with Entra ID and OpenSSH |
| Azure Bastion | AzureBastionSubnet ≥ /26; Native client requires Standard or Premium; session recording requires Premium and native client connections do not support recording; deployment is billed by the hour | Configuration settings · Native client |
| JIT | Belongs to Defender for Servers Plan 2; maintains denial rules in NSG/Azure Firewall, and releases specified source IPs for a limited time after approval | JIT overview |
| Disks | Five 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-id | Disk Storage overview · Attach data disk |
| NVMe Temporary disk | v6 specifications deliver original unformatted NVMe temporary disk; need to be reinitialized after stopping/deallocating/maintenance; official RAID0 initialization script | Temp NVMe FAQ |
| Azure Monitor Agent | Extended Microsoft.Azure.Monitor/AzureMonitorLinuxAgent, --enable-auto-upgrade; extended installation does not create DCR; no restart required; Linux account azuremonitoragent (runs mdsd); Heartbeat query | Install and manage AMA |
| Syslog collection | rsyslog 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 removed | Collect Syslog with AMA |
| Azure Update Manager | Periodic 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 Schedules | Overview · Programmatic · Dynamic scope |
| Serial console | Prerequisite: 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 log | Serial Console for Linux |
| Startup diagnostics | The 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 GB | Boot diagnostics |
| Run Command | Outputs 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.log | Action Run Command |
| fstab failure | Serial log feature, single user repair, ALAR az vm repair repair-button --button-command 'fstab' | fstab errors |
| Ubuntu package | Ubuntu 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 useaz vm image list-skusto 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 actualls /dev/disk/azurein 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.netin 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 theaz maintenanceparameter format are organized according to the API structure and document examples. The CLI details are subject to the-houtput. - 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.