Ansible Hour 3: Moving to the Cloud Platform (Azure)

From “managing 3 local containers” to “creating, discovering, configuring and deleting Azure VMs with code”: azure.azcollection, the azure_rm dynamic inventory, Key Vault and managed identity
ansible-core 2.21Ansible Community Package 14.xazure.azcollection 4.2.0Azure · canadacentralVerified against official docs · 2026-11
Overall Learning Objectives
  • Install azure.azcollection and its Python SDK dependencies (bundled with the collection's requirements.txt), be able to explain the priority order and use cases of the five authentication sources (Azure CLI, service principal, managed identity, environment variables, credentials file), and know auth_source how to force a specific one.
  • Write a azure_rm.yml -ending dynamic inventory file, using keyed_groups,conditional_groups,hostvar_expressions, filters and caching, to group Azure VMs automatically into tag_role_web groups like this.
  • Use azure_rm_resourcegroup / azure_rm_virtualnetwork / azure_rm_subnet / azure_rm_securitygroup / azure_rm_publicipaddress / azure_rm_networkinterface / azure_rm_virtualmachine in an idempotent manner to create one Azure VM, and use state: absent to delete safely.
  • Apply the Lessons 1–2 myapp role unchanged to Azure VMs: SSH key login, an NSG allowing only your public IP, or no public SSH at all, and instead connect through Azure Bastion a tunnel.
  • Use azure.azcollection.azure_keyvault_secret The lookup plugin reads secrets from Key Vault at runtime. Understand its “try managed identity first by default” behavior, and the Key Vault RBAC roles.
  • Explain the division of work between Ansible and Terraform/Bicep, common combination patterns and anti-patterns; locate the six common cloud failure types with the decision tree; estimate costs and clean up thoroughly.

1-Hour Time Allocation

#TimeModuleCore ContentAnimation / InteractionLab (Azure, rg-ansible-lab)
0Before ClassWarm-up & Azure PreparationSubscription, permissions, quotas, cost estimate, control node check, myapp role in placeEnvironment self-check listaz login,ansible --version
100–06azure.azcollection and AuthenticationInstall the collection and Python dependencies, pipx inject, the 5 credential sources and auth_source, OIDCCredential resolution order simulatorazure_rm_resourcegroup_info Smoke test
206–13Dynamic Inventory azure_rm*.azure_rm.yml Naming, keyed_groups, conditional_groups, hostvar_expressions, filters, cachingCore animation: the full dynamic inventory generation processansible-inventory --graph
313–22Creating Azure Resources with AnsibleRG → VNet → Subnet → NSG → PIP → NIC → VM, idempotency, check mode,state: absentResource dependency chain and idempotency demoprovision.yml Run twice
422–30Configuring Azure VMs and Deploying ApplicationsReuse the myapp role, SSH keys, NSG source IP restriction,wait_for_connection, Bastion tunnelConnection path comparison (public SSH vs Bastion)site-azure.yml + /healthz
530–37Secrets: Key Vault and Managed IdentityLookup plugin parameters, getting secrets from control node vs managed node, RBAC roles, no_logSecret retrieval timingPut the Redis password into Key Vault
637–44Division of Work: Ansible vs Terraform/BicepOrchestration vs configuration, four combination patterns, anti-patterns, hand-off points (outputs → tags → dynamic inventory)Tool selection decision guideBicep builds the VM + Ansible configures
744–53Troubleshooting in the CloudAuthentication failures, missing dependencies, empty inventory, SSH timeouts, 403, 429 throttlingInteractive troubleshooting treeDeliberately cause four faults and fix them
853–60Cost, Cleanup and Self-TestBillable items, stop vs deallocate, tag-driven cleanup, budget alerts, orphaned resourcesCost calculatorteardown.yml + verify 0 resources
—After ClassCheat sheet · Capstone LabFrom zero: create an Azure VM → dynamic inventory → deploy myapp → Key Vault → cleanupFinal quiz (12 questions)Capstone Lab

Knowledge Coverage Matrix

Target skillsM1M2M3M4M5M6M7M8Key commands / modulesLab
Install collection and SDK dependencies✓·····✓·ansible-galaxy collection install,pipx injectM1 Lab
Azure Authentication and Least Privilege✓✓··✓·✓·auth_source,az ad sp create-for-rbacSP + environment variables
Dynamic inventory and grouping·✓·✓·✓✓·ansible-inventory --graphlab.azure_rm.yml
Create cloud resources as code (idempotent)··✓··✓·✓azure_rm_virtualmachine etc.provision.yml
Secure VM access (SSH / NSG / Bastion)··✓✓··✓·az network bastion tunnelNSG source IP restriction
Deploy applications with the reused role·✓·✓✓···roles: [myapp]site-azure.yml
Secret management (Key Vault / MI)✓···✓·✓·lookup('azure.azcollection.azure_keyvault_secret', …)Redis password
IaC tool division of work··✓··✓··az deployment group createBicep + Ansible
Cloud fault diagnosis✓✓✓✓✓·✓·-vvv,ANSIBLE_DEBUG,az role assignment listFault injection
Cost control and cleanup··✓····✓az group delete,state: absentteardown.yml

Topics not covered in this lesson (and where to learn them)

TopicWhy not in this lessonWhere to learn
AWS EC2, SSM connection plugin (no need to open SSH)Belongs to AWS topicsLesson 4
GitHub Actions + OIDC federated credentials, AWX / AAP, Event-Driven AnsibleBelongs to automation pipelinesLesson 5 (M1 of this lesson only introduces oidc_token the parameter exists)
Multi-tier architecture (nginx LB + 2 app nodes + PostgreSQL), VMSS rolling configurationBeyond 1 hourLesson 6
Windows VMs (WinRM / OpenSSH for Windows), Azure Arc hybrid machinesrequire different connection methodsAnsible Windows Guide; the dynamic inventory's include_arc_resource_groups options: see the official plugin docs
Ansible management of AKS and Container AppsContainer platforms are usually managed by Terraform/Bicep + GitOpsK8s lesson; azure_rm_aks,azure_rm_containerapp Module docs
Terraform details for building Azure infrastructureThis lesson's M6 covers only the division of workTerraform Lesson 3

How to use this courseware

10 pages per module
Principles · diagrams · animation · commands · labs · production cases · troubleshooting · quiz · voice · video. Recommended: read “Principles” and “Animation” first, then do the “Lab”. M2's animation is the core of this lesson.
Learning progress
A quiz score ≥ 70% or clicking “Mark this module complete” counts toward progress, saved in this browser (cleared on refresh if local storage is disabled).
Chinese voice
The “Voice” page reads the narration script aloud using the browser's built-in Web Speech API (en-US); if no Chinese voice pack is installed, the narration script can still be read or passed to a TTS tool.
Cost and Security Notice This lesson creates real resources in your subscription: 1 Standard_B2s VM, 1 Standard public IP, 1 managed disk, optionally 1 Key Vault and 1 Azure Bastion. Running only the VM costs roughly 0.06 USD per hour (canadacentral; check prices in the Azure Pricing Calculatorfor current prices); Bastion Standard is billed hourly and is considerably more expensive, so delete it right after finishing M4's Bastion part. Run M8's cleanup commands at the end of every study session: az group delete -n rg-ansible-lab --yes --no-wait.
Version Notes Baseline for this lesson: ansible-core 2.21 (control node Python 3.12–3.14), Ansible community package 14.x,azure.azcollection 4.2.0 (released 2026-10-30; the collection requires ansible-core ≥ 2.16 and Python ≥ 3.10). azure.azcollection 4.0.0 (2026-08-31) is a major version: it removed the lookup plugin's use_cli option (use auth_source: cli), and removed azure_rm_virtualmachine non-managed disk parameters, and removed the retired MySQL/PostgreSQL Single Server and MariaDB modules. Tutorials from before 2023 often use use_cli,storage_account_name,requirements-azure.txt; copying them will cause errors.

Module 0 · Warm-up & Azure Preparation (complete before class)

Confirm that the control node and myapp role are still in place, and prepare the Azure subscription, permissions, SSH key and cost expectations
Before class ≈ 10 minUbuntu 24.04 control nodeRequires an Azure subscription
Prerequisites
  • CompletedLesson 1andLesson 2: the control node has the project directory ~/ansible-lab, which contains ansible.cfg and myapp role (roles/myapp: installs a Python venv and a gunicorn systemd service listening 8000, depends on the local redis-server, provides /healthz).
  • Control node: Ubuntu 24.04 LTS (local machine, WSL2 or a small VM), Python 3.12, with pipx install --include-deps ansible installed the Ansible community package 14.x (ansible-core 2.21).
  • An Azure subscription, with your account holding at least Contributor; M5 also requires the ability to assign Key Vault RBAC roles (Owner or User Access Administrator/Role Based Access Control Administrator), otherwise ask your administrator to grant them in advance.
  • Azure CLI installed (az).

Continuity with the previous lesson: names and variables carried over

NameValueSource / Purpose
Project directory~/ansible-labLessons 1–2; this lesson adds subdirectories azure/
Application roleroles/myapp, variable myapp_port: 8000,myapp_redis_password (encrypted with Vault in Lesson 2)Reused unchanged in this lesson; only the inventory and secret source change
Resource grouprg-ansible-labCreated in this lesson, fully deleted at the end
RegioncanadacentralSame as the Docker lesson
VMvm-myapp-01,Standard_B2s, Ubuntu 24.04 (Canonical:ubuntu-24_04-lts:server:latest)Created in M3
Tagsenv=lab,app=myapp,role=web,owner=<your name>M2 dynamic inventory groups by tag; M8 cleans up by tag
Administrator userazureuser + ~/.ssh/id_ed25519M4 SSH login

Step 1: Check the control node

cd ~/ansible-lab
ansible --version | head -3
python3 --version
ls roles/myapp/tasks roles/myapp/templates
ansible-galaxy collection list azure.azcollection
ansible [core 2.21.5]
  config file = /home/andy/ansible-lab/ansible.cfg
  configured module search path = ['/home/andy/.ansible/plugins/modules', ...]
Python 3.12.3
main.yml  install.yml  service.yml
myapp.service.j2  app.env.j2

# /home/andy/.local/share/pipx/venvs/ansible/lib/python3.12/site-packages/ansible_collections
Collection         Version
------------------ -------
azure.azcollection 3.x.x

community package ansible already bundles azure.azcollection, but its version follows the community package release cadence and may lag behind 4.2.0 on Galaxy; more importantly,the community package does not install the Azure Python SDK that the collection requires. M1 addresses both issues.

Step 2: If the myapp role is missing (quick rebuild of the minimal version)

If you skipped the first two lessons, use the minimal role below instead (function: installs redis + venv + gunicorn, managed by systemd). For the full version, return to Lessons 1–2.

mkdir -p ~/ansible-lab/roles/myapp/{tasks,templates,defaults,handlers,files} && cd ~/ansible-lab
cat > roles/myapp/defaults/main.yml <<'EOF'
myapp_user: myapp
myapp_dir: /opt/myapp
myapp_port: 8000
myapp_redis_password: "change-me"
EOF
cat > roles/myapp/files/app.py <<'EOF'
import os, redis
from flask import Flask
app = Flask(__name__)
r = redis.Redis(host="127.0.0.1", password=os.environ.get("REDIS_PASSWORD"))
@app.get("/")
def index():
    return f"Hello from {os.uname().nodename}! visits={r.incr('hits')}\n"
@app.get("/healthz")
def healthz():
    r.ping(); return "ok\n"
EOF
cat > roles/myapp/tasks/main.yml <<'EOF'
- name: Install OS packages
  ansible.builtin.apt:
    name: [python3-venv, redis-server]
    update_cache: true
    cache_valid_time: 3600
- name: Configure redis password
  ansible.builtin.lineinfile:
    path: /etc/redis/redis.conf
    regexp: '^#?\s*requirepass '
    line: "requirepass {{ myapp_redis_password }}"
  no_log: true
  notify: restart redis
- name: Create service user
  ansible.builtin.user: { name: "{{ myapp_user }}", system: true, shell: /usr/sbin/nologin, create_home: false }
- name: Create app dir
  ansible.builtin.file: { path: "{{ myapp_dir }}", state: directory, owner: "{{ myapp_user }}", mode: "0755" }
- name: Copy app
  ansible.builtin.copy: { src: app.py, dest: "{{ myapp_dir }}/app.py", owner: "{{ myapp_user }}", mode: "0644" }
  notify: restart myapp
- name: Python venv with deps
  ansible.builtin.pip:
    name: [flask, "gunicorn==23.*", redis]
    virtualenv: "{{ myapp_dir }}/venv"
    virtualenv_command: python3 -m venv
- name: Env file
  ansible.builtin.copy:
    content: "REDIS_PASSWORD={{ myapp_redis_password }}\n"
    dest: /etc/myapp.env
    mode: "0600"
  no_log: true
  notify: restart myapp
- name: systemd unit
  ansible.builtin.template: { src: myapp.service.j2, dest: /etc/systemd/system/myapp.service, mode: "0644" }
  notify: restart myapp
- name: Enable myapp
  ansible.builtin.systemd_service: { name: myapp, enabled: true, state: started, daemon_reload: true }
EOF
cat > roles/myapp/templates/myapp.service.j2 <<'EOF'
[Unit]
Description=myapp (Flask + gunicorn)
After=network-online.target redis-server.service
[Service]
User={{ myapp_user }}
WorkingDirectory={{ myapp_dir }}
EnvironmentFile=/etc/myapp.env
ExecStart={{ myapp_dir }}/venv/bin/gunicorn --bind 0.0.0.0:{{ myapp_port }} --workers 2 app:app
Restart=on-failure
[Install]
WantedBy=multi-user.target
EOF
cat > roles/myapp/handlers/main.yml <<'EOF'
- name: restart redis
  ansible.builtin.systemd_service: { name: redis-server, state: restarted }
- name: restart myapp
  ansible.builtin.systemd_service: { name: myapp, state: restarted, daemon_reload: true }
EOF

Step 3: Log in to Azure, confirm subscription and permissions

az login                         # no browser environment: az login --use-device-code
az account set --subscription "<subscription name or ID>"
az account show --query "{name:name, id:id, tenant:tenantId, user:user.name}" -o table
az role assignment list --assignee "$(az ad signed-in-user show --query id -o tsv)" \
  --all --query "[].{role:roleDefinitionName, scope:scope}" -o table
az vm list-usage -l canadacentral --query "[?contains(name.value,'standardBSFamily')]" -o table
Name        Id                                    Tenant                                User
----------  ------------------------------------  ------------------------------------  -----------------
Lab-Sub     00000000-1111-2222-3333-444444444444  aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee  andy@contoso.com
Role         Scope
-----------  ---------------------------------------------------
Contributor  /subscriptions/00000000-1111-2222-3333-444444444444
CurrentValue    Limit    LocalName
--------------  -------  --------------------------------
0               10       Standard BS Family vCPUs

Note: Subscriptions with a B-series quota of 0 (some free/student subscriptions) will fail to create VMs; you can switch to Standard_D2s_v5 or another size with quota, or request a quota in the portal.

Step 4: Prepare the SSH key and your public IP

test -f ~/.ssh/id_ed25519 || ssh-keygen -t ed25519 -N "" -f ~/.ssh/id_ed25519 -C "ansible-lab"
MY_IP=$(curl -s https://api.ipify.org); echo "$MY_IP"
mkdir -p ~/ansible-lab/azure/{inventory,playbooks,group_vars}
Note Company networks often have multiple egress IPs (or go through a proxy),api.ipify.org return only one of them. In the M4 lab, if SSH times out, the first thing to check is the source IP in the NSG.

Warm-up: answer from memory (30 seconds)

When Ansible runs a task, where does the module code execute?

By default on the managed node: the control node renders the module and parameters and sends them over SSH; the managed node's Python executes them and returns JSON. But the azure_rm_* modules in this lesson are an exception: they call the Azure REST API, usually hosts: localhost + connection: local, running on the control node — which is exactly why the Azure SDK must be installed in Ansible's environment on the control node.

Static inventory inventory.ini has what limitations?

Hard-coded host IPs. Cloud VMs get rebuilt, scaled and given new IPs, so static inventory goes stale quickly. M2 uses dynamic inventory to query the current VMs from the Azure API on every run.

What is the difference between the Ansible Vault in Lesson 2 and Azure Key Vault in this lesson?

Ansible Vault stores secrets encrypted in the repository, requiring a decryption password; Azure Key Vault keeps secrets in a cloud service, with access controlled by Entra ID identities and RBAC, auditable and rotatable. M5 covers how to read from Key Vault at playbook runtime.

Environment self-check list

Module 1 · azure.azcollection and Authentication

00:00 – 06:00 · The collection is only a “shell”; the real work is done by the Azure Python SDK on the control node; where credentials come from is determined by auth_source
6 minazure.azcollection 4.2.04.0.0 has breaking changes★★★★★
Learning objectives
  • Use ansible-galaxy to install/upgrade the collection, and install the collection directory's requirements.txt into the same Python environment that runs Ansible (with pipx, use pipx inject).
  • State auth_source: auto 's lookup order: module parameters → environment variables → ~/.azure/credentials → Azure CLI; know that managed identity is not in the auto chain, so it must be set explicitly auth_source: msi.
  • Create a least-privilege service principal for automation and provide it to Ansible via environment variables or a credentials file.
Prerequisites: Lesson 1's module execution model; Azure Entra ID and RBAC basics. Importance:★★★★★ (all later modules depend on this step)

What: what azure.azcollection is

azure.azcollection is an Ansible collection maintained by Microsoft and the Red Hat community (GitHub ansible-collections/azure), containing hundreds of azure_rm_* modules (and corresponding *_info read-only modules),azure_rm / azure_kql dynamic inventory plugins,azure_keyvault_secret lookup plugins, etc. The latest version verified in 2026-11 is 4.2.0 (2026-10-30),meta/runtime.yml declares requires_ansible: '>=2.16.0', and the README requires Python ≥ 3.10.

The collection itself is only Python source; each module, when executed, import azure.mgmt.compute,azure.identity etc. Azure SDK for Python packages, which are listed in the collection root directory's requirements.txt (4.2.0 pins azure-identity==1.25.2,azure-mgmt-compute==33.0.0,azure-cli-core==2.91.0 and dozens of versions).

Why: why dependencies must be installed on the control node

azure_rm_* modules call the Azure Resource Manager (ARM) REST API and do not need to log in to any VM. They almost always run with hosts: localhost,connection: local : the control node is the “managed node”, and the module executes on the control node with Ansible's own Python interpreter. If the SDK is installed in the system Python but Ansible runs in a pipx virtual environment, you will see Failed to import the required Python library (azure-mgmt-...).

How: installation and authentication

StepCommandKey points
1 Install/upgrade collectionansible-galaxy collection install azure.azcollection --upgradeinstall to ~/.ansible/collections, takes precedence over the older version bundled with the community package (collections_path order)
2 Install SDKpipx inject ansible -r ~/.ansible/collections/ansible_collections/azure/azcollection/requirements.txtWith a pip virtual environment, use venv/bin/pip install -r …
3 Choose credentialsauth_source parameters or ANSIBLE_AZURE_AUTH_SOURCE environment variablesauto (default) / cli / env / credential_file / msi

5 credential sources

SourceHow to provideSuitable forNotes
Azure CLI (cli)first az login, reuses the CLI token cachepersonal laptop, interactive labsaz must be installed separately (OS package or standalone venv),do not put azure-cli via pip into Ansible's environment — the official docs explicitly say this conflicts with the SDK versions pinned in requirements.txt
Service principal (SP)client_id + secret (or certificate x509_certificate_path/thumbprint) + tenant + subscription_idCI, AWX, shared automation accountskeys expire (default 1 year) and must be rotated; scope them to the resource group
Environment variables (env)AZURE_CLIENT_ID,AZURE_SECRET,AZURE_TENANT (or AZURE_TENANT_ID),AZURE_SUBSCRIPTION_IDinjected by CI pipelinesnote that it is AZURE_SECRET, not the usual Azure SDK convention AZURE_CLIENT_SECRET
Credentials file (credential_file)~/.azure/credentials (INI format; section name is the profile; default [default])switch between multiple subscriptions (profile: / AZURE_PROFILE)in plaintext,chmod 600; do not commit to Git
Managed identity (msi)The control node itself is an Azure VM/container; enable a system- or user-assigned managed identity; for user-assigned, pass client_idAWX / self-hosted runners running inside Azurenot in the auto chain, must be set explicitly auth_source: msi; no keys to manage

Also supports OIDC workload federation: oidc_token / oidc_token_file_path (environment variables AZURE_FEDERATED_TOKEN / AZURE_FEDERATED_TOKEN_FILE) together with client_id and tenant, used for GitHub Actions etc.; practiced in Lesson 5.

When: which to choose

  • Local learning: az login + auth_source: cli (explicitly written out, to avoid leftover AZURE_* variables “taking precedence”).
  • CI: prefer OIDC federated credentials (no long-lived keys); next SP + certificate; SP + secret only as a last resort.
  • Azure-hosted control node: managed identity.

Comparison with similar technologies

Ansible azure.azcollectionTerraform azurerm providerAzure CLI / Bicep
DependenciesControl node Python + SDK (requirements.txt)Single provider binary (Go)az CLI
Credential chainauto: parameters → env → credentials file → CLI; MSI must be set explicitlyprovider block / ARM_* environment variables / CLI / MSI / OIDCaz login any of the methods
StateStateless; queries Azure's actual state on each runstate fileARM deployment history (no local state)
Common misconceptions① “ansible-galaxy collection install will automatically install Python dependencies” — No, Galaxy only installs collection files. ② “auto automatically uses the VM's managed identity” — No; the auto chain is parameters → env → credentials file → CLI. ③ “sudo pip install -r requirements.txt is enough” — what gets installed is the system Python, which the pipx Ansible cannot see; and Ubuntu 24.04's system Python is protected by PEP 668, so it will report externally-managed-environment. ④ “The lookup plugin's use_cli: true still works” — removed in 4.0.0; use auth_source: cli.

Architecture diagram: a single azure_rm_* task from control node to ARM

Control node (Ubuntu 24.04 · pipx venv ~/.local/share/pipx/venvs/ansible) ansible-playbookhosts: localhostconnection: local azure_rm_* modulesAnsiballZ packagingsame Python executes Azure SDKazure-identityazure-mgmt-* Credential resolution (azure_rm_common._get_credentials) ① Module parametersclient_id… ② Environment variablesAZURE_* ③ Credentials file~/.azure/credentials ④ Azure CLIaz login cache MSIauth_source only HTTPS Microsoft Entra IDlogin.microsoftonline.com → access token Azure Resource Managermanagement.azure.comRBAC authorization → resource provider Microsoft.Compute / NetworkPUT / GET / DELETE
Figure 1-1: azure_rm_* modules run on the control node; via the Azure SDK they first obtain an Entra ID token, then call the ARM REST API

Flowchart: auth_source decision

auth_source = ?Default auto cli → read-only az login env → read-only AZURE_* credential_file → profile msi → IMDS 169.254.169.254 auto: parameters have client_id/ad_user? → AZURE_* environment variables present?→ ~/.azure/credentials [default]? → az CLI logged in? → otherwise error
Figure 1-2: explicitly setting auth_source reads only one source; auto follows a fixed order “first come, first served”, so leftover environment variables override az login

Interactive simulator: where do credentials really come from?

Tick the credential sources that “exist” on the control node, select auth_source, then play. The simulator checks them one by one in the real order of azure_rm_common._get_credentials() and displays in the terminal -vvv / what appears in the logs, and the subsequent calls to Entra ID and ARM.

auth_source:

Core commands and parameters

CommandPurposeKey parameters / notes
ansible-galaxy collection install azure.azcollectionInstall collection--upgrade upgrade to latest; azure.azcollection:==4.2.0 pin version; -r requirements.yml
ansible-galaxy collection list azure.azcollectionView versions across all pathsshows both the community package's bundled version and the user-directory version; the one listed first takes effect
pipx inject ansible -r …/requirements.txtInstall SDK into the pipx ansible environmentre-run once after upgrading the collection
az ad sp create-for-rbacCreate service principal and assign role--role Contributor --scopes /subscriptions/…/resourceGroups/rg-ansible-lab
ansible localhost -m azure.azcollection.azure_rm_resourcegroup_infoAuthentication smoke test-a "auth_source=cli"; -vvv View details
ANSIBLE_AZURE_AUTH_SOURCE=cliSpecify credential source globallyapplies to both modules and inventory plugins

Install collection and SDK (pipx environment)

ansible-galaxy collection install azure.azcollection --upgrade
ansible-galaxy collection list azure.azcollection
pipx inject ansible -r ~/.ansible/collections/ansible_collections/azure/azcollection/requirements.txt
pipx runpip ansible list 2>/dev/null | grep -E "^azure-(identity|mgmt-compute|mgmt-network|cli-core) "
Starting galaxy collection install process
...
azure.azcollection:4.2.0 was installed successfully

# /home/andy/.ansible/collections/ansible_collections
Collection         Version
------------------ -------
azure.azcollection 4.2.0

# /home/andy/.local/share/pipx/venvs/ansible/lib/python3.12/site-packages/ansible_collections
Collection         Version
------------------ -------
azure.azcollection 3.x.x
...
azure-cli-core      2.91.0
azure-identity      1.25.2
azure-mgmt-compute  33.0.0
azure-mgmt-network  ...

How to verify: User directory (~/.ansible/collections) comes first; 4.2.0 takes effect. Common error: Running outside pipx with pip install; after upgrading the collection, forgot to re-inject, so the SDK packages needed by new modules are missing. Production use: Bake the collection and SDK into an execution environment image (ansible-builder, Lesson 5), keeping CI consistent with local.

Plain venv environment (when not using pipx)

python3 -m venv ~/venvs/ansible && . ~/venvs/ansible/bin/activate
pip install ansible-core==2.21.*
ansible-galaxy collection install azure.azcollection
pip install -r ~/.ansible/collections/ansible_collections/azure/azcollection/requirements.txt

Pin versions: collections/requirements.yml

collections:
  - name: azure.azcollection
    version: "==4.2.0"
  - name: community.general
    version: ">=10.0.0"

Service principal: minimum scope

SUB=$(az account show --query id -o tsv)
az group create -n rg-ansible-lab -l canadacentral --tags env=lab app=myapp
az ad sp create-for-rbac -n sp-ansible-lab --role Contributor \
  --scopes /subscriptions/$SUB/resourceGroups/rg-ansible-lab
{
  "appId": "11111111-2222-3333-4444-555555555555",
  "displayName": "sp-ansible-lab",
  "password": "xxxxx~xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
  "tenant": "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee"
}
# Method A: environment variables (note AZURE_SECRET)
export AZURE_SUBSCRIPTION_ID=$SUB
export AZURE_CLIENT_ID=11111111-2222-3333-4444-555555555555
export AZURE_SECRET='xxxxx~xxxx'
export AZURE_TENANT=aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee

# Method B: credentials file
install -m 600 /dev/null ~/.azure/credentials
cat > ~/.azure/credentials <<EOF
[default]
subscription_id=$SUB
client_id=11111111-2222-3333-4444-555555555555
secret=xxxxx~xxxx
tenant=aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee
EOF

Smoke test

ansible localhost -m azure.azcollection.azure_rm_resourcegroup_info -a "name=rg-ansible-lab auth_source=cli"
localhost | SUCCESS => {
    "changed": false,
    "resourcegroups": [
        {
            "id": "/subscriptions/0000.../resourceGroups/rg-ansible-lab",
            "location": "canadacentral",
            "name": "rg-ansible-lab",
            "tags": { "app": "myapp", "env": "lab" }
        }
    ]
}

If this succeeds but the playbook fails, it is almost always because the two used different Python environments or different credential sources.

Lab 1: install the collection, compare three credential sources (about 6 min)

Install collection and SDK: run the pipx install section on the “Commands” page and confirm azure.azcollection 4.2.0 takes effect.
Authenticate with Azure CLI:
cd ~/ansible-lab/azure
cat > ansible.cfg <<'EOF'
[defaults]
roles_path = ../roles
inventory = inventory/
host_key_checking = True
interpreter_python = auto_silent
stdout_callback = default
callback_result_format = yaml

[inventory]
enable_plugins = azure.azcollection.azure_rm, ansible.builtin.yaml, ansible.builtin.ini
EOF
cat > playbooks/whoami.yml <<'EOF'
- name: Which identity am I using?
  hosts: localhost
  connection: local
  gather_facts: false
  tasks:
    - name: List resource groups visible to this identity
      azure.azcollection.azure_rm_resourcegroup_info:
        auth_source: "{{ az_auth | default('auto') }}"
      register: rgs
    - name: Show names
      ansible.builtin.debug:
        msg: "{{ rgs.resourcegroups | map(attribute='name') | list }}"
EOF
ansible-playbook playbooks/whoami.yml -e az_auth=cli
TASK [Show names] *************************************************************
ok: [localhost] =>
    msg:
    - rg-ansible-lab
    - NetworkWatcherRG
    - rg-shared-dns

The CLI identity is you, and you can see all resource groups in the subscription you have permission for.

Authenticate with service principal (environment variables): create per the “Commands” page sp-ansible-lab and export the 4 variables, then:
ansible-playbook playbooks/whoami.yml -e az_auth=env
ok: [localhost] =>
    msg:
    - rg-ansible-lab

The SP was granted only rg-ansible-lab, so it sees just this one resource group — this is least privilege. Newly created role assignments can take a few minutes to take effect.

Observe auto's “first come, first served”: run with environment variables still present ansible-playbook playbooks/whoami.yml (without az_auth). The result matches env: in the auto chain environment variables come before the CLI. Run unset AZURE_CLIENT_ID AZURE_SECRET AZURE_TENANT afterwards and the result returns to the CLI identity.
(Optional) credentials file: write to ~/.azure/credentials then run -e az_auth=credential_file. Delete after the lab: shred -u ~/.azure/credentials.
Cleanup and security: later sections of this lesson default to using auth_source: cli. Delete the SP after the capstone: az ad sp delete --id <appId>. Keep the resource group for M2/M3.

Case 1: a module that worked “yesterday” throws ImportError in CI today

Problem: Every pipeline run ansible-galaxy collection install azure.azcollection has no version pin; after upgrading the collection, a new dependency on a new SDK package was added, but the SDK in the pipeline image is still old. Approach: in collections/requirements.yml pin ==4.2.0, and when building the image also install the matching version of the collection's requirements.txt; upgrade the collection via PR, and run a *_info smoke playbook in the PR. Limitation: Major collection versions (e.g. 4.0.0) remove parameters; read the BREAKING CHANGE section of the CHANGELOG before upgrading.

Case 2: a leftover environment variable made the playbook operate on the wrong subscription

Problem: While debugging CI, an engineer exported the production SP's AZURE_*, then locally az login to the test subscription; the auto chain preferred environment variables and created resources in the production subscription. Approach: All playbooks explicitly set auth_source (or set in group_vars azure_auth_source variables referenced uniformly), and at the start of the play use azure_rm_subscription_info to assert the subscription ID. Configuration:ansible.builtin.assert: that: sub.subscriptions[0].subscription_id == expected_sub.

Case 3: AWX running on AKS, using workload identity to avoid keys

Problem: The security team requires the automation platform to stop storing SP keys. Approach: AKS enables Workload Identity; the webhook injects into the Pod AZURE_CLIENT_ID,AZURE_TENANT_ID,AZURE_FEDERATED_TOKEN_FILE; the collection reads AZURE_FEDERATED_TOKEN_FILE, and in AZURE_TENANT falls back to when not set AZURE_TENANT_ID. Limitation: The federated credential's subject must match the ServiceAccount exactly; details in Lesson 5.

Common errors and fixes

Failed to import the required Python library (ansible[azure] (azure >= 2.0.0)) on controller's Python /home/andy/.local/share/pipx/venvs/ansible/bin/python

Cause: The Azure SDK is not installed in the interpreter running Ansible (the message shows the interpreter path).

ansible --version | grep "python version"
pipx runpip ansible list | grep -c "^azure-"

Fix:pipx inject ansible -r ~/.ansible/collections/ansible_collections/azure/azcollection/requirements.txt.

error: externally-managed-environment × This environment is externally managed

Cause: Ubuntu 24.04's system Python follows PEP 668, which forbids direct pip installs.

Fix: use pipx inject or a venv; do not add --break-system-packages.

Failed to get credentials. Either pass as parameters, set environment variables, define a profile in ~/.azure/credentials, or log in with Azure CLI (`az login`).

Cause: The auto chain has no credentials from all four sources, or az is not on PATH.

which az; az account show -o table; env | grep ^AZURE_ | sed 's/=.*/=***/'

Fix:az login; in CI check the variable names (AZURE_SECRET rather than AZURE_CLIENT_SECRET).

ERROR: Could not install packages due to an OSError / ResolutionImpossible: azure-cli 2.x requires azure-mgmt-compute==…

Cause: Installing the full azure-cli via pip into the Ansible environment conflicts with the versions pinned in requirements.txt.

Fix: rebuild the Ansible environment; az install from Microsoft's apt repository (curl -sL https://aka.ms/InstallAzureCLIDeb | sudo bash).

Unsupported parameters for (azure.azcollection.azure_keyvault_secret) lookup: use_cli

Cause: 4.0.0 removed use_cli.

Fix: change to auth_source='cli'.

Command-line operations
1. Write the command that installs azure.azcollection's Python dependencies into the pipx-managed ansible environment.
pipx inject ansible -r ~/.ansible/collections/ansible_collections/azure/azcollection/requirements.txt
2. Without changing the playbook, force this run to use only Azure CLI credentials.
ANSIBLE_AZURE_AUTH_SOURCE=cli ansible-playbook playbooks/whoami.yml
Scenario analysis
The team deployed AWX on an Azure VM; the VM has a system-assigned managed identity with Contributor on the resource group, but the playbook still reports “Failed to get credentials”. Why?

auth_source defaults to auto, and the chain has no MSI. You need to set auth_source: msi (or environment variable ANSIBLE_AZURE_AUTH_SOURCE=msi); for a user-assigned identity, also pass its client_id; if there are multiple subscriptions, pass subscription_id. Also confirm the AWX job container can reach IMDS (169.254.169.254).

Verified teaching videos

▶
Ansible to automate Microsoft Azure — Red Hat
English · Red Hat official channel · introduces the Azure module, credentials and the Tower dynamic inventory (recorded earlier; the UI is Tower; collection versions and parameters follow this lesson)
▶
Ansible in 100 Seconds — Fireship
English · about 2 min · quick review of Ansible's agentless model

Official docs

Video storyboard script (about 75 seconds)

This courseware cannot generate video/MP3 directly; storyboards and narration scripts are provided for a video tool.

Shot 1 · 0–15s
Visual: inside the control-node box, the ansible-playbook icon connects to the azure_rm module, which connects to a stack of SDK packages.
Narration: Azure modules run on the control node; the Azure Python SDK is what actually calls the cloud API.
Shot 2 · 15–35s
Visual: terminal runs pipx inject; packages from requirements.txt drop one by one into the ansible virtual environment.
Narration: Galaxy installs only the collection; the SDK must be installed into the same environment with pipx inject.
Shot 3 · 35–60s
Visual: four tiles light up in turn: module parameters, environment variables, credentials file, Azure CLI; beside them a dashed MSI tile.
Narration: auto mode goes in this order, first come first served. Managed identity is not in the chain; you must explicitly set the auth source to msi.
Shot 4 · 60–75s
Visual: service principal card; the scope arrow points only at rg-ansible-lab.
Narration: the automation identity is granted only resource-group-level permissions.
or get a quiz score ≥ 70%

Module 2 · Dynamic inventory azure_rm

06:00 – 13:00 · The inventory is no longer a hard-coded IP list but a query to the Azure API on every run: list VMs → fill in network and power state → group by tags
7 mininventory plugin · azure.azcollection.azure_rmThe file name must end with azure_rm.yml★★★★★
Learning objectives
  • Write a usable lab.azure_rm.yml: plugin,auth_source,include_vm_resource_groups,hostnames,keyed_groups,conditional_groups,hostvar_expressions/compose.
  • Explain the plugin's real workflow: list VMs (Compute API) → batch-fetch instanceView, NIC, public IP (ARM /batch) → generate hostvars → filter → group.
  • Be able to use ansible-inventory --graph / --host / --list to verify, enable caching and know when to refresh (--flush-cache).
Prerequisites: Lesson 1's inventory, groups and host_vars; Jinja2 expressions. Importance:★★★★★ (core capability of Ansible in the cloud)

What: the dynamic inventory plugin

Ansible's inventory plugin inventory plugins run on each execution ansible/ansible-playbook/ansible-inventory time, converting external data sources into hosts, groups and variables. azure.azcollection.azure_rm The plugin queries Azure Resource Manager and returns VMs in the subscription (or a specified resource group); it can also include VMSS instances (include_vmss_resource_groups), Azure Arc machines (include_arc_resource_groups) and Azure Stack HCI VMs.

plugin only accepts files whose names end in azure_rm.yml or azure_rm.yaml ends with (source code verify_file()), for example lab.azure_rm.yml. The plugin must also be [inventory] enable_plugins enabled (the default list includes auto, which loads based on the plugin: key in the file, so explicit configuration is usually unnecessary).

Why: why dynamic inventory is required in the cloud

  • VM IPs change (after a rebuild, or when a deallocated VM's dynamic public IP changes), so static inventory goes stale quickly.
  • Autoscaling and blue-green replacement keep changing the number of hosts.
  • Tags become the single source of truth: Terraform/Bicep/Ansible tag VMs with role=web, and the configuration stage hosts: tag_role_web selects them automatically — this is the “hand-off point” covered in M6.

How: what the plugin does internally (4.2.0 source)

  1. Parse configuration and authenticate: read auth_source and other options, and obtain an Entra ID token (same credential chain as M1).
  2. List VMs: for each include_vm_resource_groups issue GET /subscriptions/{sub}/resourceGroups/{rg}/providers/Microsoft.Compute/virtualMachines ('*' when a subscription-level list is used), paging by nextLink pages.
  3. Pre-filter: since 4.2.0, only fields from the VM list (such as name,tags,location) of the exclude_host_filters/include_host_filters are evaluated before fetching details, so excluded VMs trigger no follow-up requests (pre-filtering does not apply when cache is enabled).
  4. Batch-fetch details: for each remaining VM, request …/instanceView (power state), NICs and public IPs. By default batch_fetch: true, the plugin bundles these GETs and sends them through ARM's POST /batch?api-version=2015-11-01 in one batch (source comment: up to 500 requests per batch), greatly reducing round trips.
  5. Generate hostvars: name,id,location,tags,powerstate,provisioning_state,public_ipv4_address,public_dns_hostnames,private_ipv4_addresses,os_profile,vmid,availability_zone etc.; by default ansible_host = the first public IP; if none, the first private IP.
  6. Filter: default_host_filters By default, excludes not-running VMs (powerstate != 'running') and VMs that are not fully provisioned; then applies your exclude/include filters.
  7. Naming and grouping: by hostnames determines inventory_hostname; execute hostvar_expressions/compose; then conditional_groups/groups (added when the expression is true) and keyed_groups (generates groups from variable values).

keyed_groups naming rules

configurationhostvar valuegenerated group
{prefix: tag, key: tags}tags = {role: web, env: lab}tag_role_web,tag_env_lab (dictionary: one group per key-value pair)
{prefix: azure_loc, key: location}canadacentralazure_loc_canadacentral
{prefix: role, key: tags.role | default('none')}web / missingrole_web / role_none
{key: os_profile.system} (no prefix)linux_linux (leading_separator: true prepends a leading underscore by default)

Illegal characters in group names (such as -,., spaces) are replaced with underscores: tag app=my-app generates tag_app_my_app.

When: which options to use when

  • Limit scope: always write include_vm_resource_groups, to avoid scanning the whole subscription (slow, prone to throttling, may pick up someone else's VMs).
  • Private connectivity only (Bastion/VPN/running inside Azure): hostvar_expressions: {ansible_host: private_ipv4_addresses | first}.
  • Large subscription, frequent runs: cache: true + cache_plugin: ansible.builtin.jsonfile + a reasonable cache_timeout.
  • Name collision: the default inventory_hostname is “VM name + underscore + short hash” to guarantee uniqueness; within a single resource group you can use hostnames: [name] to get more readable names.

Comparison with similar technologies

Static INI/YAMLazure_rm pluginazure_kql pluginTerraform output generates inventory
Data sourceHand-writtenARM Compute/Network APIAzure Resource Graph (KQL query)state output
Real-timeManual maintenanceQuery each run (cacheable)Resource Graph has a short indexing delayReflects only the last apply
Suitable forLocal experimentsMost scenariosLarge-scale queries across many subscriptionsOne-time bootstrap
Common misconceptions① “A file named azure.yml also works” — No; the plugin rejects files not ending in azure_rm.yml/azure_rm.yaml ; the inventory becomes empty (only localhost implicitly exists). ② “Stopped VMs will also appear” — by default they are default_host_filters excluded. ③ “The keyed_groups key can be written as tags['role'] anything else” — the key is a Jinja2 expression evaluated against hostvars; if a variable does not exist it errors or is skipped, so you need | default(...). ④ “The inventory plugin creates VMs” — it is read-only.

Architecture diagram: data flow of the dynamic inventory

lab.azure_rm.ymlplugin: azure_rminclude_vm_resource_groupskeyed_groups / filters InventoryModule.parse()verify_file: *.azure_rm.ymlcredentials → tokenrequest queue / cache ① GET VM list ② POST /batch Azure Resource Manager Compute: virtualMachines …/instanceView (powerstate) Network: networkInterfaces Network: publicIPAddresses hostvars (per VM)tags, location, powerstatepublic_ipv4_address, private_ipv4_addressesansible_host (public IP preferred by default) Filterdefault_host_filtersexclude_host_filtersinclude_host_filters Naming and groupinghostnames → inventory_hostnamecompose / hostvar_expressionsconditional_groups · keyed_groups → tag_role_web
Figure 2-1: the plugin lists VMs first, then batch-fills power state and network info, and finally filters, names and groups them, for the playbook's hosts: pattern

Diagram: how tags become groups

vm-myapp-01env=lab app=myapp role=web vm-myapp-02env=lab app=myapp role=web vm-redis-01env=lab app=myapp role=cache tag_role_web: vm-myapp-01, vm-myapp-02 tag_role_cache: vm-redis-01 tag_env_lab · tag_app_myapp: all 3 hosts azure_loc_canadacentral: all 3 hosts keyed_groups: [{prefix: tag, key: tags}, {prefix: azure_loc, key: location}]
Figure 2-2: a tag dictionary expands into multiple groups; one host can belong to several groups at once

Core animation: the full dynamic inventory generation process

Simulation ansible-playbook -i inventory/lab.azure_rm.yml site-azure.yml What happens before the first task. The resource group has 4 VMs, of which vm-old are deallocated. Below each step the terminal shows the real API calls or -vvvv -level logs.

Azure (rg-ansible-lab)
Ansible in-memory inventory

Core commands and parameters

Command / optionPurposeKey parameters / notes
ansible-inventory -i lab.azure_rm.yml --graphShow groups and hosts as a tree--vars Show variables as well
ansible-inventory --host NAMEView all hostvars of a single hostDebug keyed_groups key expressions
ansible-inventory --list --yamlOutput the full inventory--output file
--flush-cacheIgnore and refresh the inventory cacheUse right after creating a VM
ansible tag_role_web -m pingRun ad-hoc against a dynamic groupGroup names are case-sensitive
-vvvvView plugin loading and API requests“Parsed … inventory source with auto plugin”

Complete inventory file

plugin: azure.azcollection.azure_rm
auth_source: cli                 # explicitly set, to avoid leftover environment variables taking precedence
include_vm_resource_groups:
  - rg-ansible-lab
# Name: prefer the VM name (unique within a single RG), otherwise fall back to the default unique name
hostnames:
  - name
  - default
# Only VMs with the app=myapp tag (relies only on list fields → pre-filtered since 4.2.0)
exclude_host_filters:
  - tags.app | default('') != 'myapp'
conditional_groups:
  webservers: "tags.role | default('') == 'web'"
  linux: "os_profile.system == 'linux'"
keyed_groups:
  - prefix: tag
    key: tags
  - prefix: azure_loc
    key: location
  - prefix: role
    key: tags.role | default('none')
hostvar_expressions:
  # Use public IP if present, otherwise private (Bastion/VPN scenarios)
  ansible_host: (public_ipv4_address + private_ipv4_addresses) | first
  ansible_user: "'azureuser'"
  myapp_env: tags.env | default('dev')
# Cache (optional): reduces API calls
cache: true
cache_plugin: ansible.builtin.jsonfile
cache_connection: ~/.cache/ansible-azure-inventory
cache_timeout: 600

Note on quotes:hostvar_expressions value is a Jinja2 expression; string constants must be wrapped in another layer of quotes: "'azureuser'". Written as azureuser is treated as a nonexistent variable.

cd ~/ansible-lab/azure
ansible-inventory -i inventory/lab.azure_rm.yml --graph
@all:
  |--@ungrouped:
  |--@webservers:
  |  |--vm-myapp-01
  |--@linux:
  |  |--vm-myapp-01
  |--@tag_env_lab:
  |  |--vm-myapp-01
  |--@tag_app_myapp:
  |  |--vm-myapp-01
  |--@tag_role_web:
  |  |--vm-myapp-01
  |--@tag_owner_andy:
  |  |--vm-myapp-01
  |--@azure_loc_canadacentral:
  |  |--vm-myapp-01
  |--@role_web:
  |  |--vm-myapp-01
ansible-inventory -i inventory/lab.azure_rm.yml --host vm-myapp-01 | head -40
{
    "ansible_host": "20.151.12.34",
    "ansible_user": "azureuser",
    "availability_zone": null,
    "id": "/subscriptions/0000.../resourceGroups/rg-ansible-lab/providers/Microsoft.Compute/virtualMachines/vm-myapp-01",
    "location": "canadacentral",
    "myapp_env": "lab",
    "name": "vm-myapp-01",
    "os_profile": { "system": "linux" },
    "powerstate": "running",
    "private_ipv4_addresses": [ "10.30.1.4" ],
    "provisioning_state": "succeeded",
    "public_dns_hostnames": [],
    "public_ipv4_address": [ "20.151.12.34" ],
    "resource_group": "rg-ansible-lab",
    "resource_type": "Microsoft.Compute/virtualMachines",
    "tags": { "app": "myapp", "env": "lab", "owner": "andy", "role": "web" },
    ...
}

How to verify:--graph groups you expect appear in --host in ansible_host is a reachable address. Common errors: empty inventory (check file name, permissions, resource group spelling, see M7); VM just created but blocked by cache (--flush-cache). Production use: run first in CI ansible-inventory --graph and assert that the target group is non-empty before deploying, to prevent “0 hosts counts as success”.

Combining with static variables

# all sources in the inventory/ directory are merged; group_vars matches dynamic groups by group name
ls inventory/ group_vars/
cat > group_vars/tag_role_web.yml <<'EOF'
myapp_port: 8000
EOF
ansible-inventory -i inventory/ --host vm-myapp-01 | grep myapp_port

Note group_vars/ must be placed next to the inventory directory or next to the playbook directory to be loaded; this lesson uses ~/ansible-lab/azure/group_vars (when the playbook is in playbooks/ subdirectory, it is recommended to put group_vars inside inventory/ directory, see M7 troubleshooting).

Lab 2: write the inventory first, then watch it go “from empty to populated” (about 6 min)

Write the inventory file: copy the code from the “Commands” page lab.azure_rm.yml save to ~/ansible-lab/azure/inventory/, first change cache: true to false (avoid cache interference during the lab).
There are no VMs in the resource group yet:
cd ~/ansible-lab/azure
ansible-inventory -i inventory/lab.azure_rm.yml --graph
@all:
  |--@ungrouped:

No errors, just empty — this shows authentication and plugin loading both succeeded, there are simply no matching VMs.

Quickly create a temporary VM with the CLI to verify grouping (M3 will formally create VMs with Ansible; this one is only for verifying the inventory; delete after 3 minutes):
az vm create -g rg-ansible-lab -n vm-inv-test --image Ubuntu2404 --size Standard_B1s \
  --admin-username azureuser --ssh-key-values ~/.ssh/id_ed25519.pub \
  --public-ip-address "" --nsg "" --tags env=lab app=myapp role=test owner=$USER
ansible-inventory -i inventory/lab.azure_rm.yml --graph
@all:
  |--@ungrouped:
  |--@linux:
  |  |--vm-inv-test
  |--@tag_env_lab:
  |  |--vm-inv-test
  |--@tag_app_myapp:
  |  |--vm-inv-test
  |--@tag_role_test:
  |  |--vm-inv-test
  ...
  |--@role_test:
  |  |--vm-inv-test

This VM has no public IP, so ansible_host falls back to the private IP (--host vm-inv-test is visible). --public-ip-address "" and --nsg "" indicate no public IP and no NSG are created.

Observe the filter:
az vm deallocate -g rg-ansible-lab -n vm-inv-test
ansible-inventory -i inventory/lab.azure_rm.yml --graph     # VM disappears: default_host_filters excludes non-running
az vm update -g rg-ansible-lab -n vm-inv-test --set tags.app=other
ansible-inventory -i inventory/lab.azure_rm.yml --graph -vvvv 2>&1 | grep -iE "azure_rm|batch" | head

The second time, even if the VM is started, it will be exclude_host_filters excluded.

Enable cache and compare timing: change cache back to true:
time ansible-inventory -i inventory/lab.azure_rm.yml --graph >/dev/null   # first run: calls API and writes cache
time ansible-inventory -i inventory/lab.azure_rm.yml --graph >/dev/null   # second run: reads cache
ls ~/.cache/ansible-azure-inventory/
time ansible-inventory -i inventory/lab.azure_rm.yml --graph --flush-cache >/dev/null
Cleanup:
az vm delete -g rg-ansible-lab -n vm-inv-test --yes --force-deletion none
# NIC, OS disk and VNet auto-created by az vm create are not deleted with the VM:
az resource list -g rg-ansible-lab -o table
az network nic delete -g rg-ansible-lab -n vm-inv-testVMNic
az disk list -g rg-ansible-lab --query "[?starts_with(name,'vm-inv-test')].id" -o tsv | xargs -r az disk delete --yes --ids
az network vnet delete -g rg-ansible-lab -n vm-inv-testVNET

starting with az resource list actual output prevails. This step also foreshadows M8's “orphaned resources”.

Case 1: one playbook managing dev/test/prod across three subscriptions

Problem: The three environments have identical VM structures but different subscriptions. Approach: one inventory directory per environment: inventories/prod/prod.azure_rm.yml (subscription_id and include_vm_resource_groups differ) + each with its own group_vars; at runtime -i inventories/prod. Limitation: Do not use one inventory to scan multiple subscriptions and then distinguish environments by tags — one mistake will hit production.

Case 2: generating an inventory for hundreds of VMs takes 2 minutes

Problem:include_vm_resource_groups: ['*'] Scanning the whole subscription, with many VMs only being filtered out. Approach: limit to the resource group; write conditions that rely only on tags/name as exclude_host_filters the first few entries (evaluated in advance since 4.2.0, no longer fetching NIC/PIP for them); in AWX enable inventory cache and set a cache timeout with “update before run”. For many subscriptions consider the azure_kql (Resource Graph) plugin. Limitation: the plugin does not pre-filter when cache is enabled.

Case 3: rolling configuration of VMSS instances

Problem: Instances scaled out by a VMSS need automatic configuration. Approach:include_vmss_resource_groups: [rg-app], using keyed_groups: [{prefix: vmss, key: vmss.name}] to generate vmss_web groups; in the playbook serial: 20% in batches. Limitation: It is better to bake configuration into the image (Packer + Ansible provisioner) or cloud-init so new instances are ready at boot; covered in Lesson 6.

Common errors and fixes

[WARNING]: Unable to parse /home/andy/ansible-lab/azure/inventory/azure.yml as an inventory source

Cause: file name does not end in azure_rm.yml/azure_rm.yaml ; the plugin's verify_file rejects it; other plugins cannot parse it either.

ansible-inventory -i inventory/azure.yml --graph -vvvv 2>&1 | grep -i "azure_rm inventory filename"

Fix: rename to lab.azure_rm.yml.

[WARNING]: provided hosts list is empty, only localhost is available. Note that the implicit localhost does not match 'all'

Cause: Inventory parsed successfully but has no hosts: resource group name misspelled, VM not running, filter too strict, or the credentials lack permission to see the resource group.

az vm list -g rg-ansible-lab -d --query "[].{n:name,p:powerState,t:tags}" -o table
ansible-inventory -i inventory/lab.azure_rm.yml --list --flush-cache | head

Fix: comment out filters one by one to locate the problem; confirm the identity has Reader or higher. M7's troubleshooting tree has the full process.

Could not match supplied host pattern, ignoring: tag_role_web

Cause: Group does not exist: tag value case differs (Role=Web → tag_Role_Web), tag contains hyphens that get converted, or keyed_groups has no prefix configured.

ansible-inventory -i inventory/ --graph | grep -i role

Fix: standardize tags (all lowercase), or use conditional_groups together with | lower.

Error in creating keyed group name: … 'dict object' has no attribute 'role'

Cause: Some VMs have no role tag, so the expression tags.role fails to evaluate.

Fix:key: tags.role | default('none'), or set default_value; or fail_on_template_errors: false (hides the real problem — use with caution).

Newly created VMs are not in the inventory (appear only a few minutes later)

Cause: the inventory cache has not expired, or the inventory was not refreshed after creating the VM in the same playbook.

Fix: command line --flush-cache; inside the playbook use - ansible.builtin.meta: refresh_inventory (used in M4).

Command-line operations
1. Check vm-myapp-01's powerstate and ansible_host in the dynamic inventory.
ansible-inventory -i inventory/lab.azure_rm.yml --host vm-myapp-01 | grep -E '"(powerstate|ansible_host)"'
2. Write a keyed_groups entry that groups VMs by size (producing groups like size_Standard_B2s ).
keyed_groups:
  - prefix: size
    key: virtual_machine_size | default('unknown')

The hostvars of each VM in the 4.2.0 source include virtual_machine_size (taken from hardwareProfile.vmSize),resource_group (lowercase),security_group,network_interface etc.; first use --host to confirm which variables are available in your version.

Scenario analysis
The deployment pipeline reports an empty “PLAY RECAP” yet shows success, and the new version never went live. What are the possible causes and safeguards?

The dynamic inventory returned 0 hosts (permission change hides the resource group, tags changed, VMs deallocated, stale cached data); Ansible only warns for a play with 0 hosts and does not count it as a failure. Safeguards: ① before deployment, ansible-inventory --graph run a check and assert that the target group's host count ≥ the expected value; ② add to the play ansible.builtin.assert: that: groups['tag_role_web'] | length >= 2 (place it in hosts: localhost the pre-check play); (3) set ANSIBLE_HOST_PATTERN_MISMATCH=error to fail with an error when a group is not found.

Verified instructional videos

▶
Ansible to automate Microsoft Azure — Red Hat
English · includes a demo of the Azure dynamic inventory in Tower (earlier version; same concepts, settings follow this lesson)

No verified dedicated video for azure.azcollection 4.x was found; azure_rm.yml use the official documentation and the storyboard below as the reference.

Official docs

Video storyboard script (about 90 seconds)

This courseware cannot directly generate a video or MP3. The storyboard and narration script are provided and can be handed to a video tool.

Scene 1 · 0–15s
Visual: IPs in a static inventory.ini turn red and expire one by one.
Narration: Cloud IPs change, so a static inventory goes stale quickly.
Scene 2 · 15–40s
Visual: the plugin icon sends GET virtualMachines to ARM, which returns four VM cards; then a batch envelope carrying the instanceView, NIC, and PIP requests flies out.
Narration: The plugin first lists the VMs, then uses batched requests to fill in power state and network addresses.
Scene 3 · 40–65s
Visual: the deallocated vm-old fades out in gray; the tags on the remaining cards fly to the right and form group boxes such as tag_role_web.
Narration: Machines that are not running are filtered out by default, and tags become groups according to the keyed groups rules.
Scene 4 · 65–90s
Visual: the playbook says hosts: tag_role_web, two VMs are highlighted, and SSH connections appear.
Narration: The playbook names only the group, not IPs. Add a new VM tagged role=web and it will be picked up automatically on the next run.
or score ≥ 70% on the quiz

Module 3 · Create Azure resources with Ansible

13:00 – 22:00 · Resource group → VNet → subnet → NSG → public IP → NIC → VM: each module does a GET first and then decides whether to PUT, so it is safe to run it a second time
9 min7 modules, including azure_rm_virtualmachineIncurs charges★★★★☆
Learning objectives
  • Use 7 azure_rm_* modules to explicitly create the VM and its network dependencies, rather than relying on the modules' “automatically create default resources” behavior.
  • Understand how azure_rm modules achieve idempotency: read the existing resource → compare against the desired parameters → PUT/PATCH only when there is a difference; use --check --diff to preview.
  • Use state: absent in reverse dependency order, delete resources, and understand the roles and risks of remove_on_absent and force_delete_nonempty .
Prerequisites: M1 authentication; basics of Azure VNet/NSG/NIC. Importance:★★★★☆ (in production, infrastructure is usually handed to Terraform/Bicep, see M6; but Ansible is convenient for small environments, labs, and temporary resources)

What: resource modules and dependency chain

OrderModule (azure.azcollection)ARM resource typeName in this lesson
1azure_rm_resourcegroupMicrosoft.Resources/resourceGroupsrg-ansible-lab
2azure_rm_virtualnetworkMicrosoft.Network/virtualNetworksvnet-ansible (10.30.0.0/16)
3azure_rm_securitygroupMicrosoft.Network/networkSecurityGroupsnsg-app (22 and 8000 allow only your IP)
4azure_rm_subnet…/virtualNetworks/subnetssnet-app (10.30.1.0/24, associated with nsg-app)
5azure_rm_publicipaddressMicrosoft.Network/publicIPAddressespip-myapp-01 (Standard, Static)
6azure_rm_networkinterfaceMicrosoft.Network/networkInterfacesnic-myapp-01
7azure_rm_virtualmachineMicrosoft.Compute/virtualMachines (+ OS managed disk)vm-myapp-01

Each module has a matching read-only *_info module (for example azure_rm_virtualmachine_info), used for querying and asserting.

Why: why create each layer explicitly

azure_rm_virtualmachine It is very “helpful”: when no NIC is specified, it will automatically create a default NIC and public IP, and place them in the first VNet found in the resource group; azure_rm_networkinterface When no NSG is specified (create_with_security_group default true), it will automatically create an NSG that opens port 22 to Any. These defaults are convenient for demos, but in production they mean: resource names are uncontrolled, SSH is open to the entire internet, and VNet selection is unpredictable. Creating each layer explicitly keeps naming, address planning, and security rules in code.

How: how idempotency is implemented

  1. The module uses the SDK to send a GET request to read the resource (if it does not exist, the SDK raises ResourceNotFoundError, i.e., HTTP 404).
  2. If it does not exist and state: present → build the request body, send a PUT (begin_create_or_update), and poll the long-running operation (LRO: Azure-AsyncOperation header) until Succeeded → changed: true.
  3. If it exists → compare the desired parameters with the returned properties item by item (tags default to merge,append_tags: false replaced when set) → PUT/PATCH only if there is a difference → otherwise changed: false.
  4. --check In check mode, only steps 1 and 3 are compared, reporting “would change” without sending write requests (most azure_rm modules support check mode; refer to the “check_mode: full/partial” attribute in the module docs).
  5. state: absent → if it exists, send a DELETE and wait for completion; if it does not exist, return ok.

Immutable properties

Some properties cannot be changed after creation (for example, the VM's admin_username,image, availability zone; a VNet subnet prefix cannot be shrunk while NICs exist). Changing these parameters makes the module either fail or ignore the change; unlike Terraform, Ansible does not automatically “destroy and recreate.” This is an important basis for the M6 discussion of responsibilities.

When: when to create resources with Ansible

  • Good fit: lab environments, temporary test machines, small deployments tightly coupled with configuration, an integrated “create then configure immediately” workflow, or teams already using Ansible without Terraform.
  • Poor fit: large, long-lived, multi-person infrastructure (lacking state, plan and drift detection, and parallel dependency graphs); see M6.

Comparison with similar technologies

Ansible azure_rm_*Terraform azurermBicep / ARM
Execution orderIn the order tasks are written (serial)Dependency graph, automatic parallelismARM dependency graph (dependsOn/implicit)
Preview--check --diff (module support varies)terraform planwhat-if
DeletionRequires writing a separate state: absent (reverse order)terraform destroyDeleting the resource group or --mode Complete/deployment stacks
DriftCorrects managed properties on every runplan detectswhat-if detects
Common misconceptions (1) “Deleting a task deletes the resource”—no. Ansible is stateless, so you must write state: absent. (2) “Deleting azure_rm_virtualmachine only deletes the VM”—remove_on_absent by default ['all'], it also deletes the OS/data managed disks associated with the VM, the NIC, and the public IP on the NIC (including ones you explicitly created and attached, such as a static public IP you want to keep). (3) “Use the Basic SKU public IP because it is cheaper”—the Basic SKU was retired on 2025-09-30; for new deployments use sku: standard.

Architecture diagram: resources created in this lesson

rg-ansible-lab · canadacentral · tags: env=lab app=myapp owner=… vnet-ansible 10.30.0.0/16 snet-app 10.30.1.0/24 nsg-app100 Allow 22 ← MY_IP/32110 Allow 8000 ← MY_IP/3265000+ default rules(associated with the subnet) nic-myapp-0110.30.1.4 (dynamic)ipconfig1 → PIP vm-myapp-01Standard_B2sUbuntu 24.04 LTSazureuser + SSH keyOS disk 30 GiB StdSSD pip-myapp-01Standard · Static · 20.151.x.x Your control nodeMY_IP → 22 / 8000
Figure 3-1: the NSG is associated with the subnet and only allows the control node's public IP; the VM reaches the outside through its explicitly created NIC and a Standard static public IP

Flowchart: creation order and deletion order

RG VNet NSG Subnet(+NSG) Public IP NIC VM + OS disk present: in dependency order (provision.yml) absent: reverse order VM → NIC → PIP → Subnet → NSG → VNet → RG (or delete the RG directly) Wrong ordering returns 400 errors such as InUseSubnetCannotBeDeleted / NicInUse / PublicIPAddressInUse
Figure 3-2: Ansible does not infer dependencies automatically; task order is execution order

Animation: first run, second run, and deletion

Choose a scenario to play. Each block represents one task; colors:yellow=changed,green=ok,red=deleted. The terminal shows the actual types of requests the module sends to ARM behind the scenes.

Core modules and parameters

ModuleKey parametersNotes
azure_rm_resourcegroupname location tags state force_delete_nonemptyDeleting a non-empty RG requires force_delete_nonempty: true
azure_rm_virtualnetworkaddress_prefixes_cidr purge_address_prefixesManage subnets with a separate azure_rm_subnet, which is recommended
azure_rm_securitygrouprules[] (name/protocol/destination_port_range/source_address_prefix/access/priority/direction) purge_rulespriority 100–4096 and unique; purge_rules: true Delete rules not defined in code
azure_rm_subnetvirtual_network_name address_prefix_cidr security_group default_outbound_accessAssociate NSG with subnet
azure_rm_publicipaddressallocation_method: static sku: standard zonesReturns state.ip_address
azure_rm_networkinterfacevirtual_network subnet_name ip_configurations[] create_with_security_groupWhen the subnet already has an NSG, set create_with_security_group: false
azure_rm_virtualmachinevm_size image admin_username ssh_password_enabled ssh_public_keys network_interface_names managed_disk_type os_disk_size_gb vm_identity tags started/allocated remove_on_absentUbuntu 24.04: publisher Canonical, offer ubuntu-24_04-lts, sku server

Variables file

az_auth: cli
rg: rg-ansible-lab
location: canadacentral
owner: "{{ lookup('ansible.builtin.env', 'USER') }}"
common_tags:
  env: lab
  app: myapp
  owner: "{{ owner }}"
vnet: { name: vnet-ansible, cidr: 10.30.0.0/16 }
subnet: { name: snet-app, cidr: 10.30.1.0/24 }
nsg_name: nsg-app
# Your public IP: at runtime, -e my_ip=$(curl -s https://api.ipify.org)
my_ip: "{{ undef(hint='Pass your public IP with -e my_ip=x.x.x.x') }}"
vms:
  - { name: vm-myapp-01, size: Standard_B2s, role: web }
admin_user: azureuser
ssh_pubkey: "{{ lookup('ansible.builtin.file', '~/.ssh/id_ed25519.pub') }}"

undef(hint=…) is a Jinja2 global function available since ansible-core 2.12; it gives a clear message when the variable is not passed. owner The tag makes it easy to clean up by person in M8.

provision.yml

- name: Provision Azure infrastructure for myapp
  hosts: localhost
  connection: local
  gather_facts: false
  vars_files: [vars/lab.yml]
  module_defaults:
    group/azure.azcollection.all:      # set common parameters for all modules in the collection
      auth_source: "{{ az_auth }}"
  tasks:
    - name: Resource group
      azure.azcollection.azure_rm_resourcegroup:
        name: "{{ rg }}"
        location: "{{ location }}"
        tags: "{{ common_tags }}"

    - name: Virtual network
      azure.azcollection.azure_rm_virtualnetwork:
        resource_group: "{{ rg }}"
        name: "{{ vnet.name }}"
        address_prefixes_cidr: ["{{ vnet.cidr }}"]
        tags: "{{ common_tags }}"

    - name: Network security group (only my IP)
      azure.azcollection.azure_rm_securitygroup:
        resource_group: "{{ rg }}"
        name: "{{ nsg_name }}"
        purge_rules: true
        rules:
          - name: allow-ssh-from-me
            protocol: Tcp
            destination_port_range: 22
            source_address_prefix: "{{ my_ip }}/32"
            access: Allow
            priority: 100
            direction: Inbound
          - name: allow-myapp-from-me
            protocol: Tcp
            destination_port_range: 8000
            source_address_prefix: "{{ my_ip }}/32"
            access: Allow
            priority: 110
            direction: Inbound
        tags: "{{ common_tags }}"

    - name: Subnet with NSG
      azure.azcollection.azure_rm_subnet:
        resource_group: "{{ rg }}"
        virtual_network_name: "{{ vnet.name }}"
        name: "{{ subnet.name }}"
        address_prefix_cidr: "{{ subnet.cidr }}"
        security_group: "{{ nsg_name }}"

    - name: Public IPs
      azure.azcollection.azure_rm_publicipaddress:
        resource_group: "{{ rg }}"
        name: "pip-{{ item.name | regex_replace('^vm-', '') }}"
        allocation_method: static
        sku: standard
        tags: "{{ common_tags }}"
      loop: "{{ vms }}"
      register: pips

    - name: NICs
      azure.azcollection.azure_rm_networkinterface:
        resource_group: "{{ rg }}"
        name: "nic-{{ item.name | regex_replace('^vm-', '') }}"
        virtual_network: "{{ vnet.name }}"
        subnet_name: "{{ subnet.name }}"
        create_with_security_group: false     # NSG is already associated with the subnet
        ip_configurations:
          - name: ipconfig1
            public_ip_address_name: "pip-{{ item.name | regex_replace('^vm-', '') }}"
            primary: true
        tags: "{{ common_tags }}"
      loop: "{{ vms }}"

    - name: Virtual machines
      azure.azcollection.azure_rm_virtualmachine:
        resource_group: "{{ rg }}"
        name: "{{ item.name }}"
        vm_size: "{{ item.size }}"
        admin_username: "{{ admin_user }}"
        ssh_password_enabled: false
        ssh_public_keys:
          - path: "/home/{{ admin_user }}/.ssh/authorized_keys"
            key_data: "{{ ssh_pubkey }}"
        network_interface_names: ["nic-{{ item.name | regex_replace('^vm-', '') }}"]
        image:
          publisher: Canonical
          offer: ubuntu-24_04-lts
          sku: server
          version: latest
        managed_disk_type: StandardSSD_LRS
        os_disk_size_gb: 30
        vm_identity:
          type: SystemAssigned        # M5 uses this to read Key Vault
        tags: "{{ common_tags | combine({'role': item.role}) }}"
      loop: "{{ vms }}"
      register: vm_out

    - name: Show public IPs
      ansible.builtin.debug:
        msg: "{{ item.item.name }} → {{ item.state.ip_address }}"
      loop: "{{ pips.results }}"
      loop_control: { label: "{{ item.item.name }}" }

action group for module_defaults: azure.azcollection, in meta/runtime.yml defines action_groups: all, so you can use group/azure.azcollection.all to set auth_source (as well as subscription_id etc.).

cd ~/ansible-lab/azure
ansible-playbook playbooks/provision.yml -e my_ip=$(curl -s https://api.ipify.org) --check --diff   # Preview
ansible-playbook playbooks/provision.yml -e my_ip=$(curl -s https://api.ipify.org)
TASK [Resource group] ***********************************************************
changed: [localhost]
TASK [Virtual network] **********************************************************
changed: [localhost]
TASK [Network security group (only my IP)] **************************************
changed: [localhost]
TASK [Subnet with NSG] **********************************************************
changed: [localhost]
TASK [Public IPs] ***************************************************************
changed: [localhost] => (item={'name': 'vm-myapp-01', 'size': 'Standard_B2s', 'role': 'web'})
TASK [NICs] *********************************************************************
changed: [localhost] => (item=...)
TASK [Virtual machines] *********************************************************
changed: [localhost] => (item=...)
TASK [Show public IPs] **********************************************************
ok: [localhost] => (item=vm-myapp-01) =>
    msg: vm-myapp-01 → 20.151.12.34

PLAY RECAP **********************************************************************
localhost : ok=8  changed=7  unreachable=0  failed=0  skipped=0  rescued=0  ignored=0

How to verify: Run it again immediately; it should be changed=0; az resource list -g rg-ansible-lab -o table should list 7 resource types (including the OS disk). Common errors: the resource group already exists with a different location (the RG's location cannot be changed); insufficient quota (OperationNotAllowed … quota); the SKU is not available in that region (SkuNotAvailable). Production use: Run in the CI “preview” stage --check --diff, and execute after approval.

Querying and asserting (*_info)

ansible localhost -m azure.azcollection.azure_rm_virtualmachine_info \
  -a "resource_group=rg-ansible-lab name=vm-myapp-01 auth_source=cli" | grep -E '"(power_state|provisioning_state|vm_size)"'
                "power_state": "running",
                "provisioning_state": "Succeeded",
                "vm_size": "Standard_B2s",

Stop, deallocate and delete

- name: Deallocate (stop compute billing)
  azure.azcollection.azure_rm_virtualmachine:
    resource_group: rg-ansible-lab
    name: vm-myapp-01
    allocated: false          # deallocate; started: false only shuts down, and compute is still billed

- name: Delete the VM but keep its public IP
  azure.azcollection.azure_rm_virtualmachine:
    resource_group: rg-ansible-lab
    name: vm-myapp-01
    state: absent
    remove_on_absent: [network_interfaces, virtual_storage]   # does not include public_ips → static public IP is kept

remove_on_absent Allowed values (4.2.0 source): all (default: disks + NICs + public IPs on the NICs),all_autocreated (only delete resources automatically generated when the module created the VM),network_interfaces,virtual_storage,public_ips (must be used together with network_interfaces). The NSG on the subnet and the VNet are not deleted. Before deleting, use --check to preview; the result lists deleted_network_interfaces,deleted_managed_disk_ids and similar fields list the resources to be deleted.

Lab 3: create, verify idempotency, introduce drift, correct it (about 8 min; billing starts)

Cost / permissions / risks Cost: Standard_B2s + StandardSSD 30 GiB + Standard static public IP, about USD 0.06 per hour (example value; refer to the pricing calculator). Permissions: rg-ansible-lab Contributor on the target scope. Risk: the public IP exposes ports 22 and 8000, but the NSG only allows your IP.
Write variables and playbook: copy the vars/lab.yml and provision.yml save to ~/ansible-lab/azure/playbooks/.
Preview, then run:
cd ~/ansible-lab/azure
export MY_IP=$(curl -s https://api.ipify.org)
ansible-playbook playbooks/provision.yml -e my_ip=$MY_IP --check
ansible-playbook playbooks/provision.yml -e my_ip=$MY_IP

In check mode, tasks such as the VM and NIC that depend on earlier resources may fail with “prerequisite resource does not exist yet” or show changed. This is an inherent limitation of check mode when there is a dependency chain, and it is acceptable on the first creation.

Verify idempotency:
ansible-playbook playbooks/provision.yml -e my_ip=$MY_IP | tail -3
PLAY RECAP **********************************************************************
localhost : ok=8  changed=0  unreachable=0  failed=0  skipped=0  rescued=0  ignored=0
Introduce drift: simulate someone changing the SSH source to Any in the portal and manually adding a rule:
az network nsg rule update -g rg-ansible-lab --nsg-name nsg-app -n allow-ssh-from-me --source-address-prefixes '*'
az network nsg rule create -g rg-ansible-lab --nsg-name nsg-app -n temp-rdp --priority 300 \
  --destination-port-ranges 3389 --access Allow --protocol Tcp
ansible-playbook playbooks/provision.yml -e my_ip=$MY_IP --check     # first see what it will correct
ansible-playbook playbooks/provision.yml -e my_ip=$MY_IP
TASK [Network security group (only my IP)] **************************************
changed: [localhost]
...
localhost : ok=8  changed=1  ...

purge_rules: true Let Ansible delete temp-rdp and change the SSH source back to $MY_IP/32. This is “correct on every run.”

View resources and tags:
az resource list -g rg-ansible-lab --query "[].{type:type,name:name}" -o table
ansible-inventory -i inventory/lab.azure_rm.yml --graph --flush-cache
Type                                       Name
-----------------------------------------  ----------------------------------------
Microsoft.Network/networkSecurityGroups    nsg-app
Microsoft.Network/virtualNetworks          vnet-ansible
Microsoft.Network/publicIPAddresses        pip-myapp-01
Microsoft.Network/networkInterfaces        nic-myapp-01
Microsoft.Compute/virtualMachines          vm-myapp-01
Microsoft.Compute/disks                    vm-myapp-01_OsDisk_1_3f2a…
@all:
  |--@ungrouped:
  |--@webservers:
  |  |--vm-myapp-01
  ...
Cleanup: keep the resources for M4. If you stop for today: az vm deallocate -g rg-ansible-lab -n vm-myapp-01 (stops compute billing, but the public IP and disks are still billed), or run the M8 teardown.yml.

Case 1: a temporary test environment for each feature branch

Problem: QA needs to create test VMs per branch and delete them when done. Approach: Include the branch name in the resource group name rg-myapp-pr-123, and tag all resources with ttl=24h,pr=123 tags; provision → configure → test → azure_rm_resourcegroup state: absent force_delete_nonempty: true in one go; a nightly cleanup job also deletes any RG past its TTL as a fallback. Limitations: Deleting the whole group is the most reliable cleanup method, provided shared resources are not placed in the same RG.

Case 2: a static public IP on the allowlist was lost when the VM was rebuilt

Problem: The partner's firewall only allows the VM's static public IP. To upgrade the OS, the team used azure_rm_virtualmachine state: absent to delete the old VM; by default remove_on_absent: all deleted the NIC and public IP together, the new IP changed, and the integration broke. Approach: Manage resources to be kept separately; when deleting the VM, explicitly set remove_on_absent: [network_interfaces, virtual_storage]; for the critical public IP, add CanNotDelete resource lock (azure_rm_lock). Limitations: Any deletion in CI should first run --check and receive manual approval.

Case 3: creation fails due to insufficient regional capacity

Problem: a popular region has tight capacity for a certain size,AllocationFailed/SkuNotAvailable. Approach: Provide a list of fallback sizes in variables, and have the task use block/rescue them in turn; before creating, use az vm list-skus -l canadacentral --size Standard_B --query "[?restrictions==\`[]\`].name" to check. Limitations: Retries lengthen the run time; production capacity problems should be solved with reservations or capacity reservation groups.

Common errors and fixes

(InUseSubnetCannotBeDeleted) Subnet snet-app is in use by /subscriptions/…/networkInterfaces/nic-myapp-01/ipConfigurations/ipconfig1 and cannot be deleted.

Cause: Wrong deletion order; there are still NICs on the subnet.

Fix: Delete in reverse order (VM → NIC → PIP → subnet), or delete the resource group directly.

(SkuNotAvailable) The requested VM size for resource 'Following SKUs have failed for Capacity Restrictions: Standard_B2s' is currently not available in location 'canadacentral'.
az vm list-skus -l canadacentral --resource-type virtualMachines --size Standard_B2 -o table

Fix: Change the size (for example Standard_B2ls_v2,Standard_D2s_v5) or region; check the Restrictions column.

(OperationNotAllowed) Operation could not be completed as it results in exceeding approved standardBSFamily Cores quota.
az vm list-usage -l canadacentral -o table | grep -i "BS Family"

Fix: Delete unused VMs, or request a quota increase in the portal under “Quotas.”

Error creating or updating resource group rg-ansible-lab - Invalid resource group location 'eastus'. The Resource group already exists in location 'canadacentral'.

Cause: A resource group's location cannot be changed after creation.

Fix: Keep the variable consistent with the existing RG; to change regions, create a new RG.

Parameter error: ssh_public_keys is required when ssh_password_enabled is false / The value of parameter linuxConfiguration.ssh.publicKeys.keyData is invalid.

Cause: Wrong public key file path, empty content, or wrong format (for example, a private key was copied).

ssh-keygen -l -f ~/.ssh/id_ed25519.pub

Fix:key_data It must be a single line ssh-ed25519 AAAA… comment; path it must be /home/<admin_username>/.ssh/authorized_keys.

Command-line exercises
1. Without running any write operation, preview what provision.yml would change and show the differences.
ansible-playbook playbooks/provision.yml -e my_ip=$MY_IP --check --diff
2. Write a task that deallocates vm-myapp-01 to stop compute billing.
- azure.azcollection.azure_rm_virtualmachine:
    resource_group: rg-ansible-lab
    name: vm-myapp-01
    allocated: false
Scenario analysis
A colleague changed the VM's image.sku from server to another version, and after running changed=0, the VM is still running the old OS. Why? What should be done?

The image is an immutable property set when the VM is created; azure_rm_virtualmachine does not rebuild the VM because the image changed (unlike Terraform's “forces replacement”). To change the OS, you need to rebuild explicitly: first state: absent delete it (mind remove_on_absent), then create again; or use a blue-green approach: create a new vm-myapp-02 (new image) → configure → switch traffic → delete the old VM. Needs like this “immutable infrastructure” are one of the reasons M6 recommends handing them to Terraform/Bicep.

Verified instructional videos

▶
Ansible to automate Microsoft Azure — Red Hat
English · demonstrates the overall approach of creating Azure resources with Ansible modules (module parameters follow the 4.x docs)

No verified dedicated video was found on creating VNet/NSG/NIC/VM layer by layer with azure.azcollection 4.x.

Official docs

Video storyboard script (about 90 seconds)

This courseware cannot directly generate a video/MP3. The storyboard and narration script are provided and can be handed to a video tool.

Scene 1 · 0–20s
Visual: seven blocks appear from left to right in turn: resource group, virtual network, security group, subnet, public IP, NIC, virtual machine.
Narration: Ansible does not infer dependencies; the order of tasks is the creation order.
Scene 2 · 20–45s
Visual: beside each block, GET 404 appears first, then PUT and a spinning polling icon, and finally it turns yellow to show changed.
Narration: the module reads first; if the resource does not exist, it creates it and waits for the asynchronous operation to complete.
Scene 3 · 45–70s
Visual: on the second run, all blocks show only GET 200 and turn green to show ok. Someone modifies the NSG in the portal, and on the next run only the NSG turns yellow.
Narration: running again only corrects what differs; this is idempotency and drift correction.
Scene 4 · 70–90s
Visual: red arrows delete the blocks one by one from right to left.
Narration: deletion requires state absent and reverse order; the easiest approach is to delete the entire resource group.
or score ≥ 70% on the quiz

Module 4 · Configure Azure VMs and deploy applications

22:00 – 30:00 · Roles don't care where the machine is: point the myapp role from lessons 1–2 at tag_role_web unchanged; the only thing to solve is “how to connect safely”
8 minRole reuse · wait_for_connectionBastion requires Standard SKU + tunneling★★★★★
Learning objectives
  • Write site-azure.yml: a playbook that waits for SSH to be available and cloud-init to finish → applies myapp the role → verifies from the control node /healthz.
  • Handle host keys on first connection (StrictHostKeyChecking=accept-new), and understand why it should not be disabled globally host_key_checking.
  • Two secure access methods: the NSG only allows the control node's public IP; or do not expose public SSH at all and use az network bastion tunnel to set up local port forwarding.
  • In the same run, “create first, then configure”: meta: refresh_inventory or add_host.
Prerequisites: Lesson 2's role structure, handlers, and variable precedence; M2 dynamic inventory; the M3 VM. Importance:★★★★★

What: from “created” to “usable”

At the end of M3, the VM is in Running, but that does not mean it is ready to deploy: sshd may not be ready yet, and cloud-init may still be running apt (it will contend with Ansible's apt tasks for the dpkg lock), and the host keys are not yet trusted. This module's playbook first handles these “boot-time” issues, then hands off to the role.

Why: why the role can be reused unchanged

The myapp role from lesson 2 only depends on: an Ubuntu 24.04 machine, an SSH user with sudo, and a few variables (myapp_port,myapp_redis_password). All differences between cloud and local containers are in the inventory layer: where hosts come from (dynamic inventory), how to connect (ansible_host/ansible_user/ansible_port), and where secrets come from (M5). This is the value of “decoupling roles from environments.”

How: how each task executes on an Azure VM

  1. The control node packages the module and parameters into an AnsiballZ script.
  2. Connect via OpenSSH ansible_host:ansible_port (public IP:22, or 127.0.0.1:2222 through the Bastion tunnel), reusing ControlPersist connections; enable pipelining when on, the script is sent via stdin; otherwise it is first copied via sftp to ~/.ansible/tmp.
  3. become: true With sudo set, the task escalates privileges with sudo (Azure Linux VM admin users have passwordless sudo by default).
  4. On the managed node, the /usr/bin/python3 (Ubuntu 24.04 ships Python 3.12, within the 3.9–3.14 range supported by core 2.21) runs the module, prints JSON, and Ansible uses that to decide changed/ok/failed.

Comparison of the two access methods

Public IP + NSG source IP restrictionAzure Bastion tunnel
Does the VM need a public IPYesNo
NSG rulesPort 22 allows only MY_IP/32The default AllowVnetInBound is sufficient (Bastion sits in the same VNet's AzureBastionSubnet)
AuthenticationSSH keyEntra ID (Azure RBAC: Reader on VM, NIC, and Bastion) + SSH key
Ansible configurationansible_host = public IPfirst az network bastion tunnel … --port 2222,ansible_host=127.0.0.1 ansible_port=2222
Multiple hostsrun in parallel directlyone tunnel/local port per VM (or an SSH ProxyCommand script)
CostPublic IP hourly chargeBastion Standard SKU (native client/tunneling requires Standard or higher) is billed hourly and is clearly more expensive
Best forlabs, personal useproduction, or compliance requirements for “no public management ports”

Other option: the control node (or a self-hosted Runner/AWX) is itself deployed in the same VNet or a peered VNet and connects directly over private IPs (ansible_host: private_ipv4_addresses | first)—the most common approach in production; VPN/ExpressRoute can also be used.

When: what goes in cloud-init and what goes to Ansible

  • cloud-init (custom_data): minimal first-boot bootstrap—users, SSH, Python.
  • Ansible: any configuration that needs to be repeatable, auditable, and change with versions—applications, config files, services, upgrades.

Comparison with similar technologies

Ansible over SSHVM Run Command (az vm run-command)Custom Script Extension
Requires network reachabilityYes (SSH)No, via Azure proxyNo, via Azure proxy
Idempotent / structuredYes, modularScript must ensure it itselfScript must ensure it itself
Best forday-to-day configuration managementemergencies, troubleshooting when there is no networkfirst-boot bootstrap
Common misconceptions (1) “A running VM can run a playbook right away”—cloud-init may still hold the apt lock, causing Could not get lock /var/lib/dpkg/lock-frontend. (2) “To save effort, set host_key_checking = False”—this makes man-in-the-middle attacks undetectable; use accept-new only trusts a host key on first sight, and still raises an alert if the key changes later. (3) “Bastion Basic/Developer SKU can also use az network bastion tunnel”—native client connections require Standard or higher SKU with tunneling enabled (native client support).

Architecture diagram: two connection paths

Control nodeansible-playbookOpenSSH + ControlPersistMY_IP 203.0.113.10 vnet-ansible 10.30.0.0/16 pip-myapp-0120.151.12.34:22 nsg-app22 ← 203.0.113.10/32 vm-myapp-0110.30.1.4sshd · python3.12 (1) Public SSH Azure Bastion (Standard)AzureBastionSubnet /26enable-tunneling ② az network bastion tunnel127.0.0.1:2222 → HTTPS/WebSocket Private 10.30.1.4:22
Figure 4-1 Path (1): the VM has a public IP and the NSG only allows the control node; Path (2): the VM has no public IP and reaches private port 22 through the Bastion WebSocket tunnel

Flowchart: execution stages of site-azure.yml

Dynamic inventorytag_role_web wait_for_connectionsshd ready cloud-init status--wait gather_factssetup role: myappapt/pip/systemd uri /healthzdelegate_to localhost gather_facts: false at the play level; wait for the connection to be available, then run setup manually to avoid UNREACHABLE at the first step
Figure 4-2 boot-time checks → fact gathering → roles → external verification

Animation: how an apt task reaches an Azure VM

After choosing a connection method, play it and watch the same ansible.builtin.apt task passes through each hop, and the corresponding -vvv logs.

Core commands and parameters

Command / keywordPurposeNotes
ansible.builtin.wait_for_connectionWait for SSH + Python to be availabletimeout: 300,delay,sleep
cloud-init status --waitWait for the first-boot script to completeReturns status: done
ansible_ssh_common_argsExtra SSH parameters-o StrictHostKeyChecking=accept-new
ansible.builtin.meta: refresh_inventoryRe-run the inventory plugin in the playbookConfigure immediately after creating the VM
az network bastion tunnellocal port → Bastion → VM port--target-resource-id --resource-port 22 --port 2222
ansible-playbook --limitRun only on some hosts--limit vm-myapp-01

Connection variables (per dynamic group)

ansible_user: azureuser
ansible_ssh_private_key_file: ~/.ssh/id_ed25519
ansible_ssh_common_args: "-o StrictHostKeyChecking=accept-new"
ansible_python_interpreter: /usr/bin/python3

Place it in inventory/group_vars/ , in the same directory as the inventory file; it is loaded regardless of which directory the playbook is in.

site-azure.yml

- name: Configure myapp on Azure VMs
  hosts: tag_role_web
  gather_facts: false
  become: true
  vars:
    myapp_port: 8000
  pre_tasks:
    - name: Wait until SSH and Python are reachable
      ansible.builtin.wait_for_connection:
        timeout: 300
        delay: 5

    - name: Wait for cloud-init to finish (releases apt/dpkg locks)
      ansible.builtin.command: cloud-init status --wait
      register: ci
      changed_when: false
      failed_when: ci.rc not in [0, 2]     # 2 = done with recoverable errors

    - name: Gather facts now
      ansible.builtin.setup:

  roles:
    - role: myapp

  post_tasks:
    - name: Verify /healthz from the control node
      ansible.builtin.uri:
        url: "http://{{ ansible_host }}:{{ myapp_port }}/healthz"
        return_content: true
      delegate_to: localhost
      become: false
      register: hz
      retries: 10
      delay: 3
      until: hz.status == 200

    - name: Report
      ansible.builtin.debug:
        msg: "{{ inventory_hostname }} ({{ ansible_host }}) healthz={{ hz.content | trim }}"
cd ~/ansible-lab/azure
ansible-inventory -i inventory/ --graph tag_role_web
ansible tag_role_web -i inventory/ -m ansible.builtin.ping
ansible-playbook -i inventory/ playbooks/site-azure.yml
vm-myapp-01 | SUCCESS => {
    "changed": false,
    "ping": "pong"
}
...
TASK [myapp : Install OS packages] **********************************************
changed: [vm-myapp-01]
...
RUNNING HANDLER [myapp : restart myapp] *****************************************
changed: [vm-myapp-01]
TASK [Report] *******************************************************************
ok: [vm-myapp-01] =>
    msg: vm-myapp-01 (20.151.12.34) healthz=ok

PLAY RECAP **********************************************************************
vm-myapp-01 : ok=14  changed=9  unreachable=0  failed=0  skipped=0  rescued=0  ignored=0

How to verify: Browser or curl http://<public IP>:8000/ shows the counter incrementing; on the second run changed=0. Common errors: UNREACHABLE (NSG source IP, ansible_user, keys); see “Troubleshooting.”Production use: Do not expose port 8000 publicly; instead put an Application Gateway / Load Balancer in front (lesson 6).

“Create + configure” in the same run

- ansible.builtin.import_playbook: provision.yml

- name: Refresh dynamic inventory after provisioning
  hosts: localhost
  gather_facts: false
  tasks:
    - ansible.builtin.meta: refresh_inventory

- ansible.builtin.import_playbook: site-azure.yml

When inventory caching is enabled,refresh_inventory refreshes the plugin data; if you still see old data, add --flush-cache.

Azure Bastion: do not expose public SSH

# 1) Subnet (the name must be AzureBastionSubnet, at least /26), public IP, Bastion (Standard + tunneling)
az network vnet subnet create -g rg-ansible-lab --vnet-name vnet-ansible -n AzureBastionSubnet --address-prefixes 10.30.255.0/26
az network public-ip create -g rg-ansible-lab -n pip-bastion --sku Standard -l canadacentral
az network bastion create -g rg-ansible-lab -n bas-lab --vnet-name vnet-ansible \
  --public-ip-address pip-bastion --sku Standard --enable-tunneling true -l canadacentral   # about 5–10 min

# 2) Open the tunnel (keep this terminal running)
VMID=$(az vm show -g rg-ansible-lab -n vm-myapp-01 --query id -o tsv)
az network bastion tunnel -g rg-ansible-lab -n bas-lab --target-resource-id "$VMID" --resource-port 22 --port 2222
# 3) In another terminal: have Ansible go through the tunnel
ansible-playbook -i inventory/ playbooks/site-azure.yml --limit vm-myapp-01 \
  -e ansible_host=127.0.0.1 -e ansible_port=2222 \
  -e '{"ansible_ssh_common_args": "-o StrictHostKeyChecking=accept-new -o HostKeyAlias=vm-myapp-01"}'

HostKeyAlias Have known_hosts record keys by VM name, to avoid multiple tunnels all named [127.0.0.1]:2222 causing key conflicts. At this point the post_tasks /healthz check will hit 127.0.0.1:8000, so you need to open another --resource-port 8000 --port 8000 tunnel for it, or change it to check locally on the VM (url: http://127.0.0.1:8000/healthz, remove delegate_to). After confirming it works, you can delete the VM's public IP and the port 22 rule in the NSG.

Lab 4: deploy myapp to an Azure VM (about 7 min)

Write the connection variables and playbook: save the inventory/group_vars/tag_env_lab.yml and playbooks/site-azure.yml from the “Commands” tab.
Confirm inventory and connectivity:
cd ~/ansible-lab/azure
ansible-inventory -i inventory/ --graph tag_role_web --flush-cache
ansible tag_role_web -i inventory/ -m ansible.builtin.ping
Deploy: ansible-playbook -i inventory/ playbooks/site-azure.yml, then:
IP=$(ansible-inventory -i inventory/ --host vm-myapp-01 | python3 -c 'import json,sys;print(json.load(sys.stdin)["ansible_host"])')
for i in 1 2 3; do curl -s http://$IP:8000/; done
Hello from vm-myapp-01! visits=1
Hello from vm-myapp-01! visits=2
Hello from vm-myapp-01! visits=3
Verify idempotency: run the playbook again, and expect changed=0 (only the cloud-init check command is marked changed_when: false changed, but no real change is made).
Verify the NSG restriction: from another network (a phone hotspot or Azure Cloud Shell), run curl -m 5 http://$IP:8000/, which should time out—only your IP can connect.
(optional, extra cost) Bastion path: following the “Commands” tab, create Bastion, open the tunnel, and use -e ansible_host=127.0.0.1 -e ansible_port=2222 to run it again. Delete immediately after finishing:
az network bastion delete -g rg-ansible-lab -n bas-lab
az network public-ip delete -g rg-ansible-lab -n pip-bastion
Cleanup: keep the VM for M5. When pausing study, run az vm deallocate -g rg-ansible-lab -n vm-myapp-01.

Case 1: self-hosted Runner inside the VNet, all traffic over private networking

Problem: The security baseline prohibits VMs from having public IPs. Approach: Deploy a small VM in the hub VNet as the Ansible control node (or a GitHub self-hosted Runner / AWX), peered with the application VNet; the dynamic inventory hostvar_expressions: {ansible_host: private_ipv4_addresses | first}; the control node authenticates with a managed identity (M1). Limitations: The control node itself becomes a high-value target and needs hardening, JIT access, and auditing.

Case 2: occasional dpkg lock errors on first deployment

Problem: On new VMs, Ansible's apt tasks fail about 30% of the time: Could not get lock /var/lib/dpkg/lock-frontend. Approach: In pre_tasks, cloud-init status --wait; additionally set lock_timeout: 120 (provided by ansible-core 2.12+). Limitations: unattended-upgrades can also hold the lock; in the role, use apt-daily timer configuration or lock_timeout as a fallback.

Case 3: rolling deployment to 10 web VMs

Problem: Restarting gunicorn on all of them at once causes a brief outage. Approach:serial: 2 + max_fail_percentage: 0; in the load balancer backend pool, remove first and then add back (azure_rm_loadbalancer or the Application Gateway health probe removes it automatically). Limitations: Detailed orchestration is covered in lesson 6.

Common errors and fixes

vm-myapp-01 | UNREACHABLE! => "Failed to connect to the host via ssh: ssh: connect to host 20.151.12.34 port 22: Connection timed out"

Cause: The NSG does not allow your current egress IP (you changed networks, the company has multiple egress points, or a proxy is in use), or the VM is not running.

curl -s https://api.ipify.org; echo
az network nsg rule show -g rg-ansible-lab --nsg-name nsg-app -n allow-ssh-from-me --query sourceAddressPrefix -o tsv
az network watcher test-ip-flow -g rg-ansible-lab --vm vm-myapp-01 --direction Inbound --protocol TCP \
  --local 10.30.1.4:22 --remote $(curl -s https://api.ipify.org):50000

Fix: Re-run with the new IP provision.yml -e my_ip=… (purge_rules updates the rules). test-ip-flow will tell you which NSG rule denied the traffic.

"Failed to connect to the host via ssh: azureuser@20.151.12.34: Permission denied (publickey)."

Cause:ansible_user Not the admin_username used at creation, or the wrong private key was used.

ssh -i ~/.ssh/id_ed25519 -v azureuser@$IP true 2>&1 | grep -E "Offering|Authenticated|denied"

Fix: Correct group_vars; in an emergency, az vm user update -g rg-ansible-lab -n vm-myapp-01 -u azureuser --ssh-key-value ~/.ssh/id_ed25519.pub reset the public key (via the VM agent; no SSH needed).

Host key verification failed. / WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED!

Cause: The VM was deleted and recreated and reused the same static public IP, so its host key changed.

Fix: After confirming you rebuilt the VM yourself, run ssh-keygen -R 20.151.12.34; do not disable host_key_checking globally for this.

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

Cause: cloud-init or unattended-upgrades is running.

Fix: In pre_tasks, cloud-init status --wait; add lock_timeout: 120.

az network bastion tunnel fails immediately, with a message that the SKU or native client / tunneling is not enabled (symptom)

Cause: Basic/Developer SKU, or tunneling (native client support) is not enabled.

az network bastion show -g rg-ansible-lab -n bas-lab --query "{sku:sku.name, tunneling:enableTunneling}"

Fix:az network bastion update -g rg-ansible-lab -n bas-lab --sku Standard --enable-tunneling true. The exact error text varies with the CLI/bastion extension version; follow the terminal output.

Command-line exercises
1. Run site-azure.yml only against vm-myapp-01 in the tag_role_web group, and show the differences for each task.
ansible-playbook -i inventory/ playbooks/site-azure.yml --limit vm-myapp-01 --diff
2. When the VM has no public IP, open a Bastion tunnel to vm-myapp-01 (local port 2222).
az network bastion tunnel -g rg-ansible-lab -n bas-lab \
  --target-resource-id "$(az vm show -g rg-ansible-lab -n vm-myapp-01 --query id -o tsv)" \
  --resource-port 22 --port 2222
Scenario analysis
A playbook first creates 3 VMs, then the hosts: tag_role_web play reports “Could not match supplied host pattern.” The VMs were actually created successfully. What is the cause and how do you fix it?

The inventory is parsed only once, at the start of the playbook, when the VMs did not yet exist, so the dynamic group was empty. Fix: add, between the two plays, meta: refresh_inventory (if inventory caching is enabled, you also need to --flush-cache or use a shorter cache_timeout); or, after the create task, use add_host to add the new VMs to the in-memory inventory (name,groups,ansible_host taken from the registered result). In addition, the new VMs need wait_for_connection to be reconfigured.

Verified instructional videos

▶
What is Ansible | Ansible Playbook explained | Ansible Tutorial for Beginners — TechWorld with Nana
English · reviews playbooks, roles, and the SSH execution model; consistent with this module's “reuse roles unchanged” approach
▶
Automate EVERYTHING with Ansible! (Ansible for Beginners) — Techno Tim
English · hands-on, demonstrates SSH keys and running a playbook

No verified dedicated video on “Ansible + Azure Bastion tunnel” was found.

Official docs

Video storyboard script (about 80 seconds)

This courseware cannot directly generate a video/MP3. The storyboard and narration script are provided and can be handed to a video tool.

Scene 1 · 0–20s
Visual: the myapp role box is “moved” from a local container to a cloud VM; the contents of the box stay the same, and only the inventory label outside changes.
Narration: roles don't care where the machine is; only the inventory and the connection method change.
Scene 2 · 20–45s
Visual: the VM has just started, a cloud-init progress bar is running, and Ansible's apt task hits a lock icon; after adding a wait, it passes smoothly.
Narration: first wait for the connection to be available, then wait for cloud-init to finish, and only then gather facts and run the role.
Scene 3 · 45–80s
Visual: the left path goes through the public IP and NSG allowlist; the right path enters the private network through the Bastion tunnel.
Narration: labs can use a public IP with source address restrictions; production is better off not exposing public SSH and connecting through Bastion or an internal control node.
or score ≥ 70% on the quiz

Module 5 · Secrets: the Key Vault lookup plugin and managed identities

30:00 – 37:00 · The lookup plugin always runs on the control node: whoever fetches the secret depends on the control node's identity; the VM's own managed identity is used for “processes on the VM” to fetch secrets
7 minlookup: azure.azcollection.azure_keyvault_secretuse_msi defaults to true★★★★★
Learning objectives
  • Use lookup('azure.azcollection.azure_keyvault_secret', 'redis-password', vault_url=…) to read secrets at runtime, replacing the Ansible Vault–encrypted myapp_redis_password.
  • Explain the lookup plugin's authentication behavior: by default use_msi: true, try managed identity first, then follow auth_source; on a laptop, you should use_msi=false + auth_source='cli'.
  • Enable RBAC authorization for Key Vault and assign roles following least privilege Key Vault Secrets User (read) / Key Vault Secrets Officer (write); use no_log to keep secrets out of logs.
  • Distinguish two modes: the control node fetches the secret and pushes it down (push) vs. the VM uses its own managed identity to fetch the secret at runtime (pull).
Prerequisites: Lesson 2 Ansible Vault and no_log; M1 credentials; M3's vm_identity: SystemAssigned. Importance:★★★★★

What: the lookup plugin and its parameters

azure.azcollection.azure_keyvault_secret is a lookup plugin. Lookup plugins run during template rendering on the control node (regardless of which host the play targets), returning the secret value from Key Vault to the Jinja2 expression.

ParametersDescription (4.2.0 docs)
Positional argument termssecret name; name/version can pin a version; omit it to get the latest
vault_urlRequired, for example https://kv-ansible-ab12.vault.azure.net
auth_sourceauto (default) / cli / env / msi
use_msiDefault true: try managed identity first, then use auth_source; set it to false to skip
client_id / secret / tenant (alias tenant_id) / subscription_idservice principal, or the client_id of a user-assigned managed identity; can come from AZURE_CLIENT_ID,AZURE_SECRET,AZURE_TENANT
oidc_token / oidc_token_file_pathworkload identity federation (lesson 5)
cloud_environmentDefault AzureCloud
use_cliRemoved in 4.0.0; use auth_source: cli

Note: there is no secret_name keyword argument; the secret name is a positional argument. To write/manage secrets, use the module azure_rm_keyvaultsecret, and to query metadata, use azure_rm_keyvaultsecret_info, and to create a vault, use azure_rm_keyvault.

Why: why use Key Vault instead of Ansible Vault

Ansible Vault (lesson 2)Azure Key Vault
Where secrets are storedEncrypted, in the Git repositoryA cloud service backed by HSMs
Access controlAnyone with the vault password can decrypt everythingEntra ID + RBAC, scoped down to individual secrets
RotationRe-encrypt, commit, and distribute the passwordNew versions take effect immediately; expiration and rotation policies can be set
AuditingGit historyDiagnostic logs record every read (who and when)
Offline availabilityYesRequires network and Azure identity

How: two modes

Mode A · Push: the control node fetches, Ansible pushes

  1. The template contains lookup('azure.azcollection.azure_keyvault_secret', …), and the plugin on the control node is invoked.
  2. The plugin (use_msi: true when set) first requests IMDS 169.254.169.254 for a managed identity token; if the control node is not an Azure VM, this step fails, then it falls back per auth_source to get credentials (CLI/env…).
  3. Use the token (with resource/scope set to https://vault.azure.net) to call the Key Vault data plane GET /secrets/redis-password; Key Vault authorizes via RBAC (Microsoft.KeyVault/vaults/secrets/getSecret/action, included in the Secrets User role).
  4. The value is returned to the template → becomes a module parameter → is sent to the VM over SSH and written to /etc/myapp.env (0600). The whole process uses no_log: true to mask it.

Mode B · Pull: the VM uses its own managed identity to fetch

The VM has a system-assigned managed identity enabled (in M3, vm_identity: SystemAssigned), and is granted Key Vault Secrets User. Processes on the VM request a token from IMDS and read Key Vault directly. The secret does not pass through the control node, and does not appear in Ansible's parameters; Ansible only distributes the configuration of “which Key Vault and which secret to fetch.” When the application supports it (the Azure SDK's DefaultAzureCredential), this is the better choice.

When: which mode to choose

  • The configuration file must contain the plaintext secret (for example, redis.conf's requirepass): Mode A (or fetch with MI on the VM and let a local script write it).
  • The application can read the secret itself at startup: Mode B; rotating the secret does not require rerunning Ansible.
  • The control node is inside Azure (AWX/Runner): Mode A can also use a managed identity, with no long-lived keys at all.

Comparison with similar technologies

azure_keyvault_secret lookupcommunity.hashi_vault lookupAAP 2.6 external credential plugins
BackendsAzure Key VaultHashiCorp VaultAzure Key Vault, HashiCorp Vault, CyberArk, AWS Secrets Manager, etc.
Where it is fetchedcontrol node, at playbook runtimeControl nodethe platform injects credentials before the job starts
Common misconceptions (1) “The lookup runs on the target VM, so it uses the VM's managed identity”—wrong; lookups always run on the control node. (2) “On a laptop, use_msi doesn't matter”—by default it tries IMDS first and only falls back after failing, which can cause delays or confusing errors; on a local machine, set it explicitly use_msi=false. (3) “Having Key Vault Contributor lets you read secrets”—Contributor-type roles are management-plane permissions; in RBAC mode, reading secret values requires the data-plane role Key Vault Secrets User (or Officer/Administrator). (4) “It's fine to debug a variable”—-v output, callback plugins, and AWX job logs all record it, so tasks containing secrets must no_log: true.

Sequence diagram: Mode A (Push)

Jinja2 templatelookup pluginIMDS / az CLIEntra IDKey Vault lookup('…azure_keyvault_secret', 'redis-password') (1) use_msi: GET 169.254.169.254/metadata/identity Laptop: connection fails → fall back (2) auth_source=cli: read the az login token request, scope vault.azure.net access_token (3) GET https://kv-…vault.azure.net/secrets/redis-password (Bearer) → RBAC: Secrets User? 200 {"value": "…"} string value → module parameter (no_log)
Figure 5-1: the lookup plugin runs on the control node: try managed identity first, then get a token per auth_source, and finally call the Key Vault data plane

Structure diagram: Mode B (Pull, VM managed identity)

AnsibleOnly the vault name and secret name are distributed(no secret value) SSH vm-myapp-01System-assigned managed identitymyapp startup script / application SDKGET IMDS token(resource=vault.azure.net)Header: Metadata: true Token IMDS 169.254.169.254Reachable only from inside the VM GET secret kv-ansible-xxxxRBAC: VM identity = Secrets User
Figure 5-2: in Mode B, secrets do not pass through the control node; after rotating a secret, the application reads the new value on restart

Animation: how does the secret travel?

Choose a scenario to play, and watch which components the secret value passes through and at which step it could leak into logs.

Core commands and parameters

Command / modulePurposeNotes
az keyvault create … --enable-rbac-authorization trueCreate a vault that uses RBAC authorizationName is globally unique, 3–24 characters; soft delete is enabled by default
az role assignment create --role "Key Vault Secrets Officer"Grant yourself permission to write secretsscope is the vault resource ID
az role assignment create --role "Key Vault Secrets User"Grant read permission to readers (your CLI identity / SP / VM managed identity)Propagation may take a few minutes
azure_rm_keyvaultsecretWrite a secret with Ansiblekeyvault_uri secret_name secret_value
lookup('azure.azcollection.azure_keyvault_secret', NAME, vault_url=…)Read a secretuse_msi auth_source
az keyvault purgePermanently purge a soft-deleted vaultUsed for cleanup in M8

Create the Key Vault and grant access

KV=kv-ansible-$(openssl rand -hex 3)          # globally unique
az keyvault create -g rg-ansible-lab -n $KV -l canadacentral \
  --enable-rbac-authorization true --tags env=lab app=myapp owner=$USER
KVID=$(az keyvault show -n $KV --query id -o tsv)
ME=$(az ad signed-in-user show --query id -o tsv)
az role assignment create --assignee-object-id $ME --assignee-principal-type User \
  --role "Key Vault Secrets Officer" --scope $KVID
# Read-only access for the VM's system-assigned managed identity (enabled in M3)
VMPID=$(az vm show -g rg-ansible-lab -n vm-myapp-01 --query identity.principalId -o tsv)
az role assignment create --assignee-object-id $VMPID --assignee-principal-type ServicePrincipal \
  --role "Key Vault Secrets User" --scope $KVID
sleep 60   # wait for RBAC propagation
az keyvault secret set --vault-name $KV -n redis-password --value "$(openssl rand -base64 24)" -o none
echo "vault_url: https://$KV.vault.azure.net"

Note: Newer Azure CLI versions may already enable RBAC authorization by default when creating a vault; writing the parameter explicitly avoids depending on the CLI version. --assignee-principal-type This avoids “PrincipalNotFound” errors caused by Graph query delays.

Read in a playbook (Mode A)

kv_url: "https://kv-ansible-ab12cd.vault.azure.net"     # change to your
# Laptop: skip the MSI attempt and use az login; on a control node inside Azure, change to use_msi=true
myapp_redis_password: "{{ lookup('azure.azcollection.azure_keyvault_secret', 'redis-password',
                          vault_url=kv_url, use_msi=false, auth_source='cli') }}"

Variables are evaluated lazily; the lookup runs only when a task uses myapp_redis_password it, and each reference may call it again. For frequent use, read it once in pre_tasks with set_fact fetch it once (also add no_log: true).

ansible -i inventory/ tag_role_web -m ansible.builtin.debug -a "msg={{ myapp_redis_password | length }}"
ansible-playbook -i inventory/ playbooks/site-azure.yml --diff
vm-myapp-01 | SUCCESS => {
    "msg": "32"
}
TASK [myapp : Configure redis password] *****************************************
changed: [vm-myapp-01]
TASK [myapp : Env file] *********************************************************
changed: [vm-myapp-01]
...

Only prints the length, not the value. no_log: true task under --diff also shows no content; the output shows “the output has been hidden due to the fact that 'no_log: true' was specified for this result”.

Write a secret with Ansible (optional)

- name: Store generated password in Key Vault
  azure.azcollection.azure_rm_keyvaultsecret:
    keyvault_uri: "{{ kv_url }}"
    secret_name: redis-password
    secret_value: "{{ lookup('ansible.builtin.password', '/dev/null', length=32, chars=['ascii_letters','digits']) }}"
    auth_source: cli
  no_log: true
  delegate_to: localhost

Note: this task generates a new password and writes a new version on every run (not idempotent). In production, you should first use azure_rm_keyvaultsecret_info to check whether it already exists.

Mode B: read on the VM using its managed identity (demonstrating the mechanism with the uri module)

- name: Get token from IMDS (runs on the VM)
  ansible.builtin.uri:
    url: "http://169.254.169.254/metadata/identity/oauth2/token?api-version=2018-02-01&resource=https%3A%2F%2Fvault.azure.net"
    headers: { Metadata: "true" }
    return_content: true
  register: imds
  no_log: true

- name: Read secret with the VM identity
  ansible.builtin.uri:
    url: "{{ kv_url }}/secrets/redis-password?api-version=7.4"
    headers: { Authorization: "Bearer {{ imds.json.access_token }}" }
    return_content: true
  register: kvsecret
  no_log: true

- name: Prove it works without printing the value
  ansible.builtin.debug:
    msg: "secret length = {{ kvsecret.json.value | length }}"

This is only to show the real HTTP flow of “VM identity fetching secrets”; in practice, applications should directly use the Azure SDK's DefaultAzureCredential/ManagedIdentityCredential to read at runtime, rather than having Ansible read the value back.

Lab 5: migrate the Redis password from Ansible Vault to Key Vault (about 7 min)

Cost / permissions Key Vault Standard is billed per operation (on the order of a few cents per 10,000 operations; refer to the pricing page). Cost for this lab is negligible. You need permission to assign roles on the vault (Owner / User Access Administrator / Role Based Access Control Administrator).
Create the vault, grant access, write the secret: run the first section of the “Commands” tab and note vault_url.
Read from the control node:
cd ~/ansible-lab/azure
ansible localhost -m ansible.builtin.debug \
  -a "msg={{ lookup('azure.azcollection.azure_keyvault_secret','redis-password',vault_url='https://$KV.vault.azure.net',use_msi=false,auth_source='cli') | length }}"
localhost | SUCCESS => {
    "msg": "32"
}
Replace the variable source: create inventory/group_vars/tag_app_myapp.yml (see the “Commands” tab), and confirm that nothing else (for example, the lesson 2 vault file) defines it with higher precedence myapp_redis_password:
grep -rn "myapp_redis_password" ../roles ../group_vars inventory playbooks 2>/dev/null
Deploy and verify:
ansible-playbook -i inventory/ playbooks/site-azure.yml
ansible -i inventory/ tag_role_web -b -m ansible.builtin.shell \
  -a "redis-cli -a \"\$(grep -oP '(?<=REDIS_PASSWORD=).*' /etc/myapp.env)\" --no-auth-warning ping"
curl -s http://$IP:8000/healthz
vm-myapp-01 | CHANGED | rc=0 >>
PONG
ok
Try Mode B: put the three uri tasks from the “Commands” tab into playbooks/kv-pull-demo.yml (hosts: tag_role_web,gather_facts: false) and run it; it should print secret length = 32—this time the secret is fetched with the VM's managed identity; your CLI identity is not involved.
Rotation drill: az keyvault secret set --vault-name $KV -n redis-password --value "$(openssl rand -base64 24)" -o none, then run site-azure.yml again: the redis and env file tasks show changed, and the handlers restart the service,/healthz still ok.
Cleanup: the vault is deleted with the resource group in M8, but soft delete keeps the name reserved; see M8's az keyvault purge.

Case 1: AWX on Azure, zero long-lived keys

Problem: An audit requires deleting the SP keys stored in AWX. Approach: The node hosting AWX uses a user-assigned managed identity; the lookup plugin use_msi=true client_id=<the UAMI's client id>, Key Vault grants Secrets User to that identity; the resource modules auth_source: msi. Limitations: Managed identities are only available inside Azure; local developers still need az login; use group_vars to switch parameters per environment.

Case 2: a secret appeared in CI logs

Problem: A developer added debug: var=myapp_redis_password, and the CI logs are publicly visible. Approach: Immediately create a new version in Key Vault (rotate), enable an ansible-lint rule that checks whether variables containing password/secret are paired with no_log, and set in CI ANSIBLE_NO_LOG only disable it for specific jobs. Limitations: no_log only masks Ansible's output; content that the module itself writes to logs on the target machine must be handled separately.

Case 3: same-named secrets across multiple environments

Problem: dev and prod use the same playbook. Approach: One Key Vault per environment (kv-myapp-dev,kv-myapp-prod),kv_url placed in each environment inventory's group_vars, with consistent secret names; the prod vault enables purge protection and a private endpoint. Limitations: After enabling a private endpoint, the control node must be able to resolve and reach the privatelink address.

Common errors and fixes

(Forbidden) Caller is not authorized to perform action on resource. … Action: 'Microsoft.KeyVault/vaults/secrets/getSecret/action' … Code: ForbiddenByRbac

Cause: The vault uses RBAC authorization, and the caller has no data-plane read role, or the role was just assigned and has not yet propagated.

az role assignment list --scope $KVID --query "[].{who:principalName, role:roleDefinitionName}" -o table

Fix: Assign Key Vault Secrets User; wait a few minutes; confirm you are using the identity you think you are (use_msi tries MSI first!).

An error occurred while running the lookup plugin 'azure.azcollection.azure_keyvault_secret'. … ManagedIdentityCredential … / IMDS endpoint unavailable

Cause: By default use_msi: true, the IMDS attempt fails on a non-Azure machine, and there are no fallback auth_source credentials.

Fix:use_msi=false, auth_source='cli' (or env). The exact error text varies with the azure-identity version.

(SecretNotFound) A secret with (name/id) redis-pasword was not found in this key vault.

Cause: The name is misspelled, or the secret has been deleted (soft-deleted state).

az keyvault secret list --vault-name $KV --query "[].name" -o tsv
az keyvault secret list-deleted --vault-name $KV --query "[].name" -o tsv

Fix: Correct the name; to recover an accidental deletion, use az keyvault secret recover.

Unsupported parameters for lookup: use_cli

Cause: Using the syntax from before 4.0.0.

Fix:auth_source='cli'.

(VaultAlreadyExists) The vault name 'kv-ansible-lab' is already in use. / (ConflictError) … is in a deleted but recoverable state

Cause: Names are globally unique; or a vault with the same name that you deleted earlier is still in its soft-delete retention period.

az keyvault list-deleted --query "[].{name:name, purgeDate:properties.scheduledPurgeDate}" -o table

Fix: Choose a different name; or az keyvault recover -n NAME recover it; if you are sure you don't need it, then az keyvault purge -n NAME (if purge protection is enabled, it cannot be purged; you can only wait for the retention period to end).

Command-line exercises
1. Write a variable definition: from https://kv-prod.vault.azure.net read the secret db-password at the specified version 3f2a…, using the CLI identity on a laptop.
db_password: "{{ lookup('azure.azcollection.azure_keyvault_secret', 'db-password/3f2a…',
                 vault_url='https://kv-prod.vault.azure.net', use_msi=false, auth_source='cli') }}"
2. Grant the system-assigned managed identity of VM vm-myapp-01 read-only secret permission on a certain vault.
az role assignment create --assignee-object-id "$(az vm show -g rg-ansible-lab -n vm-myapp-01 --query identity.principalId -o tsv)" \
  --assignee-principal-type ServicePrincipal --role "Key Vault Secrets User" \
  --scope "$(az keyvault show -n $KV --query id -o tsv)"
Scenario analysis
You assigned Key Vault Secrets User to vm-myapp-01's managed identity, but when you run the playbook on your laptop, the lookup still reports 403. Why?

The lookup runs on the control node (your laptop), using the laptop's identity (the CLI-logged-in user or the SP in env), not the VM's managed identity. You need to grant read permission to your CLI identity (or the CI SP). If you want only the VM to read, switch to Mode B so that processes on the VM read directly with their managed identity.

Verified instructional videos

No verified video explaining azure.azcollection.azure_keyvault_secret the lookup plugin was found; refer to the official docs and the storyboard below.

Official docs

Video storyboard script (about 80 seconds)

This courseware cannot directly generate a video/MP3. The storyboard and narration script are provided and can be handed to a video tool.

Scene 1 · 0–20s
Visual: a lookup line in the playbook is highlighted, with an arrow pointing to the control node rather than the VM.
Narration: the lookup plugin always runs on the control node; the control node's identity is what fetches the secret.
Scene 2 · 20–45s
Visual: the plugin first knocks on the IMDS door; on the laptop the door won't open, so it turns to the az CLI for a token, then uses the token to unlock Key Vault.
Narration: by default it tries managed identity first, then falls back by auth source; on a laptop, turn off use_msi.
Scene 3 · 45–65s
Visual: the VM gets a token from IMDS itself and connects directly to Key Vault; the control node is grayed out.
Narration: a better approach is to have the VM read at runtime with its own managed identity; the secret never goes through Ansible.
Scene 4 · 65–80s
Visual: a line of plaintext password in the log is covered by the no_log mask.
Narration: any task that handles secrets must have no_log.
or score ≥ 70% on the quiz

Module 6 · Ansible and Terraform/Bicep division of labor

37:00 – 44:00 · Terraform/Bicep answers “what should exist in the cloud”; Ansible answers “what the machine inside should look like”; the handoff points are tags and outputs, not calling each other
7 minTerraform 1.17 · Bicep · azure.azcollectionArchitecture decision★★★★☆
Learning objectives
  • Compare Ansible and Terraform/Bicep across five dimensions: state management, dependency graph, change preview, deletion semantics, and in-OS configuration.
  • Master four common combination patterns (tag handoff, outputs generating inventory, Ansible driving Terraform, image baking) and their use cases.
  • Recognize anti-patterns: Terraform local-exec calling ansible-playbook, two tools managing the same resource, and using Ansible to maintain large-scale long-lived infrastructure without drift detection.
Prerequisites: M2 dynamic inventory, M3 resource modules; Terraform basics (the Terraform course in this repo). Importance:★★★★☆ (frequent interview topic)

What: the fundamental difference between the two types of tools

DimensionTerraform (1.17) / OpenTofuBicep / ARMAnsible (azure.azcollection)
ModelDeclarative; desired state + state fileDeclarative; ARM deployment engine (no local state)Procedural task sequence; each module is idempotent internally
Dependencies and parallelismAutomatically builds a dependency graph and runs in parallelARM infers dependencies and runs in parallelSerial in written order (per host)
Previewterraform plan (precise to the property level, marks replacements)az deployment group what-if--check --diff (module support varies; results on dependency chains are unreliable)
DeletionRemove from code → plan shows destroyComplete mode or deployment stacks' --action-on-unmanagemust be set explicitly state: absent
Immutable property changeAutomatic “destroy and recreate” (forces replacement)Deployment error or rebuild, depending on the resourceUsually errors or is ignored
In-OS configurationWeak (provisioners are officially positioned as a last resort)None (only via extensions/cloud-init)Strong: packages, files, services, users, rolling updates, orchestration
Driftplan detects, apply correctswhat-if detectsCorrects “code-managed properties” on every run

Why: why divide the work

Infrastructure's lifecycle is “create — rarely change — eventually destroy”, where what matters most is the dependency graph, precise preview, and deletion semantics. The lifecycle of OS and application configuration is “frequent change, rolling releases, patching”, where what matters most is idempotent operations on in-machine state and orchestration. Let each tool do what it does best, and define a clear handoff point.

How: four combination patterns

#PatternFlowProsWatch out
1Tag handoff (recommended)Terraform/Bicep creates the VM and applies role=web → Ansible azure_rm → dynamic inventory → hosts: tag_role_webThe two tools are fully decoupled; scale-out is automatically includedTag conventions are an “interface contract” and need documentation and policy (enforced by Azure Policy)
2Outputs generate inventoryTerraform outputs IP/hostname → generates inventory (terraform output -json, or cloud.terraform collection's terraform_provider/terraform_state inventory plugin)No dependency on cloud API queriesstate is the source of truth and must be able to read the remote state
3Ansible drives TerraformA playbook uses cloud.terraform.terraform module to run plan/apply, then uses terraform_output to read the outputs, then configuresone entry point to complete the end-to-end flow (suited to AWX workflows)Terraform state still needs a remote backend and locking
4Image bakingPacker + Ansible provisioner build the image → Terraform/Bicep use the image to create the VMSS → ready on bootImmutable infrastructure, fastest to scale outevery change requires rebuilding the image; runtime config (secrets) is injected separately

When: when “Ansible only” also makes sense

  • few resources, short lifecycle (labs, PR environments, demos) — the M3 scenario in this lesson.
  • the organization already has a mature Ansible platform (AAP) and lacks Terraform skills and state management capability.
  • a tightly coupled “configure right after create” flow, with the whole set of resources cleaned up by deleting the resource group.

Anti-patterns

Anti-pattern list ① Terraform local-exec Calling ansible-playbook: a configuration failure puts the Terraform resource into the tainted state; configuration changes cannot run on their own; the provisioner only runs at creation (HashiCorp officially positions provisioners as a “last resort”).
② Two tools managing the same resource: for example, Terraform manages an NSG and Ansible also uses purge_rules: true to manage the same NSG — the two keep “correcting” each other. Rule: each resource can have only one owner.
③ Ansible maintaining large, long-lived infrastructure with no drift detection: no plan, and deletion depends on someone remembering to write absent.
④ In Terraform, using remote-exec to install software: cramming configuration management into an infrastructure tool loses idempotency and reuse.
⑤ Tags named arbitrarily: the handoff point breaks and the dynamic inventory selects the wrong machines.

Architecture diagram: recommended layers and handoff points

Layer 1 · Platform/infrastructure (Terraform or Bicep, state / deployment history)Subscriptions, networking, NSGs, Key Vault, VMs/VMSS, load balancing, managed identities and RBAC → outputs: role/env/app tags, Key Vault URL Handoff point (contract)Tag standard · outputs · Key Vault secret names Layer 2 · Configuration and release (Ansible, stateless, repeatable)azure_rm dynamic inventory → roles (OS hardening, myapp, monitoring agent) → rolling release → health check Layer 0 (optional) · Image: Packer + Ansible provisioner → Azure Compute Gallery image version → referenced by Layer 1
Figure 6-1: the infrastructure and configuration layers hand off only through a “contract”; each resource has exactly one owner

Flowchart: one complete change using the tag handoff pattern

PR: count 2→3terraform plan Approval → applyNew VM role=web CI next stageansible-inventory site.ymlhosts: tag_role_web New VM configuredExisting VM changed=0 Terraform doesn’t know Ansible exists, and Ansible doesn’t read Terraform state — they only share tags
Figure 6-2: scaling out requires no changes to any Ansible code

Animation: three integration methods, comparing what happens on failure

Each method stops when a “configuration step fails”, so you can observe the state each tool leaves behind.

Core commands

Command / modulePurposeNotes
az deployment group what-ifBicep change previewEquivalent to plan
az deployment group create -f vm.bicepDeploy Bicep-p name=value
azure.azcollection.azure_rm_deploymentDeploy an ARM template from AnsibleBicep must first be az bicep build compiled to JSON
cloud.terraform.terraformRun Terraform from Ansibleproject_path state: present check_mode Produces a plan
cloud.terraform.terraform_outputRead Terraform outputsPass to subsequent tasks / add_host
terraform output -jsonData source for generating a static inventorySuited to one-time bootstrapping

Bicep: add one more web VM (reusing the M3 VNet/subnet)

param vmName string = 'vm-myapp-02'
param location string = resourceGroup().location
param adminUsername string = 'azureuser'
@secure()
param sshPublicKey string
param owner string

var tags = { env: 'lab', app: 'myapp', role: 'web', owner: owner, managedBy: 'bicep' }

resource subnet 'Microsoft.Network/virtualNetworks/subnets@2024-05-01' existing = {
  name: 'vnet-ansible/snet-app'
}

resource pip 'Microsoft.Network/publicIPAddresses@2024-05-01' = {
  name: 'pip-${replace(vmName, 'vm-', '')}'
  location: location
  sku: { name: 'Standard' }
  properties: { publicIPAllocationMethod: 'Static' }
  tags: tags
}

resource nic 'Microsoft.Network/networkInterfaces@2024-05-01' = {
  name: 'nic-${replace(vmName, 'vm-', '')}'
  location: location
  tags: tags
  properties: {
    ipConfigurations: [ {
      name: 'ipconfig1'
      properties: {
        subnet: { id: subnet.id }
        privateIPAllocationMethod: 'Dynamic'
        publicIPAddress: { id: pip.id }
      }
    } ]
  }
}

resource vm 'Microsoft.Compute/virtualMachines@2024-07-01' = {
  name: vmName
  location: location
  tags: tags
  identity: { type: 'SystemAssigned' }
  properties: {
    hardwareProfile: { vmSize: 'Standard_B2s' }
    osProfile: {
      computerName: vmName
      adminUsername: adminUsername
      linuxConfiguration: {
        disablePasswordAuthentication: true
        ssh: { publicKeys: [ { path: '/home/${adminUsername}/.ssh/authorized_keys', keyData: sshPublicKey } ] }
      }
    }
    storageProfile: {
      imageReference: { publisher: 'Canonical', offer: 'ubuntu-24_04-lts', sku: 'server', version: 'latest' }
      osDisk: { createOption: 'FromImage', diskSizeGB: 30, managedDisk: { storageAccountType: 'StandardSSD_LRS' }, deleteOption: 'Delete' }
    }
    networkProfile: { networkInterfaces: [ { id: nic.id, properties: { deleteOption: 'Delete' } } ] }
  }
}

output vmName string = vm.name
output publicIp string = pip.properties.ipAddress
cd ~/ansible-lab/azure
az deployment group what-if -g rg-ansible-lab -f bicep/vm.bicep \
  -p sshPublicKey="$(cat ~/.ssh/id_ed25519.pub)" owner=$USER
az deployment group create -g rg-ansible-lab -f bicep/vm.bicep \
  -p sshPublicKey="$(cat ~/.ssh/id_ed25519.pub)" owner=$USER --query properties.outputs
Resource and property changes are indicated with this symbol:
  + Create
The deployment will update the following scope:
Scope: /subscriptions/0000.../resourceGroups/rg-ansible-lab
  + Microsoft.Compute/virtualMachines/vm-myapp-02
  + Microsoft.Network/networkInterfaces/nic-myapp-02
  + Microsoft.Network/publicIPAddresses/pip-myapp-02
Resource changes: 3 to create.
{
  "publicIp": { "type": "String", "value": "20.151.56.78" },
  "vmName":   { "type": "String", "value": "vm-myapp-02" }
}

deleteOption: 'Delete' Have the OS disk and NIC deleted along with the VM to reduce orphaned resources (the public IP can also be set with deleteOption in the NIC’s ipConfiguration, if needed). Ownership note: This VM is managed by Bicep, so don’t add it to Ansible’s provision.yml of vms list.

Handing off to Ansible: zero code changes

ansible-inventory -i inventory/ --graph tag_role_web --flush-cache
ansible-playbook -i inventory/ playbooks/site-azure.yml
@tag_role_web:
  |--vm-myapp-01
  |--vm-myapp-02
...
PLAY RECAP **********************************************************************
vm-myapp-01 : ok=14  changed=0  ...
vm-myapp-02 : ok=14  changed=9  ...

The managed identity of vm-myapp-02 has no Key Vault permission, but in pattern A the secrets are fetched with the control node’s identity, so the deployment is unaffected; if you use pattern B, you need to create the role assignment in Bicep as well (Microsoft.Authorization/roleAssignments) — this is an example of “RBAC belongs to the infrastructure layer.”

Pattern 3: Ansible drives Terraform (illustrative)

- hosts: localhost
  gather_facts: false
  tasks:
    - name: terraform apply
      cloud.terraform.terraform:
        project_path: "{{ playbook_dir }}/../terraform"
        state: present
        force_init: true
    - name: Read outputs
      cloud.terraform.terraform_output:
        project_path: "{{ playbook_dir }}/../terraform"
      register: tf
    - ansible.builtin.meta: refresh_inventory

Requires ansible-galaxy collection install cloud.terraform and the control node has the terraform binary; for parameters, follow the cloud.terraform documentation.

Lab 6: Bicep creates the machine, Ansible configures it (about 7 minutes; the second VM incurs charges)

Save the Bicep file: mkdir -p ~/ansible-lab/azure/bicep, copying the command from the “Commands” tab vm.bicep. az bicep version Confirm the Bicep CLI is available (if not, az bicep install).
Run what-if, then deploy: run the two commands on the “Commands” tab az deployment group commands.
The dynamic inventory automatically picks up: ansible-inventory -i inventory/ --graph tag_role_web --flush-cache, you should see two hosts.
Configure: ansible-playbook -i inventory/ playbooks/site-azure.yml; vm-myapp-01 is changed=0, while vm-myapp-02 is a fresh install.
Ownership-conflict demo (read-only thought exercise): what happens if you now add vm-myapp-02 to provision.yml’s vms list? — azure_rm_virtualmachine treats it as an existing VM, compares it with Ansible’s parameters and modifies it (for example, tags are merged and managed identity settings are changed), and the next Bicep deployment changes it back. Conclusion: each resource can have only one owner.
Clean up the second VM:
az vm delete -g rg-ansible-lab -n vm-myapp-02 --yes     # OS disk and NIC have deleteOption set to Delete
az network public-ip delete -g rg-ansible-lab -n pip-myapp-02
az resource list -g rg-ansible-lab --query "[?contains(name,'myapp-02')].name" -o tsv   # should be empty

Case 1: platform team uses Terraform, application team uses Ansible

Problem: The two teams’ boundaries are unclear, and they often overwrite each other’s NSG rules. Approach: A written “tag and ownership contract”: the platform team (Terraform) owns RGs, VNets, NSGs, VMs and RBAC; the application team (Ansible) owns only what is inside the VMs; requests for new ports go to the platform team as a PR. Azure Policy enforces role/env/owner that tags exist. Limitation: The process is slower, but incidents drop significantly.

Case 2: migrating from local-exec to a two-stage pipeline

Problem: In Terraform, provisioner "local-exec" { command = "ansible-playbook …" }; when configuration fails, the resource is marked tainted and the VM is rebuilt on the next apply; configuration changes also have to “touch” Terraform. Approach: Remove the provisioner; pipeline stage 1 terraform apply, stage 2 ansible-playbook (dynamic inventory); configuration changes run only stage 2. Limitation: Handle the window where “the VM is created but not yet configured” (don’t add it to the load balancer until the health probe passes).

Case 3: configuring VMSS scale-out

Problem: Nobody runs Ansible on instances that VMSS scales out. Approach: Packer (the Ansible provisioner reuses the same set of roles) bakes the image into Azure Compute Gallery, and Terraform references the image version; at runtime, only environment variables and the Key Vault name are injected via cloud-init, and the application fetches secrets with its managed identity (M5 pattern B). Limitation: The image pipeline needs version management and periodic patch rebuilds.

Common errors and fixes

Every Terraform and Ansible run shows changed: NSG rules keep flipping

Cause: Both tools manage the same NSG (Ansible’s purge_rules: true removes Terraform’s rules, and Terraform adds them back).

az network nsg show -g rg-ansible-lab -n nsg-app --query tags
az monitor activity-log list -g rg-ansible-lab --offset 1d --query "[?contains(resourceId,'nsg-app')].{who:caller,op:operationName.value,time:eventTimestamp}" -o table

Fix: Decide on a single owner and tag the resource with an managedBy=terraform tag; forbid Ansible code review from modifying such resources.

Error: local-exec provisioner error … exit status 2 (the Terraform resource is marked tainted)

Cause: The ansible-playbook in the provisioner failed.

Fix: Short term: terraform untaint; long term, remove the provisioner and switch to a two-stage pipeline.

InvalidTemplate / Bicep build: The resource type 'Microsoft.Compute/virtualMachines@2024-07-01' … / BCP081 warning

Cause: The Bicep CLI is too old and has no type information for that API version (BCP081 is a “type unavailable” warning; the deployment usually can still proceed).

az bicep upgrade; az bicep version

Fix: Upgrade Bicep, or switch to an API version Bicep knows.

The Ansible dynamic inventory can’t see the VM Bicep just created

Cause: inventory cache; tag spelling doesn’t match what keyed_groups expects (Role vs role); exclude_host_filters requires app=myapp.

Fix:--flush-cache; compare against az vm show --query tags; put the tag standard into Bicep’s shared variables.

Command-line exercises
1. Preview what changes the Bicep template would make to the resource group.
az deployment group what-if -g rg-ansible-lab -f bicep/vm.bicep -p sshPublicKey="$(cat ~/.ssh/id_ed25519.pub)" owner=$USER
2. List resources in the resource group that have the managedBy=bicep tag.
az resource list -g rg-ansible-lab --tag managedBy=bicep --query "[].{name:name,type:type}" -o table
Scenario analysis
The team wants “one command” to create and configure everything and proposes calling ansible-playbook from local-exec in Terraform. How would you respond? Give alternatives.

Point out the problems: the provisioner only runs at creation, so configuration changes cannot run on their own; a failure taints the resource and it gets rebuilt on the next apply; it couples two lifecycles together; and HashiCorp recommends provisioners only as a last resort. Alternatives: (1) a two-stage CI pipeline (terraform apply → ansible-playbook, with the dynamic inventory selecting hosts by tag), which still looks like “one button” from outside; (2) an AWX/AAP workflow template: Terraform job (cloud.terraform module) → inventory sync → configuration job; (3) if you want “ready at boot”, bake images with Packer.

Verified teaching videos

▶
Terraform in 100 Seconds — Fireship
English · about 2 minutes · quick overview of declarative IaC and state
▶
Terraform explained in 15 mins | Terraform Tutorial for Beginners — TechWorld with Nana
English · the video specifically compares the roles of Terraform and Ansible (infrastructure orchestration vs configuration management)
▶
Ansible in 100 Seconds — Fireship
English · watch alongside the Terraform video above

Official docs

Video storyboard script (about 80 seconds)

This courseware cannot directly generate video or MP3, so a storyboard and narration script are provided for a video tool to produce.

Shot 1 · 0–20s
Visual: cloud resource blocks on top (Terraform/Bicep icons), gears inside a VM at the bottom (Ansible icon).
Narration: infrastructure tools decide what exists in the cloud; configuration management tools decide what the machines look like inside.
Shot 2 · 20–50s
Visual: Bicep creates a VM and tags it role=web, and Ansible’s dynamic inventory pulls it in like a magnet.
Narration: the two hand off through tags without calling each other, and scaling out requires no Ansible code changes.
Shot 3 · 50–80s
Visual: two hands pull on one NSG at the same time, its rules flicker back and forth, and a red X appears.
Narration: each resource can have only one owner; don’t use local-exec to tie two tools together.
or score ≥ 70% on the quiz

Module 7 · Troubleshooting on the cloud

44:00 – 53:00 · First work out which stage the failure is in: local environment → authentication → inventory → ARM authorization/throttling → network connectivity → managed node; each stage has matching evidence
9 minInteractive troubleshooting tree6 common failure types★★★★★
Learning objectives
  • Split the cloud Ansible execution chain into 6 stages, and quickly locate the stage from an error keyword.
  • Master the diagnostic commands for each stage: ansible --version,pipx runpip,az account show,ansible-inventory -vvvv,az role assignment list,az network watcher test-ip-flow,ssh -vvv.
  • Understand ARM’s 403 (AuthorizationFailed / RBAC propagation) and 429 (TooManyRequests / Retry-After) mechanisms, and know how to reduce call volume.
Prerequisites: M1–M5. Importance:★★★★★

What: the 6 stages of the execution chain

StageWhat happensTypical error keywordsFirst diagnostic command
① Local environmentWhich Python Ansible uses, collection version, whether the SDK is installedFailed to import the required Python library,couldn't resolve module/actionansible --version; ansible-galaxy collection list azure.azcollection
② AuthenticationObtain an Entra ID tokenFailed to get credentials,AADSTS7000215 (wrong secret),AADSTS7000222 (secret expired),AADSTS700016 (application not found)az account show; env | grep ^AZURE_
③ Inventoryplugin parsing, listing VMs, filtering, groupingUnable to parse … as an inventory source,provided hosts list is empty,Could not match supplied host patternansible-inventory -i … --graph -vvvv
④ ARM authorization / throttlingRBAC authorization, resource provider registration, Azure Policy, throttlingAuthorizationFailed (403),RequestDisallowedByPolicy,MissingSubscriptionRegistration,TooManyRequests (429)az role assignment list --assignee …
⑤ Network connectivitycontrol node → VM TCP 22Connection timed out,Connection refused,No route to hostnc -vz IP 22; az network watcher test-ip-flow
⑥ Managed nodeSSH authentication, sudo, Python, module executionPermission denied (publickey),Missing sudo password,dpkg lockssh -vvv; ansible -m ping -vvv

Why: why troubleshooting in the cloud is harder

In local container labs, failures are basically only in ⑤⑥; in the cloud you add identity (who is calling), authorization (is it allowed), eventual consistency (role assignments and resource creation take time to propagate), quotas and throttling, and network security groups and platform default rules. The same “UNREACHABLE” can come from an NSG, a powered-off VM, a changed egress IP, or sshd not yet ready.

How: a few key mechanisms

403 AuthorizationFailed

ARM performs an RBAC check before routing the request to the resource provider. The error message states client '…' with object id '…' does not have authorization to perform action 'Microsoft.Compute/virtualMachines/write' over scope '…'— three elements: who (object id),what action,what scope. A newly assigned role may take a few minutes to take effect; group memberships cached in the CLI token may need you to sign in again (az logout; az login) to update.

429 TooManyRequests

ARM applies request rate limits per subscription, tenant and principal (the official docs describe a per-region token bucket algorithm, with reads, writes and deletes throttled separately; for exact numbers, see the official “Understand how Azure Resource Manager throttles requests”). Resource providers (such as Microsoft.Compute) also have their own throttling policies. Response headers x-ms-ratelimit-remaining-subscription-reads and similar show the remaining quota, and 429 responses include Retry-After. The Azure SDK (azure-core’s retry policy) automatically retries based on Retry-After, so the symptom is often “slower” rather than “failed.” Common triggers: include_vm_resource_groups: ['*'] scanning large subscriptions, high forks forks, the azure_rm module running on every host (it should run once on localhost), and multiple pipelines running in parallel.

5 reasons the inventory is empty

  1. The file name doesn’t end with azure_rm.yml / the plugin is not enabled;
  2. authenticated to the wrong subscription, or the identity can’t see the resource group;
  3. the resource group name is misspelled (the plugin matches RG names case-insensitively, but a typo returns 0 hosts);
  4. A VM that is not running is default_host_filters excluded, or your filter is too strict;
  5. the cache holds stale data.

When: troubleshooting order

Left to right: first use ansible --version and az account show to rule out ①②, then ansible-inventory --graph to rule out ③, then on a single host ansible HOST -m ping -vvv to rule out ⑤⑥. When the azure_rm module errors, look at ④ directly.

Comparison with similar technologies

SymptomLocal container labAzure
Host unreachablecontainer not running, port mappingNSG, egress IP, VM deallocated, sshd/cloud-init not ready
Insufficient permissionssudosudo + RBAC (management plane) + Key Vault data plane role
Wrong host listINI typodynamic inventory filters, tags, subscription, cache
Common misconceptions① “403 means the role isn’t assigned” — it could also be assigned at the wrong scope, assigned to another identity (the auto chain picked the SP from environment variables), or not yet propagated; an Azure Policy denial would be RequestDisallowedByPolicy (also 403 but for a completely different reason). ② “If you get 429, add forks to speed it up” — this makes it worse. ③ “-vvvv shows every HTTP request” — the inventory plugin prints some batch request info under -vvvv; SDK requests inside the module need to be enabled through log_mode/log_path or ANSIBLE_DEBUG, and note the logs may contain sensitive information.

Fault location diagram: which stage the error falls in

① Local environmentPython · collections · SDK ② AuthenticationEntra ID token ③ Inventorylist VMs · filter · group ④ ARMRBAC · Policy · 429 ⑤ NetworkNSG · IP · 22 ⑥ Managed nodeSSH · sudo · modules ImportErrorexternally-managedcouldn't resolve module Failed to get credentialsAADSTS7000215/222wrong subscription Unable to parsehosts list is emptyNo match: tag_role_web AuthorizationFailedRequestDisallowedByPolicyTooManyRequests 429 Connection timed outConnection refusedNo route to host Permission deniedMissing sudo passworddpkg lock ①–④ happen between the control node and Azure (hosts: localhost or the inventory stage); ⑤–⑥ happen between the control node and the VM (UNREACHABLE / FAILED)
Figure 7-1: use the error keyword to locate the stage first, then check that stage’s evidence

Flowchart: the three questions for a 403

403 AuthorizationFailedRead the 3 elements in the error Who? object id= the identity you think it is? What action? actionmanagement plane / data plane What scope? scopeRG / resource / subscription Does the role assignment exist and cover the scope?→ wait for propagation / sign in again Doesn’t exist → assign the minimum role(Contributor / Secrets User)
Figure 7-2: the 403 error itself contains all the information needed for diagnosis

Fault injection simulator

Choose a fault and play ansible-playbook -i inventory/ playbooks/all-in-one.yml, and observe at which stage execution stops, what it outputs, and what evidence to check.

Diagnostic command quick reference

StageCommandWhat to look at
①ansible --version; pipx runpip ansible list | grep azure-python version and path; whether the SDK exists
①ansible-doc azure.azcollection.azure_rm_virtualmachine | headwhether the module can be found, and the active collection path
②az account show; az ad signed-in-user show --query idSubscription and identity
②az ad app credential list --id <appId> --query "[].endDateTime"whether the SP secret has expired
③ansible-inventory -i inventory/ --graph -vvvvwhich plugin parsed which file; excluded hosts
④az role assignment list --assignee <objectId> --all -o tableroles and scope
④az provider show -n Microsoft.Compute --query registrationStatewhether the resource provider is registered
④az monitor activity-log list -g rg-ansible-lab --status Failed --offset 2hthe failed operation, caller, Policy denial
⑤nc -vz -w 5 IP 22; az network watcher test-ip-flow …whether TCP is reachable; which NSG rule applies
⑤az vm get-instance-view -g … -n … --query instanceView.statuses[1]VM power state
⑥ansible HOST -m ping -vvv; ssh -vvv azureuser@IPSSH command line, auth method, sudo
⑥az vm run-command invoke … --scripts "journalctl -u ssh -n 50"when SSH is unreachable, view logs inside the VM via the Azure agent

Turn on the azure_rm module’s SDK logs (use with caution)

ansible localhost -m azure.azcollection.azure_rm_resourcegroup_info \
  -a "name=rg-ansible-lab auth_source=cli log_mode=debug log_path=/tmp/azure_rm.log" -vvv
grep -E "HTTP|Request URL|x-ms-ratelimit" /tmp/azure_rm.log | head
rm -f /tmp/azure_rm.log     # the log may contain tokens or sensitive information

log_mode/log_path is a shared collection parameter (see the options listed in M2); the exact log contents vary with the SDK version.

Check remaining throttling quota

az rest --method get --url "https://management.azure.com/subscriptions/$(az account show --query id -o tsv)/resourceGroups?api-version=2021-04-01" --debug 2>&1 \
  | grep -i "x-ms-ratelimit-remaining"
DEBUG: cli.azure.cli.core.sdk.policies:     'x-ms-ratelimit-remaining-subscription-reads': '249'
DEBUG: cli.azure.cli.core.sdk.policies:     'x-ms-ratelimit-remaining-subscription-global-reads': '3749'

Troubleshoot SSH via the Azure agent (no network reachability needed)

az vm run-command invoke -g rg-ansible-lab -n vm-myapp-01 --command-id RunShellScript \
  --scripts "systemctl is-active ssh; cloud-init status; ss -ltnp | grep -E ':22|:8000'"
"message": "Enable succeeded: \n[stdout]\nactive\nstatus: done\nLISTEN 0 4096 0.0.0.0:22 ...\nLISTEN 0 2048 0.0.0.0:8000 ...\n\n[stderr]\n"

Lab 7: inject 4 faults and fix them one by one (about 8 minutes)

Fault A · Empty inventory:
cd ~/ansible-lab/azure
mv inventory/lab.azure_rm.yml inventory/lab.yml
ansible -i inventory/ tag_role_web -m ping
ansible-inventory -i inventory/lab.yml --graph -vvvv 2>&1 | grep -iE "azure_rm inventory filename|Unable to parse"
mv inventory/lab.yml inventory/lab.azure_rm.yml
[WARNING]: Unable to parse /home/andy/ansible-lab/azure/inventory/lab.yml as an inventory source
[WARNING]: Could not match supplied host pattern, ignoring: tag_role_web
...azure_rm inventory filename must end with 'azure_rm.yml' or 'azure_rm.yaml'
Fault B · Wrong authentication source:
ANSIBLE_AZURE_AUTH_SOURCE=env ansible localhost -m azure.azcollection.azure_rm_resourcegroup_info -a "name=rg-ansible-lab"
# no AZURE_* variables → fails; recovers after removing the forced setting or changing it to cli
ANSIBLE_AZURE_AUTH_SOURCE=cli ansible localhost -m azure.azcollection.azure_rm_resourcegroup_info -a "name=rg-ansible-lab" | head -3
Fault C · SSH timeout (wrong NSG source IP):
ansible-playbook playbooks/provision.yml -e my_ip=198.51.100.7     # deliberately use someone else’s IP
ansible -i inventory/ tag_role_web -m ping -T 10
az network watcher test-ip-flow -g rg-ansible-lab --vm vm-myapp-01 --direction Inbound --protocol TCP \
  --local 10.30.1.4:22 --remote $MY_IP:50000
ansible-playbook playbooks/provision.yml -e my_ip=$MY_IP                # fix
vm-myapp-01 | UNREACHABLE! => {
    "changed": false,
    "msg": "Failed to connect to the host via ssh: ssh: connect to host 20.151.12.34 port 22: Connection timed out",
    "unreachable": true
}
{
  "access": "Deny",
  "ruleName": "securityRules/DenyAllInBound"
}

The first time you use Network Watcher, one is automatically created in the subscription NetworkWatcherRG (one per region, no extra charge). --local The private IP in --host should match the value you look up.

Fault D · 403 (service principal permissions revoked) (requires the sp-ansible-lab created in M1 and the environment variables):
APPID=<appId of sp-ansible-lab>
az role assignment delete --assignee $APPID --role Contributor --scope /subscriptions/$SUB/resourceGroups/rg-ansible-lab
az role assignment create --assignee $APPID --role Reader --scope /subscriptions/$SUB/resourceGroups/rg-ansible-lab
sleep 60
ANSIBLE_AZURE_AUTH_SOURCE=env ansible-playbook playbooks/provision.yml -e my_ip=$MY_IP 2>&1 | grep -m1 -o "AuthorizationFailed.*scope '[^']*'"
AuthorizationFailed) The client '11111111-…' with object id '99999999-…' does not have authorization to perform action 'Microsoft.Resources/subscriptions/resourcegroups/write' over scope '/subscriptions/0000…/resourcegroups/rg-ansible-lab'

Reader can read (the inventory works), but cannot write (resourcegroups/write is denied). Fix: restore Contributor and remove Reader.

Review with the troubleshooting tree: in the interactive tree on the “Troubleshooting” tab, walk through the symptoms you see and confirm each fault can be located.
Cleanup: confirm the NSG is restored to your IP and the SP has Contributor restored (or delete the SP after the capstone lab).

Case 1: deployment fails every Monday morning (SP secret expired)

Problem: CI reports AADSTS7000222: The provided client secret keys for app '…' are expired. Approach: Short term, rotate the secret (az ad app credential reset --id … --append); long term, migrate to OIDC federated credentials (lesson 5), and set expiry alerts for any SP still using a secret. Limitation:--append Keep the old secret for a smooth cutover, and delete it after switching.

Case 2: the playbook becomes extremely slow during a batch scale-out before a big sale

Problem: The playbook runs azure_rm_virtualmachine_info on each host (forks=50) to gather information, triggers Compute throttling, the SDK backs off per Retry-After, and runtime grows from 3 minutes to 40 minutes. Approach: Switch to run_once: true + delegate_to: localhost a single query for the whole RG, sharing the results via set_fact ; enable inventory caching; move filters that depend only on tags into exclude_host_filters. Limitation: Throttling is shared per subscription, so other automation in the same subscription is also affected; stagger runs.

Case 3: RequestDisallowedByPolicy

Problem: Creating a public IP in a new subscription failed with a policy denial. Approach: The error includes the policy assignment name and definition ID; check az policy assignment show; the organization prohibits VMs from having public IPs, so switch to the M4 Bastion / private control node approach. Limitation: Don’t request a policy exemption to “get around” it; follow the platform design.

Interactive troubleshooting tree: Ansible + Azure

Work through it by the symptoms you see; each branch ends with the diagnostic command and the fix.

More real-world errors

couldn't resolve module/action 'azure.azcollection.azure_rm_virtualmachine'. This often indicates a misspelling, missing collection, or incorrect module path.

Cause: The collection is not installed in a path Ansible can find (for example, HOME differs when running under sudo).

ansible-config dump | grep -i COLLECTIONS_PATH
ansible-galaxy collection list azure.azcollection

Fix: install and run as the same user; or set collections_path.

(MissingSubscriptionRegistration) The subscription is not registered to use namespace 'Microsoft.Network'.
az provider register -n Microsoft.Network --wait; az provider register -n Microsoft.Compute --wait

Common in new subscriptions; registering providers requires Contributor at subscription level.

(TooManyRequests) The request is being throttled as the limit has been reached for operation type - Read_ObservationWindow_00:05:00. … Retry-After …

Cause: Too many read requests in a short time (an example of the Compute resource provider’s throttling policy; use the actual error for the specific fields).

Fix: Lower forks, run azure_rm calls once on localhost, enable inventory caching, and stagger runs; the SDK retries automatically per Retry-After.

fatal: [vm-myapp-01]: FAILED! => {"msg": "Missing sudo password"}

Cause:ansible_user The user is not the admin account created with the VM (only admin_username gets passwordless sudo by default).

Fix: Use azureuser; or configure sudoers for the deployment user in the role (lesson 2).

Command-line exercises
1. SSH to the VM isn’t working; check sshd and cloud-init status without relying on network reachability.
az vm run-command invoke -g rg-ansible-lab -n vm-myapp-01 --command-id RunShellScript \
  --scripts "systemctl is-active ssh; cloud-init status"
2. Determine which NSG rule handles inbound TCP 22 traffic from 203.0.113.10.
az network watcher test-ip-flow -g rg-ansible-lab --vm vm-myapp-01 --direction Inbound \
  --protocol TCP --local 10.30.1.4:22 --remote 203.0.113.10:50000
Scenario analysis
The same playbook succeeds on an engineer’s laptop but the azure_rm task fails with 403 in CI, even though the CI SP has Contributor. List the troubleshooting steps.

① Check the object id in the 403 error and confirm which identity CI actually uses (it could be another SP, or an environment variable name typo causing a fallback to another source); ② check the scope — the SP’s Contributor may only cover rg-ansible-lab, while the playbook operates on another RG or on subscription-level resources (such as registering providers, or creating the RG itself, which needs subscription-level resourcegroups/write); ③ check the action — if it is Microsoft.Authorization/roleAssignments/write, Contributor simply doesn’t allow it; ④ check whether it is a Policy denial (RequestDisallowedByPolicy); ⑤ check whether the role was just assigned and hasn’t propagated yet.

Verified teaching videos

No verified video on “Ansible on Azure troubleshooting” was found. Use the official docs together with the storyboard below.

Official docs

Video storyboard script (about 90 seconds)

This courseware cannot directly generate video or MP3, so a storyboard and narration script are provided for a video tool to produce.

Shot 1 · 0–20s
Visual: a six-car train: local environment, authentication, inventory, ARM, network, managed node.
Narration: when troubleshooting in the cloud, first work out which car the fault is in.
Shot 2 · 20–50s
Visual: the 403 error is enlarged, with three highlighted boxes circling the object id, action and scope.
Narration: an authorization error already states who, what action, and where.
Shot 3 · 50–70s
Visual: a flood of requests hits ARM, a red 429 light comes on, and Retry-After is shown beside it.
Narration: when throttled, the SDK backs off and retries automatically; the right fix is to reduce calls, not raise concurrency.
Shot 4 · 70–90s
Visual: the SSH line is cut, and Network Watcher points to DenyAllInBound.
Narration: for a connection timeout, check the NSG and egress IP first; IP flow verify pinpoints it in one step.
or score ≥ 70% on the quiz

Module 8 · Cost, cleanup and self-check

53:00 – 60:00 · Know where the money goes; shutting down is not the same as stopping charges; deleting the resource group is the cleanest approach; soft-deleted Key Vaults and service principals must be handled separately
7 minteardown.ymlBe sure to run the cleanup★★★★☆
Learning objectives
  • List this lesson’s billable items: VM compute, managed disks, Standard public IPs, Bastion, Key Vault operations, and outbound traffic; distinguish Stopped and Deallocated (Stopped (deallocated)).
  • Write teardown.yml: a cleanup playbook that finds the lab resource group by tag and deletes it, handling Key Vault soft delete, service principals, local credentials and known_hosts.
  • Set budget alerts, use tags for cost allocation, and identify orphaned resources (disks, NICs, public IPs).
Prerequisites: M3 resources, M5 Key Vault. Importance:★★★★☆

What: this lesson’s billable items

ResourceBilling methodAfter stop / deallocateUsage in this lesson
VM Standard_B2sCompute charges billed per second (priced hourly)Shut down in the OS, or started: false: still billed; deallocate (allocated: false / az vm deallocate): compute billing stops1–2 VMs, about 1 hour each
Managed disk StandardSSD 30 GiBbilled monthly by provisioned capacity (prorated hourly)still billed, until deleted1 per VM
Standard public IP (Static)billed hourlystill billed, until deleted1 per VM (+ 1 for Bastion)
Azure Bastion Standardbilled hourly + outbound trafficcan’t be “stopped”, only deletedoptional; delete right after use
Key Vault Standardbilled per operationalmost zerodozens of operations
Outbound dataper GB (with a free allowance)—apt/pip downloads are inbound and usually not billed

Prices vary by region, currency and time; all amounts in this lesson are examples, check with the Azure Pricing Calculatoror Retail Prices API for current prices.

Why: why “delete the resource group” is the best cleanup method

  • Ansible is stateless and doesn’t remember what it created; deleting each one with state: absent easily misses auto-generated OS disks, Network Watcher, and so on.
  • The resource group is ARM’s lifecycle boundary: deleting an RG deletes all resources in it (ARM handles dependency order itself).
  • Prerequisite: all lab resources are in rg-ansible-lab, and shared resources (DNS, log workspaces) are not put in it.

How: “leftovers” beyond cleanup

LeftoverCauseHandling
Key Vault name is takenSoft delete is on by default (retention defaults to 90 days); after the RG is deleted, the vault enters a “deleted but recoverable” stateaz keyvault purge -n NAME (when purge protection is not enabled)
Service principal sp-ansible-labThe Entra ID object is not in the resource groupaz ad sp delete --id APPID (this also deletes its role assignments); if needed, az ad app delete
Role assignmentsAssignments scoped to a deleted RG become “unknown identity / orphaned” recordsare usually cleaned up along with the RG; check az role assignment list --all
NetworkWatcherRGCreated automatically on first use of Network Watcherno extra charge; can be kept
Local files~/.azure/credentials, old host keys in known_hosts, inventory cacheshred -u,ssh-keygen -R, delete cache directory

When: when to stop, when to delete

  • Continuing today: when not in use, deallocate (saves compute cost; disks and public IPs are still billed).
  • Finished for today, rebuilding tomorrow: delete the resource group, then use all-in-one.yml to rebuild in 5 minutes — this is the value of IaC.
  • Long-running environments: use auto-shutdown (the VM’s auto-shutdown schedule) plus budget alerts.

Comparison with similar technologies

AnsibleTerraformBicep
One-click deleteDelete RG (force_delete_nonempty) or absent one by oneterraform destroy (only deletes resources in state)Delete RG, or deployment stack --action-on-unmanage deleteAll
Risk of missed deletionsHigh (stateless)Low (state), but resources created out of band are not deletedMedium
Common misconceptions① “Running shutdown inside the VM stops billing” — after the OS shuts down, the state is Stopped, compute resources are still reserved and billed, so you must deallocate. ② “Deleting the VM is enough to clean up” — the Standard public IP, disks and NIC may still remain (depending on remove_on_absent / deleteOption setting). ③ “Deleting the resource group frees the Key Vault name right away” — soft delete keeps the name reserved, so purge is needed. ④ “The training subscription has free credit, so I don’t need to worry” — the credit may not stop automatically when used up, and resources like Bastion burn through money quickly.

VM power states and billing

RunningCompute ✓ Disk ✓ Public IP ✓ StoppedCompute ✓ Disk ✓ Public IP ✓OS shutdown / started: false Stopped (deallocated)Compute ✗ Disk ✓ Public IP ✓allocated: false DeletedCheck remove_on_absent/ deleteOption az vm deallocate can deallocate directly from Running; a dynamic public IP is released, while a Static one is kept
Figure 8-1: only deallocation stops compute billing; disks and public IPs keep billing until they are deleted

Cleanup flow

Find RG by tagenv:lab owner:me Record the Key Vault name(before deletion) Delete RGforce_delete_nonempty purge Key VaultDelete SP Verify 0 resourcesClear local credentials/cache
Figure 8-2: the five stages of teardown.yml

Interactive: cost calculator

Unit prices are editable example values (USD/hour); update them with the actual canadacentral prices from the pricing calculator. Drag “study hours” and pick a cleanup method to see the cumulative cost over 7 days.

VM unit price · Disk · Public IP · Bastion
Number of VMs 1 · Study time per day 2 hours

Core commands

Command / modulePurposeNotes
azure_rm_resourcegroup_info + tagsFind RGs by tagtags: ['env:lab', 'owner:andy']
azure_rm_resourcegroup state: absent force_delete_nonempty: trueDelete a non-empty RGNot recoverable
az group delete -n rg-ansible-lab --yes --no-waitCLI deleteaz group wait --deleted -n … Wait for completion
az keyvault list-deleted / purgeHandle soft-deleted vaultsCan’t purge while purge protection is enabled
az disk list --query "[?managedBy==null]"Find orphaned disksUnattached disks are still billed
az consumption budget createBudget alertscan also be set in the portal under Cost Management

teardown.yml

- name: Tear down lab resources (DESTRUCTIVE)
  hosts: localhost
  connection: local
  gather_facts: false
  vars_files: [vars/lab.yml]
  module_defaults:
    group/azure.azcollection.all:
      auth_source: "{{ az_auth }}"
  vars:
    confirm: "{{ undef(hint='Add -e confirm=yes to actually delete') }}"
  tasks:
    - name: Safety check
      ansible.builtin.assert:
        that: confirm == 'yes'
        fail_msg: "Refusing to delete without -e confirm=yes"

    - name: Find lab resource groups by tags
      azure.azcollection.azure_rm_resourcegroup_info:
        tags:
          - "env:lab"
          - "owner:{{ owner }}"
      register: rgs

    - name: Find Key Vaults in those RGs (to purge later)
      azure.azcollection.azure_rm_keyvault_info:
        resource_group: "{{ item.name }}"
      loop: "{{ rgs.resourcegroups }}"
      loop_control: { label: "{{ item.name }}" }
      register: kvs

    - name: Show what will be deleted
      ansible.builtin.debug:
        msg:
          resource_groups: "{{ rgs.resourcegroups | map(attribute='name') | list }}"
          key_vaults: "{{ kvs.results | map(attribute='keyvaults') | flatten | map(attribute='name') | list }}"

    - name: Delete resource groups (all resources inside)
      azure.azcollection.azure_rm_resourcegroup:
        name: "{{ item.name }}"
        state: absent
        force_delete_nonempty: true
      loop: "{{ rgs.resourcegroups }}"
      loop_control: { label: "{{ item.name }}" }

    - name: Purge soft-deleted Key Vaults (frees the global name)
      ansible.builtin.command: az keyvault purge --name {{ item }}
      loop: "{{ kvs.results | map(attribute='keyvaults') | flatten | map(attribute='name') | list }}"
      register: purge
      changed_when: purge.rc == 0
      failed_when: false

    - name: Remove local inventory cache
      ansible.builtin.file:
        path: ~/.cache/ansible-azure-inventory
        state: absent

azure_rm_keyvault_info Returns keyvaults the list (verified against the 4.2.0 source),azure_rm_resourcegroup_info of tags accepts 'key' or 'key:value'. Deleting a resource group may take 5–10 minutes, and the module waits for it to finish. If a rebuilt VM reuses a public IP, clear its host key manually with ssh-keygen -R <IP>.

cd ~/ansible-lab/azure
ansible-playbook -i inventory/ playbooks/teardown.yml               # without confirm → refuses to run
ansible-playbook -i inventory/ playbooks/teardown.yml -e confirm=yes
TASK [Show what will be deleted] ************************************************
ok: [localhost] =>
    msg:
        key_vaults:
        - kv-ansible-ab12cd
        resource_groups:
        - rg-ansible-lab
TASK [Delete resource groups (all resources inside)] ****************************
changed: [localhost] => (item=rg-ansible-lab)
TASK [Purge soft-deleted Key Vaults (frees the global name)] ********************
changed: [localhost] => (item=kv-ansible-ab12cd)
PLAY RECAP **********************************************************************
localhost : ok=7  changed=3  unreachable=0  failed=0  ...

CLI-equivalent cleanup and verification

az group delete -n rg-ansible-lab --yes --no-wait
az group wait --deleted -n rg-ansible-lab
az keyvault list-deleted --query "[].name" -o tsv | xargs -r -n1 az keyvault purge --name
az ad sp delete --id <appId of sp-ansible-lab>
shred -u ~/.azure/credentials 2>/dev/null; unset AZURE_CLIENT_ID AZURE_SECRET AZURE_TENANT AZURE_SUBSCRIPTION_ID
# verify
az group exists -n rg-ansible-lab
az resource list --tag env=lab --query "length(@)"
az disk list --query "[?managedBy==null].name" -o tsv
az network public-ip list --query "[?ipConfiguration==null].name" -o tsv
false
0

Budget alerts (recommended before you start)

az consumption budget create --budget-name lab-monthly --amount 20 --category cost \
  --time-grain monthly --start-date $(date +%Y-%m-01) --end-date $(date -d '+1 year' +%Y-%m-01)

Setting budget notifications (email thresholds) in the CLI is cumbersome; it’s recommended to add 50%/80%/100% alerts in the portal under “Cost Management → Budgets”. az consumption For the command group’s parameters, refer to az consumption budget create -h .

Lab 8: clean up and verify zero leftovers (about 6 minutes)

First, take inventory:
az resource list -g rg-ansible-lab --query "[].{type:type,name:name}" -o table
az keyvault list -g rg-ansible-lab --query "[].name" -o tsv
(Optional) Try deallocation:
az vm deallocate -g rg-ansible-lab -n vm-myapp-01
az vm get-instance-view -g rg-ansible-lab -n vm-myapp-01 --query "instanceView.statuses[?starts_with(code,'PowerState')].displayStatus" -o tsv
az network public-ip show -g rg-ansible-lab -n pip-myapp-01 --query ipAddress -o tsv   # Static IP is kept (still billed)
VM deallocated
20.151.12.34
Run teardown: save the script from the “Commands” tab as teardown.yml, then run ansible-playbook -i inventory/ playbooks/teardown.yml -e confirm=yes.
Handle identities and local leftovers: delete the service principal created in M1; delete ~/.azure/credentials; unset the environment variables.
Verify: run the verification commands on the “Commands” tab; az group exists should be false, and the number of resources with env=lab tags should be 0; the dynamic inventory ansible-inventory -i inventory/ --graph --flush-cache should show only @ungrouped.
(Optional) Rebuild drill: ansible-playbook -i inventory/ playbooks/all-in-one.yml -e my_ip=$MY_IP, time it: from zero to /healthz ok usually takes 5–8 minutes. Run teardown again after the drill.

Case 1: nightly automatic cleanup of a sandbox subscription

Problem: Engineers often forget to delete lab resources. Approach: Enforce tags owner,ttl (Azure Policy “Require a tag on resource groups”); every night, a scheduled AWX job runs a teardown-like playbook that queries ttl for RGs that have expired, sends a notice first, and deletes them the next day. Limitation: Deletion is irreversible; be sure to allowlist and protect shared RGs, and enable resource locks.

Case 2: orphaned disks cost thousands of dollars a year

Problem: Over the years, disks were not deleted when VMs were deleted. Approach: Weekly report of managedBy == null disks and unattached public IPs; after confirmation, delete them; new code uniformly sets deleteOption: Delete or remove_on_absent: all. Limitation: Some unattached disks are deliberately kept backups — use the keep=true tag to mark them.

Case 3: cost allocation

Problem: Finance requires costs to be split by application and team. Approach: In the shared variables of Ansible/Terraform, standardize common_tags (app, env, owner, costCenter), group by tag in Cost Management; resource-group-level tags can be inherited by resources through Policy. Limitation: Tag-based cost allocation has limits for some charges (such as outbound traffic); refer to the Cost Management docs.

Common errors and fixes

(ScopeLocked) The scope '/subscriptions/…/resourceGroups/rg-ansible-lab' cannot perform delete operation because following scope(s) are locked
az lock list -g rg-ansible-lab -o table
az lock delete -g rg-ansible-lab -n <lockName>

Confirm the lock was added by you (for example, the CanNotDelete lock from the M3 production case) before deleting it.

The resource group has been in Deleting state for a long time

Cause: Bastion, VNets and similar resources are slow to delete; or a resource is referenced by an object in another resource group (such as a peering or a private endpoint).

az group show -n rg-ansible-lab --query properties.provisioningState
az monitor activity-log list -g rg-ansible-lab --offset 1h --status Failed -o table
Vault name is already in use / Key Vault cannot be purged: Operation “purge” is not allowed because purge protection is enabled

Cause: Purge protection is enabled, so you must wait until the retention period ends.

Fix: Use a new name; don’t enable purge protection on lab vaults.

The bill still shows public IP / disk charges, but the VM has been deleted
az disk list --query "[?managedBy==null].{name:name,rg:resourceGroup}" -o table
az network public-ip list --query "[?ipConfiguration==null].{name:name,rg:resourceGroup}" -o table

Delete these orphaned resources, and check the remove_on_absent/deleteOption.

Command-line exercises
1. Use one command to delete rg-ansible-lab without waiting, then use another command to wait until it is actually deleted.
az group delete -n rg-ansible-lab --yes --no-wait
az group wait --deleted -n rg-ansible-lab
2. List all unattached managed disks in the subscription.
az disk list --query "[?managedBy==null].{name:name,rg:resourceGroup,sizeGb:diskSizeGb}" -o table
Scenario analysis
On Friday night you ran sudo shutdown -h now, and on Monday you saw the bill still growing, and the Key Vault creation failed when you rebuilt the lab the next day. Explain both symptoms and give the correct weekend procedure.

① After the OS shuts down, the VM is in the Stopped state (not deallocated); compute resources are still reserved and billed as compute, and the disk and Standard public IP are billed the whole time. ② If you delete the resource group over the weekend, Key Vault enters soft-delete state and the name stays reserved, so rebuilding a vault with the same name will conflict. Correct procedure: on Friday, run teardown.yml -e confirm=yes (delete RG + purge Key Vault), or at least az vm deallocate; on Monday, use all-in-one.yml to rebuild; also set budget alerts and an auto-shutdown schedule for the VM.

Self-check list for this lesson

Verified teaching videos

No verified video specifically on “Azure VM stop vs. deallocate billing + Ansible cleanup” was found.

Official docs

Video storyboard script (about 70 seconds)

This courseware cannot directly generate video or MP3, so a storyboard and narration script are provided for a video tool to produce.

Shot 1 · 0–20s
Visual: three meters: compute, disk, public IP. When the VM is shut down, only the compute meter is still running; after deallocation, the compute meter stops.
Narration: shutting down is not the same as stopping charges; only deallocation stops compute charges, and disks and public IPs are billed until they are deleted.
Shot 2 · 20–45s
Visual: a resource group box is tossed whole into the recycle bin, but the Key Vault pokes its head out of the bin.
Narration: deleting the resource group is the cleanest, but Key Vault has soft delete and needs a purge to free the name.
Shot 3 · 45–70s
Visual: the terminal runs teardown and verification commands, and the count drops to zero.
Narration: finally verify there are zero leftovers, and delete the service principal and local credentials. Tomorrow, one command rebuilds everything.
or score ≥ 70% on the quiz

Command cheat sheet

Common Ansible + Azure commands, config snippets, and quick troubleshooting
azure.azcollection 4.2.0ansible-core 2.21

1 · Installation and dependencies

pipx install --include-deps ansible
ansible-galaxy collection install azure.azcollection --upgrade
pipx inject ansible -r ~/.ansible/collections/ansible_collections/azure/azcollection/requirements.txt
ansible-galaxy collection list azure.azcollection
pipx runpip ansible list | grep ^azure-

2 · Authentication

az login; az account set -s <SUB>
export ANSIBLE_AZURE_AUTH_SOURCE=cli     # auto|cli|env|credential_file|msi
# env: AZURE_SUBSCRIPTION_ID AZURE_CLIENT_ID AZURE_SECRET AZURE_TENANT
az ad sp create-for-rbac -n sp-ansible-lab --role Contributor \
  --scopes /subscriptions/$SUB/resourceGroups/rg-ansible-lab

3 · Dynamic inventory

ansible-inventory -i inventory/lab.azure_rm.yml --graph
ansible-inventory -i inventory/ --host vm-myapp-01
ansible-inventory -i inventory/ --graph --flush-cache
ansible tag_role_web -i inventory/ -m ping
ansible-inventory -i inventory/ --graph -vvvv 2>&1 | grep azure_rm

4 · Resource lifecycle

ansible-playbook playbooks/provision.yml -e my_ip=$MY_IP --check --diff
ansible-playbook playbooks/provision.yml -e my_ip=$MY_IP
az resource list -g rg-ansible-lab -o table
az vm deallocate -g rg-ansible-lab -n vm-myapp-01
ansible-playbook -i inventory/ playbooks/teardown.yml -e confirm=yes

5 · Configuration and deployment

ansible-playbook -i inventory/ playbooks/site-azure.yml
ansible-playbook -i inventory/ playbooks/site-azure.yml --limit vm-myapp-01 --diff
ansible-playbook -i inventory/ playbooks/all-in-one.yml -e my_ip=$MY_IP
curl -s http://$IP:8000/healthz

6 · Bastion tunnel

az network bastion create -g rg-ansible-lab -n bas-lab --vnet-name vnet-ansible \
  --public-ip-address pip-bastion --sku Standard --enable-tunneling true
az network bastion tunnel -g rg-ansible-lab -n bas-lab \
  --target-resource-id "$VMID" --resource-port 22 --port 2222
ansible-playbook ... -e ansible_host=127.0.0.1 -e ansible_port=2222

7 · Key Vault

az keyvault create -g rg-ansible-lab -n $KV --enable-rbac-authorization true
az role assignment create --assignee-object-id $ID --assignee-principal-type User \
  --role "Key Vault Secrets User" --scope $KVID
az keyvault secret set --vault-name $KV -n redis-password --value "..."
az keyvault list-deleted; az keyvault purge -n $KV

8 · Troubleshooting

az role assignment list --assignee <objectId> --all -o table
az network watcher test-ip-flow -g RG --vm VM --direction Inbound \
  --protocol TCP --local 10.30.1.4:22 --remote $MY_IP:50000
az vm run-command invoke -g RG -n VM --command-id RunShellScript --scripts "cloud-init status"
az provider register -n Microsoft.Compute --wait
ansible HOST -i inventory/ -m ping -vvv

Quick troubleshooting table

Symptom / error keywordMost likely causeFirst step
Failed to import the required Python librarySDK not installed in Ansible’s Pythonpipx inject ansible -r …/requirements.txt
Failed to get credentialsall four sources in the auto chain are emptyaz login or check AZURE_*
Unable to parse … as an inventory sourcefile name doesn’t end with azure_rm.ymlRename
provided hosts list is emptyRG name, filters, VM not running, permissions, cacheansible-inventory --graph --flush-cache
AuthorizationFailed (403)identity / action / scope mismatchread the 3 elements of the error,az role assignment list
ForbiddenByRbac (Key Vault)missing data plane roleassign Key Vault Secrets User
TooManyRequests (429)too many callscentralize on localhost, cache, lower forks
Connection timed out (22)NSG source IP, VM not runningtest-ip-flow,curl api.ipify.org
Permission denied (publickey)wrong username or private keyssh -v; az vm user update
Could not get lock /var/lib/dpkg/lock-frontendcloud-init still runningcloud-init status --wait

Recommended config snippets

plugin: azure.azcollection.azure_rm
auth_source: cli
include_vm_resource_groups: [rg-ansible-lab]
hostnames: [name, default]
exclude_host_filters:
  - tags.app | default('') != 'myapp'
keyed_groups:
  - { prefix: tag, key: tags }
  - { prefix: azure_loc, key: location }
hostvar_expressions:
  ansible_host: (public_ipv4_address + private_ipv4_addresses) | first
module_defaults:
  group/azure.azcollection.all:
    auth_source: cli
# secrets (laptop)
myapp_redis_password: "{{ lookup('azure.azcollection.azure_keyvault_secret',
   'redis-password', vault_url=kv_url, use_msi=false, auth_source='cli') }}"
# boot phase
- ansible.builtin.wait_for_connection: { timeout: 300 }
- ansible.builtin.command: cloud-init status --wait
  changed_when: false

Capstone lab + final quiz

Create an Azure VM from scratch with Ansible → dynamic inventory discovery → deploy myapp (secrets from Key Vault) → verify → clean up
After class ≈ 40 minutesSmall cost incurred
Scenario Your team needs an Azure demo environment for myapp, with these requirements: ① everything created from code, so it can be deleted and rebuilt at any time; ② VMs don’t use password login, and management ports are open only to your IP; ③ hosts are selected by tag from the dynamic inventory, with no IPs in the playbook; ④ the Redis password is not in the repository and is fetched from Key Vault; ⑤ after the demo, no lab resources, identities or secrets remain in the subscription.
Cost / permissions / risks Expected to finish within 1 hour; cost is about 1 hour of one B2s VM + disk + public IP (example: under US$0.10; check the pricing calculator); Bastion is not included. Permissions: Contributor on the subscription or resource group, plus permission to assign roles on the vault. Risk: ports 22 and 8000 on the public IP are open only to your IP; be sure to run step 7 when finished.
Preparation (modules 0, 1)
cd ~/ansible-lab/azure
az login && az account show -o table
ansible-galaxy collection install azure.azcollection --upgrade
pipx inject ansible -r ~/.ansible/collections/ansible_collections/azure/azcollection/requirements.txt
export MY_IP=$(curl -s https://api.ipify.org)
ansible localhost -m azure.azcollection.azure_rm_resourcegroup_info -a "auth_source=cli" | head -3
Create infrastructure (module 3): run provision.yml twice; the second run must show changed=0.
ansible-playbook playbooks/provision.yml -e my_ip=$MY_IP
ansible-playbook playbooks/provision.yml -e my_ip=$MY_IP | tail -2
Dynamic inventory (module 2):
ansible-inventory -i inventory/ --graph tag_role_web --flush-cache
ansible-inventory -i inventory/ --host vm-myapp-01 | grep -E '"(ansible_host|powerstate)"'
@tag_role_web:
  |--vm-myapp-01
    "ansible_host": "20.151.12.34",
    "powerstate": "running",
Key Vault (module 5): create the vault (RBAC), grant yourself Secrets Officer, write redis-password, and in inventory/group_vars/tag_app_myapp.yml define kv_url the lookup.
Deploy myapp (module 4):
ansible-playbook -i inventory/ playbooks/site-azure.yml
IP=$(ansible-inventory -i inventory/ --host vm-myapp-01 | python3 -c 'import json,sys;print(json.load(sys.stdin)["ansible_host"])')
curl -s http://$IP:8000/; curl -s http://$IP:8000/; curl -s http://$IP:8000/healthz
Hello from vm-myapp-01! visits=1
Hello from vm-myapp-01! visits=2
ok
Security verification (modules 4, 7):
ssh -o PasswordAuthentication=yes -o PubkeyAuthentication=no azureuser@$IP true   # should fail: Permission denied (publickey)
az network nsg rule list -g rg-ansible-lab --nsg-name nsg-app --query "[].{n:name,src:sourceAddressPrefix,port:destinationPortRange}" -o table
grep -rn "redis" playbooks inventory | grep -vi "lookup\|kv_url\|redis-server\|redis-password"   # should not show any plaintext password
Cleanup (module 8):
ansible-playbook -i inventory/ playbooks/teardown.yml -e confirm=yes
az ad sp delete --id <appId of sp-ansible-lab> 2>/dev/null || true
az group exists -n rg-ansible-lab
az resource list --tag owner=$USER --query "length(@)"
az keyvault list-deleted --query "[].name" -o tsv
false
0
Acceptance checklist

Open-ended self-check (answer on your own first, then expand the reference answer)

1. Why must the Python SDK required by the azure_rm_* modules be installed on the control node rather than on the VM?

These modules call the Azure ARM REST API, and are typically run with hosts: localhost,connection: local on the control node, executed by Ansible’s own Python interpreter, so the SDK must be installed in that interpreter’s environment (pipx inject). The VM only needs plain Python 3 to run modules such as apt and template.

2. Describe the full process of the azure_rm inventory plugin from startup to generating the tag_role_web group.

validate the file name → authenticate and get a token → list VMs by include_vm_resource_groups (Compute API, paginated) → evaluate filters that depend only on list fields early → use ARM /batch to fetch instanceView, NICs and public IPs in bulk → build hostvars (powerstate, IP, tags…; by default ansible_host prefers the public IP) → default_host_filters and custom filters → hostnames naming → compose/hostvar_expressions → conditional_groups and keyed_groups (each key-value pair in the tags dictionary generates a tag_key_value group).

3. Why is lookup of Key Vault slow or does it report a managed identity error on a laptop?

The lookup plugin defaults to use_msi: true, so it first requests IMDS (169.254.169.254), which is unreachable on a laptop, and must wait for that to fail before falling back to auth_source. Set use_msi=false, auth_source='cli'.

4. When you delete a VM with Ansible, which associated resources are deleted by default? How do you keep a static public IP?

remove_on_absent By default, ['all']: managed disks, NICs, and the public IP on the NIC. To keep the public IP: remove_on_absent: [network_interfaces, virtual_storage], and you can add a CanNotDelete lock to the public IP.

5. How would you explain the division of work between Ansible and Terraform/Bicep to your team?

Terraform/Bicep manage cloud resources (dependency graph, plan/what-if, deletion semantics, state), and Ansible manages configuration and releases inside machines (idempotent modules, roles, rolling orchestration). The handoff point is tags/outputs: the infrastructure applies a role tag, and the Ansible dynamic inventory selects hosts by tag. Each resource has only one owner; avoid calling Ansible from local-exec and having two tools manage the same resource.

6. The playbook reports 403 in CI; list your troubleshooting order.

Read the object id, action, and scope in the error: confirm the actual identity (the auto chain may have picked other credentials) → confirm the role assignment exists and its scope covers this scope → determine whether it is a data plane (Key Vault) permission → check whether it is RequestDisallowedByPolicy → check whether the role was just assigned and hasn’t propagated (wait / re-acquire the token).

Final quiz (12 questions, covering all modules)

Sources and version notes

Verification basis for all technical facts in this lesson (verified 2026-11-15)
TopicVerified findingSource (accessed 2026-11-15)
ansible-core / community packagecore 2.21 (GA 2026-05, EOL 2027-11); control node Python 3.12–3.14, managed nodes 3.9–3.14; community package 14.x is based on core 2.21course spec section 3;Release and maintenance
azure.azcollection versionGalaxy latest version 4.2.0 (CHANGELOG: 2026-10-30); 4.1.0 (2026-09-29); 4.0.0 (2026-08-31); requires_ansible: '>=2.16.0'; README requires Python ≥ 3.10Galaxy · CHANGELOG · meta/runtime.yml
4.0.0 breaking changeslookup plugins removed use_cli; azure_rm_virtualmachine removes the unmanaged disk parameters; the MariaDB and MySQL/PostgreSQL Single Server modules, etc., are removedCHANGELOG v4.0.0
Python dependenciescollection root directory requirements.txt (the old name requirements-azure.txt no longer exists); 4.2.0 pins azure-identity 1.25.2, azure-mgmt-compute 33.0.0, azure-cli-core 2.91.0, etc.; the docs advise not to pip-install azure-cli into the same environmentrequirements.txt · doc_fragments/azure.py
Authentication orderauto: module parameters → env → credential_file → cli; msi must be explicit; env variable names AZURE_SECRET and AZURE_TENANT (falls back to AZURE_TENANT_ID); OIDC: AZURE_FEDERATED_TOKEN(_FILE); credentials file ~/.azure/credentialsazure_rm_common.py(_get_credentials, AZURE_CREDENTIAL_ENV_MAPPING)
azure_rm inventory pluginthe file name must end with azure_rm.yml/yaml; options and hostvars list; VM list API 2024-07-01; bulk fetch uses ARM /batch (api-version 2015-11-01); filters are evaluated early from 4.2.0; hostvars include virtual_machine_size, resource_group, etc.plugin docs (3.21.0 page) · azure_rm.py source code
resource module parametersazure_rm_virtualmachine (remove_on_absent defaults to all: disks + NICs + public IPs; allocated/started; vm_identity); networkinterface (create_with_security_group defaults to true); securitygroup (purge_rules); publicipaddress (sku standard; basic retired 2025-09-30); subnet (address_prefix_cidr, security_group)module docs and module source code
Key Vault lookup pluginname azure.azcollection.azure_keyvault_secret; terms are the secret name (may include /version); vault_url is required; use_msi defaults to true (requests IMDS first, then uses auth_source); there is no secret_name keywordlookup docs · source code
Azure BastionThe native client (az network bastion ssh/tunnel) requires the Standard or higher SKU with native client enabled; required role: Reader on the VM, NIC and BastionConnect to a VM using Bastion - Linux native client
cloud.terraform collectionmodules terraform, terraform_output, plan_stash; inventory plugins terraform_provider, terraform_stateGitHub
Key Vault RBAC / soft delete, ARM throttling, VM billing statesConceptual notes; for exact values, refer to the official docsRBAC guide · Soft delete · ARM throttling · VM states and billing

Video verification notes

The following videos were verified for title and channel via the YouTube oEmbed endpoint (2026-11-15): Red Hat, “Ansible to automate Microsoft Azure” (eRLsGq_Veyk); Fireship, “Ansible in 100 Seconds” (xRMPKQweySE) and “Terraform in 100 Seconds” (tomUWcQ0P3k); TechWorld with Nana, “What is Ansible | Ansible Playbook explained | Ansible Tutorial for Beginners” (1id6ERvfozo) and “Terraform explained in 15 mins | Terraform Tutorial for Beginners” (l5k1ai_GBDE); Techno Tim, “Automate EVERYTHING with Ansible! (Ansible for Beginners)” (w9eCU4bGgjQ). oEmbed does not return durations or publish dates, so the cards do not list specific durations (“about 2 minutes” is the typical length of the 100 Seconds series). No verified dedicated videos were found for the azure_rm dynamic inventory 4.x, the Key Vault lookup plugin, Bastion + Ansible, cloud troubleshooting, or cost cleanup, so storyboard scripts are provided instead. All videos are in English and predate azure.azcollection 4.x; for parameters, follow this lesson and the official docs.

Audio narration notes

The “Audio” tab uses the browser’s Web Speech API (speechSynthesis, en-US) reads the narration script aloud in real time, with English terms pronounced in en-US. Results depend on the voices installed on the operating system. The environment that generated this courseware cannot call a TTS service, so no MP3 is embedded; for offline audio, hand the narration script to a TTS service such as Azure AI Speech.

Known limitations

  • The lab commands in this courseware have not been run in a real Azure subscription; the subscription IDs, object IDs, IPs, hashes, times and counts in the “Expected output” sections are example values; your environment is authoritative.
  • The cost figures are examples; unit prices vary by region, currency and time, so use the Azure Pricing Calculator as the reference.
  • The docs.ansible.com plugin page for azure.azcollection showed version 3.21.0 at the time of verification; for 4.x behavior, follow the GitHub source and CHANGELOG; for check mode support of some modules, follow the attributes in each module’s documentation.
  • Azure CLI error text changes with CLI/extension versions; entries labeled “symptom” on the troubleshooting tab are not verbatim error messages. Specific ARM throttling numbers are not included in the courseware; please refer to the official docs.
  • The myapp role from lessons 1–2 had not been finalized when this lesson was written, so this lesson provides a minimal compatible version in module 0 (port 8000, variable myapp_redis_password); if your role variable names differ, adjust group_vars accordingly.
  • The timing and request order in the animations are illustrative, used to explain the mechanism (based on reading the 4.2.0 source code); they are not exact network captures.