Ansible Hour 3: Moving to the Cloud Platform (Azure)
- 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 knowauth_sourcehow to force a specific one. - Write a
azure_rm.yml-ending dynamic inventory file, usingkeyed_groups,conditional_groups,hostvar_expressions, filters and caching, to group Azure VMs automatically intotag_role_webgroups like this. - Use
azure_rm_resourcegroup/azure_rm_virtualnetwork/azure_rm_subnet/azure_rm_securitygroup/azure_rm_publicipaddress/azure_rm_networkinterface/azure_rm_virtualmachinein an idempotent manner to create one Azure VM, and usestate: absentto 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_secretThe 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
| # | Time | Module | Core Content | Animation / Interaction | Lab (Azure, rg-ansible-lab) |
|---|---|---|---|---|---|
| 0 | Before Class | Warm-up & Azure Preparation | Subscription, permissions, quotas, cost estimate, control node check, myapp role in place | Environment self-check list | az login,ansible --version |
| 1 | 00–06 | azure.azcollection and Authentication | Install the collection and Python dependencies, pipx inject, the 5 credential sources and auth_source, OIDC | Credential resolution order simulator | azure_rm_resourcegroup_info Smoke test |
| 2 | 06–13 | Dynamic Inventory azure_rm | *.azure_rm.yml Naming, keyed_groups, conditional_groups, hostvar_expressions, filters, caching | Core animation: the full dynamic inventory generation process | ansible-inventory --graph |
| 3 | 13–22 | Creating Azure Resources with Ansible | RG → VNet → Subnet → NSG → PIP → NIC → VM, idempotency, check mode,state: absent | Resource dependency chain and idempotency demo | provision.yml Run twice |
| 4 | 22–30 | Configuring Azure VMs and Deploying Applications | Reuse the myapp role, SSH keys, NSG source IP restriction,wait_for_connection, Bastion tunnel | Connection path comparison (public SSH vs Bastion) | site-azure.yml + /healthz |
| 5 | 30–37 | Secrets: Key Vault and Managed Identity | Lookup plugin parameters, getting secrets from control node vs managed node, RBAC roles, no_log | Secret retrieval timing | Put the Redis password into Key Vault |
| 6 | 37–44 | Division of Work: Ansible vs Terraform/Bicep | Orchestration vs configuration, four combination patterns, anti-patterns, hand-off points (outputs → tags → dynamic inventory) | Tool selection decision guide | Bicep builds the VM + Ansible configures |
| 7 | 44–53 | Troubleshooting in the Cloud | Authentication failures, missing dependencies, empty inventory, SSH timeouts, 403, 429 throttling | Interactive troubleshooting tree | Deliberately cause four faults and fix them |
| 8 | 53–60 | Cost, Cleanup and Self-Test | Billable items, stop vs deallocate, tag-driven cleanup, budget alerts, orphaned resources | Cost calculator | teardown.yml + verify 0 resources |
| — | After Class | Cheat sheet · Capstone Lab | From zero: create an Azure VM → dynamic inventory → deploy myapp → Key Vault → cleanup | Final quiz (12 questions) | Capstone Lab |
Knowledge Coverage Matrix
| Target skills | M1 | M2 | M3 | M4 | M5 | M6 | M7 | M8 | Key commands / modules | Lab |
|---|---|---|---|---|---|---|---|---|---|---|
| Install collection and SDK dependencies | ✓ | · | · | · | · | · | ✓ | · | ansible-galaxy collection install,pipx inject | M1 Lab |
| Azure Authentication and Least Privilege | ✓ | ✓ | · | · | ✓ | · | ✓ | · | auth_source,az ad sp create-for-rbac | SP + environment variables |
| Dynamic inventory and grouping | · | ✓ | · | ✓ | · | ✓ | ✓ | · | ansible-inventory --graph | lab.azure_rm.yml |
| Create cloud resources as code (idempotent) | · | · | ✓ | · | · | ✓ | · | ✓ | azure_rm_virtualmachine etc. | provision.yml |
| Secure VM access (SSH / NSG / Bastion) | · | · | ✓ | ✓ | · | · | ✓ | · | az network bastion tunnel | NSG 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 create | Bicep + Ansible |
| Cloud fault diagnosis | ✓ | ✓ | ✓ | ✓ | ✓ | · | ✓ | · | -vvv,ANSIBLE_DEBUG,az role assignment list | Fault injection |
| Cost control and cleanup | · | · | ✓ | · | · | · | · | ✓ | az group delete,state: absent | teardown.yml |
Topics not covered in this lesson (and where to learn them)
| Topic | Why not in this lesson | Where to learn |
|---|---|---|
| AWS EC2, SSM connection plugin (no need to open SSH) | Belongs to AWS topics | Lesson 4 |
| GitHub Actions + OIDC federated credentials, AWX / AAP, Event-Driven Ansible | Belongs to automation pipelines | Lesson 5 (M1 of this lesson only introduces oidc_token the parameter exists) |
| Multi-tier architecture (nginx LB + 2 app nodes + PostgreSQL), VMSS rolling configuration | Beyond 1 hour | Lesson 6 |
| Windows VMs (WinRM / OpenSSH for Windows), Azure Arc hybrid machines | require different connection methods | Ansible Windows Guide; the dynamic inventory's include_arc_resource_groups options: see the official plugin docs |
| Ansible management of AKS and Container Apps | Container platforms are usually managed by Terraform/Bicep + GitOps | K8s lesson; azure_rm_aks,azure_rm_containerapp Module docs |
| Terraform details for building Azure infrastructure | This lesson's M6 covers only the division of work | Terraform Lesson 3 |
How to use this courseware
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.
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).
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.
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.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)
- CompletedLesson 1andLesson 2: the control node has the project directory
~/ansible-lab, which containsansible.cfgand myapp role (roles/myapp: installs a Python venv and a gunicorn systemd service listening8000, depends on the localredis-server, provides/healthz). - Control node: Ubuntu 24.04 LTS (local machine, WSL2 or a small VM), Python 3.12, with
pipx install --include-deps ansibleinstalled 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
| Name | Value | Source / Purpose |
|---|---|---|
| Project directory | ~/ansible-lab | Lessons 1–2; this lesson adds subdirectories azure/ |
| Application role | roles/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 group | rg-ansible-lab | Created in this lesson, fully deleted at the end |
| Region | canadacentral | Same as the Docker lesson |
| VM | vm-myapp-01,Standard_B2s, Ubuntu 24.04 (Canonical:ubuntu-24_04-lts:server:latest) | Created in M3 |
| Tags | env=lab,app=myapp,role=web,owner=<your name> | M2 dynamic inventory groups by tag; M8 cleans up by tag |
| Administrator user | azureuser + ~/.ssh/id_ed25519 | M4 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}
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.
Module 1 · azure.azcollection and Authentication
- Use
ansible-galaxyto install/upgrade the collection, and install the collection directory'srequirements.txtinto the same Python environment that runs Ansible (with pipx, usepipx 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 explicitlyauth_source: msi. - Create a least-privilege service principal for automation and provide it to Ansible via environment variables or a credentials file.
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
| Step | Command | Key points |
|---|---|---|
| 1 Install/upgrade collection | ansible-galaxy collection install azure.azcollection --upgrade | install to ~/.ansible/collections, takes precedence over the older version bundled with the community package (collections_path order) |
| 2 Install SDK | pipx inject ansible -r ~/.ansible/collections/ansible_collections/azure/azcollection/requirements.txt | With a pip virtual environment, use venv/bin/pip install -r … |
| 3 Choose credentials | auth_source parameters or ANSIBLE_AZURE_AUTH_SOURCE environment variables | auto (default) / cli / env / credential_file / msi |
5 credential sources
| Source | How to provide | Suitable for | Notes |
|---|---|---|---|
Azure CLI (cli) | first az login, reuses the CLI token cache | personal laptop, interactive labs | az 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_id | CI, AWX, shared automation accounts | keys 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_ID | injected by CI pipelines | note 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_id | AWX / self-hosted runners running inside Azure | not 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 leftoverAZURE_*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.azcollection | Terraform azurerm provider | Azure CLI / Bicep | |
|---|---|---|---|
| Dependencies | Control node Python + SDK (requirements.txt) | Single provider binary (Go) | az CLI |
| Credential chain | auto: parameters → env → credentials file → CLI; MSI must be set explicitly | provider block / ARM_* environment variables / CLI / MSI / OIDC | az login any of the methods |
| State | Stateless; queries Azure's actual state on each run | state file | ARM deployment history (no local state) |
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
Flowchart: auth_source decision
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.
Core commands and parameters
| Command | Purpose | Key parameters / notes |
|---|---|---|
ansible-galaxy collection install azure.azcollection | Install collection | --upgrade upgrade to latest; azure.azcollection:==4.2.0 pin version; -r requirements.yml |
ansible-galaxy collection list azure.azcollection | View versions across all paths | shows both the community package's bundled version and the user-directory version; the one listed first takes effect |
pipx inject ansible -r …/requirements.txt | Install SDK into the pipx ansible environment | re-run once after upgrading the collection |
az ad sp create-for-rbac | Create service principal and assign role | --role Contributor --scopes /subscriptions/…/resourceGroups/rg-ansible-lab |
ansible localhost -m azure.azcollection.azure_rm_resourcegroup_info | Authentication smoke test | -a "auth_source=cli"; -vvv View details |
ANSIBLE_AZURE_AUTH_SOURCE=cli | Specify credential source globally | applies 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)
azure.azcollection 4.2.0 takes effect.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.
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.
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.~/.azure/credentials then run -e az_auth=credential_file. Delete after the lab: shred -u ~/.azure/credentials.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'.
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
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
Official docs
- ansible-collections/azure (README installation instructions)
- CHANGELOG (4.0.0 breaking changes)
- azure.azcollection documentation index
- Microsoft Learn: Ansible on Azure
Video storyboard script (about 75 seconds)
This courseware cannot generate video/MP3 directly; storyboards and narration scripts are provided for a video tool.
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.
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.
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.
Visual: service principal card; the scope arrow points only at rg-ansible-lab.
Narration: the automation identity is granted only resource-group-level permissions.
Module 2 · Dynamic inventory azure_rm
- 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 / --listto verify, enable caching and know when to refresh (--flush-cache).
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 stagehosts: tag_role_webselects them automatically — this is the “hand-off point” covered in M6.
How: what the plugin does internally (4.2.0 source)
- Parse configuration and authenticate: read
auth_sourceand other options, and obtain an Entra ID token (same credential chain as M1). - List VMs: for each
include_vm_resource_groupsissueGET /subscriptions/{sub}/resourceGroups/{rg}/providers/Microsoft.Compute/virtualMachines('*'when a subscription-level list is used), paging bynextLinkpages. - Pre-filter: since 4.2.0, only fields from the VM list (such as
name,tags,location) of theexclude_host_filters/include_host_filtersare evaluated before fetching details, so excluded VMs trigger no follow-up requests (pre-filtering does not apply when cache is enabled). - Batch-fetch details: for each remaining VM, request
…/instanceView(power state), NICs and public IPs. By defaultbatch_fetch: true, the plugin bundles these GETs and sends them through ARM'sPOST /batch?api-version=2015-11-01in one batch (source comment: up to 500 requests per batch), greatly reducing round trips. - Generate hostvars:
name,id,location,tags,powerstate,provisioning_state,public_ipv4_address,public_dns_hostnames,private_ipv4_addresses,os_profile,vmid,availability_zoneetc.; by defaultansible_host= the first public IP; if none, the first private IP. - Filter:
default_host_filtersBy default, excludes not-running VMs (powerstate != 'running') and VMs that are not fully provisioned; then applies your exclude/include filters. - Naming and grouping: by
hostnamesdeterminesinventory_hostname; executehostvar_expressions/compose; thenconditional_groups/groups(added when the expression is true) andkeyed_groups(generates groups from variable values).
keyed_groups naming rules
| configuration | hostvar value | generated 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} | canadacentral | azure_loc_canadacentral |
{prefix: role, key: tags.role | default('none')} | web / missing | role_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 reasonablecache_timeout. - Name collision: the default
inventory_hostnameis “VM name + underscore + short hash” to guarantee uniqueness; within a single resource group you can usehostnames: [name]to get more readable names.
Comparison with similar technologies
| Static INI/YAML | azure_rm plugin | azure_kql plugin | Terraform output generates inventory | |
|---|---|---|---|---|
| Data source | Hand-written | ARM Compute/Network API | Azure Resource Graph (KQL query) | state output |
| Real-time | Manual maintenance | Query each run (cacheable) | Resource Graph has a short indexing delay | Reflects only the last apply |
| Suitable for | Local experiments | Most scenarios | Large-scale queries across many subscriptions | One-time bootstrap |
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
Diagram: how tags become groups
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.
Core commands and parameters
| Command / option | Purpose | Key parameters / notes |
|---|---|---|
ansible-inventory -i lab.azure_rm.yml --graph | Show groups and hosts as a tree | --vars Show variables as well |
ansible-inventory --host NAME | View all hostvars of a single host | Debug keyed_groups key expressions |
ansible-inventory --list --yaml | Output the full inventory | --output file |
--flush-cache | Ignore and refresh the inventory cache | Use right after creating a VM |
ansible tag_role_web -m ping | Run ad-hoc against a dynamic group | Group names are case-sensitive |
-vvvv | View 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)
lab.azure_rm.yml save to ~/ansible-lab/azure/inventory/, first change cache: true to false (avoid cache interference during the lab).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.
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.
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.
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
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).
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.
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
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
- azure.azcollection.azure_rm inventory plugin
- Working with dynamic inventory
- Microsoft Learn: Configure dynamic inventories of your Azure resources using Ansible
- constructed (keyed_groups semantics)
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.
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.
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.
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.
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.
Module 3 · Create Azure resources with Ansible
- 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 --diffto preview. - Use
state: absentin reverse dependency order, delete resources, and understand the roles and risks ofremove_on_absentandforce_delete_nonempty.
What: resource modules and dependency chain
| Order | Module (azure.azcollection) | ARM resource type | Name in this lesson |
|---|---|---|---|
| 1 | azure_rm_resourcegroup | Microsoft.Resources/resourceGroups | rg-ansible-lab |
| 2 | azure_rm_virtualnetwork | Microsoft.Network/virtualNetworks | vnet-ansible (10.30.0.0/16) |
| 3 | azure_rm_securitygroup | Microsoft.Network/networkSecurityGroups | nsg-app (22 and 8000 allow only your IP) |
| 4 | azure_rm_subnet | …/virtualNetworks/subnets | snet-app (10.30.1.0/24, associated with nsg-app) |
| 5 | azure_rm_publicipaddress | Microsoft.Network/publicIPAddresses | pip-myapp-01 (Standard, Static) |
| 6 | azure_rm_networkinterface | Microsoft.Network/networkInterfaces | nic-myapp-01 |
| 7 | azure_rm_virtualmachine | Microsoft.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
- The module uses the SDK to send a
GETrequest to read the resource (if it does not exist, the SDK raisesResourceNotFoundError, i.e., HTTP 404). - If it does not exist and
state: present→ build the request body, send aPUT(begin_create_or_update), and poll the long-running operation (LRO:Azure-AsyncOperationheader) until Succeeded →changed: true. - If it exists → compare the desired parameters with the returned properties item by item (tags default to merge,
append_tags: falsereplaced when set) → PUT/PATCH only if there is a difference → otherwisechanged: false. --checkIn 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).state: absent→ if it exists, send aDELETEand wait for completion; if it does not exist, returnok.
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 azurerm | Bicep / ARM | |
|---|---|---|---|
| Execution order | In the order tasks are written (serial) | Dependency graph, automatic parallelism | ARM dependency graph (dependsOn/implicit) |
| Preview | --check --diff (module support varies) | terraform plan | what-if |
| Deletion | Requires writing a separate state: absent (reverse order) | terraform destroy | Deleting the resource group or --mode Complete/deployment stacks |
| Drift | Corrects managed properties on every run | plan detects | what-if detects |
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
Flowchart: creation order and deletion 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
| Module | Key parameters | Notes |
|---|---|---|
azure_rm_resourcegroup | name location tags state force_delete_nonempty | Deleting a non-empty RG requires force_delete_nonempty: true |
azure_rm_virtualnetwork | address_prefixes_cidr purge_address_prefixes | Manage subnets with a separate azure_rm_subnet, which is recommended |
azure_rm_securitygroup | rules[] (name/protocol/destination_port_range/source_address_prefix/access/priority/direction) purge_rules | priority 100–4096 and unique; purge_rules: true Delete rules not defined in code |
azure_rm_subnet | virtual_network_name address_prefix_cidr security_group default_outbound_access | Associate NSG with subnet |
azure_rm_publicipaddress | allocation_method: static sku: standard zones | Returns state.ip_address |
azure_rm_networkinterface | virtual_network subnet_name ip_configurations[] create_with_security_group | When the subnet already has an NSG, set create_with_security_group: false |
azure_rm_virtualmachine | vm_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_absent | Ubuntu 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)
rg-ansible-lab Contributor on the target scope. Risk: the public IP exposes ports 22 and 8000, but the NSG only allows your IP.vars/lab.yml and provision.yml save to ~/ansible-lab/azure/playbooks/.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.
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
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.”
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 ...
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.
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: falseA 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
No verified dedicated video was found on creating VNet/NSG/NIC/VM layer by layer with azure.azcollection 4.x.
Official docs
- azure_rm_virtualmachine
- azure_rm_networkinterface
- azure_rm_securitygroup
- azure_rm_subnet
- azure_rm_publicipaddress
- Microsoft Learn: Create a Linux virtual machine in Azure using Ansible
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.
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.
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.
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.
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.
Module 4 · Configure Azure VMs and deploy applications
- Write
site-azure.yml: a playbook that waits for SSH to be available and cloud-init to finish → appliesmyappthe role → verifies from the control node/healthz. - Handle host keys on first connection (
StrictHostKeyChecking=accept-new), and understand why it should not be disabled globallyhost_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 tunnelto set up local port forwarding. - In the same run, “create first, then configure”:
meta: refresh_inventoryoradd_host.
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
- The control node packages the module and parameters into an AnsiballZ script.
- Connect via OpenSSH
ansible_host:ansible_port(public IP:22, or 127.0.0.1:2222 through the Bastion tunnel), reusingControlPersistconnections; enablepipeliningwhen on, the script is sent via stdin; otherwise it is first copied via sftp to~/.ansible/tmp. become: trueWithsudoset, the task escalates privileges with sudo (Azure Linux VM admin users have passwordless sudo by default).- 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 restriction | Azure Bastion tunnel | |
|---|---|---|
| Does the VM need a public IP | Yes | No |
| NSG rules | Port 22 allows only MY_IP/32 | The default AllowVnetInBound is sufficient (Bastion sits in the same VNet's AzureBastionSubnet) |
| Authentication | SSH key | Entra ID (Azure RBAC: Reader on VM, NIC, and Bastion) + SSH key |
| Ansible configuration | ansible_host = public IP | first az network bastion tunnel … --port 2222,ansible_host=127.0.0.1 ansible_port=2222 |
| Multiple hosts | run in parallel directly | one tunnel/local port per VM (or an SSH ProxyCommand script) |
| Cost | Public IP hourly charge | Bastion Standard SKU (native client/tunneling requires Standard or higher) is billed hourly and is clearly more expensive |
| Best for | labs, personal use | production, 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 SSH | VM Run Command (az vm run-command) | Custom Script Extension | |
|---|---|---|---|
| Requires network reachability | Yes (SSH) | No, via Azure proxy | No, via Azure proxy |
| Idempotent / structured | Yes, modular | Script must ensure it itself | Script must ensure it itself |
| Best for | day-to-day configuration management | emergencies, troubleshooting when there is no network | first-boot bootstrap |
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
Flowchart: execution stages of site-azure.yml
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 / keyword | Purpose | Notes |
|---|---|---|
ansible.builtin.wait_for_connection | Wait for SSH + Python to be available | timeout: 300,delay,sleep |
cloud-init status --wait | Wait for the first-boot script to complete | Returns status: done |
ansible_ssh_common_args | Extra SSH parameters | -o StrictHostKeyChecking=accept-new |
ansible.builtin.meta: refresh_inventory | Re-run the inventory plugin in the playbook | Configure immediately after creating the VM |
az network bastion tunnel | local port → Bastion → VM port | --target-resource-id --resource-port 22 --port 2222 |
ansible-playbook --limit | Run 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)
inventory/group_vars/tag_env_lab.yml and playbooks/site-azure.yml from the “Commands” tab.cd ~/ansible-lab/azure ansible-inventory -i inventory/ --graph tag_role_web --flush-cache ansible tag_role_web -i inventory/ -m ansible.builtin.ping
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
changed=0 (only the cloud-init check command is marked changed_when: false changed, but no real change is made).curl -m 5 http://$IP:8000/, which should time out—only your IP can connect.-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
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.
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
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
No verified dedicated video on “Ansible + Azure Bastion tunnel” was found.
Official docs
- Bastion: Linux native client connection (az network bastion tunnel)
- Configure Bastion for native client connections
- wait_for_connection
- Connection methods and details
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.
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.
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.
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.
Module 5 · Secrets: the Key Vault lookup plugin and managed identities
- Use
lookup('azure.azcollection.azure_keyvault_secret', 'redis-password', vault_url=…)to read secrets at runtime, replacing the Ansible Vault–encryptedmyapp_redis_password. - Explain the lookup plugin's authentication behavior: by default
use_msi: true, try managed identity first, then followauth_source; on a laptop, you shoulduse_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_logto 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).
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.
| Parameters | Description (4.2.0 docs) |
|---|---|
| Positional argument terms | secret name; name/version can pin a version; omit it to get the latest |
vault_url | Required, for example https://kv-ansible-ab12.vault.azure.net |
auth_source | auto (default) / cli / env / msi |
use_msi | Default true: try managed identity first, then use auth_source; set it to false to skip |
client_id / secret / tenant (alias tenant_id) / subscription_id | service 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_path | workload identity federation (lesson 5) |
cloud_environment | Default AzureCloud |
use_cli | Removed 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 stored | Encrypted, in the Git repository | A cloud service backed by HSMs |
| Access control | Anyone with the vault password can decrypt everything | Entra ID + RBAC, scoped down to individual secrets |
| Rotation | Re-encrypt, commit, and distribute the password | New versions take effect immediately; expiration and rotation policies can be set |
| Auditing | Git history | Diagnostic logs record every read (who and when) |
| Offline availability | Yes | Requires network and Azure identity |
How: two modes
Mode A · Push: the control node fetches, Ansible pushes
- The template contains
lookup('azure.azcollection.azure_keyvault_secret', …), and the plugin on the control node is invoked. - The plugin (
use_msi: truewhen set) first requests IMDS169.254.169.254for a managed identity token; if the control node is not an Azure VM, this step fails, then it falls back perauth_sourceto get credentials (CLI/env…). - Use the token (with resource/scope set to
https://vault.azure.net) to call the Key Vault data planeGET /secrets/redis-password; Key Vault authorizes via RBAC (Microsoft.KeyVault/vaults/secrets/getSecret/action, included in the Secrets User role). - 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 usesno_log: trueto 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 lookup | community.hashi_vault lookup | AAP 2.6 external credential plugins | |
|---|---|---|---|
| Backends | Azure Key Vault | HashiCorp Vault | Azure Key Vault, HashiCorp Vault, CyberArk, AWS Secrets Manager, etc. |
| Where it is fetched | control node, at playbook runtime | Control node | the platform injects credentials before the job starts |
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)
Structure diagram: Mode B (Pull, VM managed identity)
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 / module | Purpose | Notes |
|---|---|---|
az keyvault create … --enable-rbac-authorization true | Create a vault that uses RBAC authorization | Name 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 secrets | scope 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_keyvaultsecret | Write a secret with Ansible | keyvault_uri secret_name secret_value |
lookup('azure.azcollection.azure_keyvault_secret', NAME, vault_url=…) | Read a secret | use_msi auth_source |
az keyvault purge | Permanently purge a soft-deleted vault | Used 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)
vault_url.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"
}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
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
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.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.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).
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)"
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
- azure_keyvault_secret lookup
- azure_rm_keyvaultsecret module
- Key Vault: use Azure RBAC authorization (built-in roles)
- Get a token using a managed identity on a VM (IMDS)
- Key Vault soft delete
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.
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.
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.
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.
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.
Module 6 · Ansible and Terraform/Bicep division of labor
- 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-execcalling ansible-playbook, two tools managing the same resource, and using Ansible to maintain large-scale long-lived infrastructure without drift detection.
What: the fundamental difference between the two types of tools
| Dimension | Terraform (1.17) / OpenTofu | Bicep / ARM | Ansible (azure.azcollection) |
|---|---|---|---|
| Model | Declarative; desired state + state file | Declarative; ARM deployment engine (no local state) | Procedural task sequence; each module is idempotent internally |
| Dependencies and parallelism | Automatically builds a dependency graph and runs in parallel | ARM infers dependencies and runs in parallel | Serial in written order (per host) |
| Preview | terraform plan (precise to the property level, marks replacements) | az deployment group what-if | --check --diff (module support varies; results on dependency chains are unreliable) |
| Deletion | Remove from code → plan shows destroy | Complete mode or deployment stacks' --action-on-unmanage | must be set explicitly state: absent |
| Immutable property change | Automatic “destroy and recreate” (forces replacement) | Deployment error or rebuild, depending on the resource | Usually errors or is ignored |
| In-OS configuration | Weak (provisioners are officially positioned as a last resort) | None (only via extensions/cloud-init) | Strong: packages, files, services, users, rolling updates, orchestration |
| Drift | plan detects, apply corrects | what-if detects | Corrects “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
| # | Pattern | Flow | Pros | Watch out |
|---|---|---|---|---|
| 1 | Tag handoff (recommended) | Terraform/Bicep creates the VM and applies role=web → Ansible azure_rm → dynamic inventory → hosts: tag_role_web | The two tools are fully decoupled; scale-out is automatically included | Tag conventions are an “interface contract” and need documentation and policy (enforced by Azure Policy) |
| 2 | Outputs generate inventory | Terraform outputs IP/hostname → generates inventory (terraform output -json, or cloud.terraform collection's terraform_provider/terraform_state inventory plugin) | No dependency on cloud API queries | state is the source of truth and must be able to read the remote state |
| 3 | Ansible drives Terraform | A playbook uses cloud.terraform.terraform module to run plan/apply, then uses terraform_output to read the outputs, then configures | one entry point to complete the end-to-end flow (suited to AWX workflows) | Terraform state still needs a remote backend and locking |
| 4 | Image baking | Packer + Ansible provisioner build the image → Terraform/Bicep use the image to create the VMSS → ready on boot | Immutable infrastructure, fastest to scale out | every 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
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
Flowchart: one complete change using the tag handoff pattern
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 / module | Purpose | Notes |
|---|---|---|
az deployment group what-if | Bicep change preview | Equivalent to plan |
az deployment group create -f vm.bicep | Deploy Bicep | -p name=value |
azure.azcollection.azure_rm_deployment | Deploy an ARM template from Ansible | Bicep must first be az bicep build compiled to JSON |
cloud.terraform.terraform | Run Terraform from Ansible | project_path state: present check_mode Produces a plan |
cloud.terraform.terraform_output | Read Terraform outputs | Pass to subsequent tasks / add_host |
terraform output -json | Data source for generating a static inventory | Suited 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)
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).az deployment group commands.ansible-inventory -i inventory/ --graph tag_role_web --flush-cache, you should see two hosts.ansible-playbook -i inventory/ playbooks/site-azure.yml; vm-myapp-01 is changed=0, while vm-myapp-02 is a fresh install.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.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.
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 tableThe 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
Official docs
- Terraform: Provisioners (“last resort”)
- Bicep overview
- Bicep what-if
- cloud.terraform collection
- This repository’s Terraform course
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.
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.
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.
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.
Module 7 · Troubleshooting on the cloud
- 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.
What: the 6 stages of the execution chain
| Stage | What happens | Typical error keywords | First diagnostic command |
|---|---|---|---|
| ① Local environment | Which Python Ansible uses, collection version, whether the SDK is installed | Failed to import the required Python library,couldn't resolve module/action | ansible --version; ansible-galaxy collection list azure.azcollection |
| ② Authentication | Obtain an Entra ID token | Failed to get credentials,AADSTS7000215 (wrong secret),AADSTS7000222 (secret expired),AADSTS700016 (application not found) | az account show; env | grep ^AZURE_ |
| ③ Inventory | plugin parsing, listing VMs, filtering, grouping | Unable to parse … as an inventory source,provided hosts list is empty,Could not match supplied host pattern | ansible-inventory -i … --graph -vvvv |
| ④ ARM authorization / throttling | RBAC authorization, resource provider registration, Azure Policy, throttling | AuthorizationFailed (403),RequestDisallowedByPolicy,MissingSubscriptionRegistration,TooManyRequests (429) | az role assignment list --assignee … |
| ⑤ Network connectivity | control node → VM TCP 22 | Connection timed out,Connection refused,No route to host | nc -vz IP 22; az network watcher test-ip-flow |
| ⑥ Managed node | SSH authentication, sudo, Python, module execution | Permission denied (publickey),Missing sudo password,dpkg lock | ssh -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
- The file name doesn’t end with
azure_rm.yml/ the plugin is not enabled; - authenticated to the wrong subscription, or the identity can’t see the resource group;
- the resource group name is misspelled (the plugin matches RG names case-insensitively, but a typo returns 0 hosts);
- A VM that is not running is
default_host_filtersexcluded, or your filter is too strict; - 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
| Symptom | Local container lab | Azure |
|---|---|---|
| Host unreachable | container not running, port mapping | NSG, egress IP, VM deallocated, sshd/cloud-init not ready |
| Insufficient permissions | sudo | sudo + RBAC (management plane) + Key Vault data plane role |
| Wrong host list | INI typo | dynamic inventory filters, tags, subscription, cache |
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
Flowchart: the three questions for a 403
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
| Stage | Command | What 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 | head | whether the module can be found, and the active collection path |
| ② | az account show; az ad signed-in-user show --query id | Subscription and identity |
| ② | az ad app credential list --id <appId> --query "[].endDateTime" | whether the SP secret has expired |
| ③ | ansible-inventory -i inventory/ --graph -vvvv | which plugin parsed which file; excluded hosts |
| ④ | az role assignment list --assignee <objectId> --all -o table | roles and scope |
| ④ | az provider show -n Microsoft.Compute --query registrationState | whether the resource provider is registered |
| ④ | az monitor activity-log list -g rg-ansible-lab --status Failed --offset 2h | the 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@IP | SSH 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)
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'
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
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.
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.
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).
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
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
- Understand how Azure Resource Manager throttles requests
- Troubleshoot Azure RBAC
- Network Watcher: IP flow verify
- VM Run Command (Linux)
- Ansible dynamic inventory
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.
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.
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.
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.
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.
Module 8 · Cost, cleanup and self-check
- 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).
What: this lesson’s billable items
| Resource | Billing method | After stop / deallocate | Usage in this lesson |
|---|---|---|---|
VM Standard_B2s | Compute charges billed per second (priced hourly) | Shut down in the OS, or started: false: still billed; deallocate (allocated: false / az vm deallocate): compute billing stops | 1–2 VMs, about 1 hour each |
| Managed disk StandardSSD 30 GiB | billed monthly by provisioned capacity (prorated hourly) | still billed, until deleted | 1 per VM |
| Standard public IP (Static) | billed hourly | still billed, until deleted | 1 per VM (+ 1 for Bastion) |
| Azure Bastion Standard | billed hourly + outbound traffic | can’t be “stopped”, only deleted | optional; delete right after use |
| Key Vault Standard | billed per operation | almost zero | dozens of operations |
| Outbound data | per 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: absenteasily 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
| Leftover | Cause | Handling |
|---|---|---|
| Key Vault name is taken | Soft delete is on by default (retention defaults to 90 days); after the RG is deleted, the vault enters a “deleted but recoverable” state | az keyvault purge -n NAME (when purge protection is not enabled) |
Service principal sp-ansible-lab | The Entra ID object is not in the resource group | az ad sp delete --id APPID (this also deletes its role assignments); if needed, az ad app delete |
| Role assignments | Assignments scoped to a deleted RG become “unknown identity / orphaned” records | are usually cleaned up along with the RG; check az role assignment list --all |
NetworkWatcherRG | Created automatically on first use of Network Watcher | no extra charge; can be kept |
| Local files | ~/.azure/credentials, old host keys in known_hosts, inventory cache | shred -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.ymlto 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
| Ansible | Terraform | Bicep | |
|---|---|---|---|
| One-click delete | Delete RG (force_delete_nonempty) or absent one by one | terraform destroy (only deletes resources in state) | Delete RG, or deployment stack --action-on-unmanage deleteAll |
| Risk of missed deletions | High (stateless) | Low (state), but resources created out of band are not deleted | Medium |
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
Cleanup flow
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.
Core commands
| Command / module | Purpose | Notes |
|---|---|---|
azure_rm_resourcegroup_info + tags | Find RGs by tag | tags: ['env:lab', 'owner:andy'] |
azure_rm_resourcegroup state: absent force_delete_nonempty: true | Delete a non-empty RG | Not recoverable |
az group delete -n rg-ansible-lab --yes --no-wait | CLI delete | az group wait --deleted -n … Wait for completion |
az keyvault list-deleted / purge | Handle soft-deleted vaults | Can’t purge while purge protection is enabled |
az disk list --query "[?managedBy==null]" | Find orphaned disks | Unattached disks are still billed |
az consumption budget create | Budget alerts | can 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)
az resource list -g rg-ansible-lab --query "[].{type:type,name:name}" -o table
az keyvault list -g rg-ansible-lab --query "[].name" -o tsvaz 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
teardown.yml, then run ansible-playbook -i inventory/ playbooks/teardown.yml -e confirm=yes.~/.azure/credentials; unset the environment variables.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.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.
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 tableOn 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.
Verified teaching videos
No verified video specifically on “Azure VM stop vs. deallocate billing + Ansible cleanup” was found.
Official docs
- States and billing status of Azure Virtual Machines
- Delete resource group and resources
- Key Vault recovery (soft delete and purge protection)
- Create and manage budgets
- Azure Pricing Calculator
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.
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.
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.
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.
Command cheat sheet
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 keyword | Most likely cause | First step |
|---|---|---|
| Failed to import the required Python library | SDK not installed in Ansible’s Python | pipx inject ansible -r …/requirements.txt |
| Failed to get credentials | all four sources in the auto chain are empty | az login or check AZURE_* |
| Unable to parse … as an inventory source | file name doesn’t end with azure_rm.yml | Rename |
| provided hosts list is empty | RG name, filters, VM not running, permissions, cache | ansible-inventory --graph --flush-cache |
| AuthorizationFailed (403) | identity / action / scope mismatch | read the 3 elements of the error,az role assignment list |
| ForbiddenByRbac (Key Vault) | missing data plane role | assign Key Vault Secrets User |
| TooManyRequests (429) | too many calls | centralize on localhost, cache, lower forks |
| Connection timed out (22) | NSG source IP, VM not running | test-ip-flow,curl api.ipify.org |
| Permission denied (publickey) | wrong username or private key | ssh -v; az vm user update |
| Could not get lock /var/lib/dpkg/lock-frontend | cloud-init still running | cloud-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) | firstmodule_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: falseCapstone lab + final quiz
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
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
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",redis-password, and in inventory/group_vars/tag_app_myapp.yml define kv_url the lookup.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
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 passwordansible-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
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
| Topic | Verified finding | Source (accessed 2026-11-15) |
|---|---|---|
| ansible-core / community package | core 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.21 | course spec section 3;Release and maintenance |
| azure.azcollection version | Galaxy 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.10 | Galaxy · CHANGELOG · meta/runtime.yml |
| 4.0.0 breaking changes | lookup plugins removed use_cli; azure_rm_virtualmachine removes the unmanaged disk parameters; the MariaDB and MySQL/PostgreSQL Single Server modules, etc., are removed | CHANGELOG v4.0.0 |
| Python dependencies | collection 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 environment | requirements.txt · doc_fragments/azure.py |
| Authentication order | auto: 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/credentials | azure_rm_common.py(_get_credentials, AZURE_CREDENTIAL_ENV_MAPPING) |
| azure_rm inventory plugin | the 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 parameters | azure_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 plugin | name 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 keyword | lookup docs · source code |
| Azure Bastion | The 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 Bastion | Connect to a VM using Bastion - Linux native client |
| cloud.terraform collection | modules terraform, terraform_output, plan_stash; inventory plugins terraform_provider, terraform_state | GitHub |
| Key Vault RBAC / soft delete, ARM throttling, VM billing states | Conceptual notes; for exact values, refer to the official docs | RBAC 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.