Ansible Dynamic Inventory for Azure: Step by Step
This guide shows how to build, validate and use an Azure dynamic inventory with Ansible, and how to set the user and password Ansible uses to log in to the VMs (and how to create new users on them).
1. Prerequisites
# 1. Install venv support (Ubuntu/Debian)
sudo apt update
sudo apt install -y python3-full python3-venv sshpass
# 2. Create and activate the virtual environment
python3 -m venv ~/ansible-venv
source ~/ansible-venv/bin/activate
# 3. Confirm pip comes from the venv (path must contain ansible-venv)
which pip
# 4. Install Ansible
pip install --upgrade pip
pip install ansible
# Azure collection (contains the azure_rm inventory plugin)
ansible-galaxy collection install azure.azcollection --force
# Python SDK dependencies required by the collection
pip install -r ~/.ansible/collections/ansible_collections/azure/azcollection/requirements.txt
If the venv is not at the default path, find the collection with
ansible-galaxy collection list | grep azure.
Every new terminal session you must re-activate the venv before running any Ansible command:
source ~/ansible-venv/bin/activate
Verify the install (important):
ansible --version
ansible-galaxy collection list | grep azure
# Must point into your venv, NOT /usr/bin
which ansible-inventory # expected: /root/ansible-venv/bin/ansible-inventory
# Must print "ok". If not, the Azure SDK is missing for this Python
python -c "import azure.mgmt.compute; print('ok')"
If
which ansible-inventoryshows/usr/bin/ansible-inventory, you are running the system Ansible instead of the venv. Runsource ~/ansible-venv/bin/activate.
3. Authenticate to Azure
Pick one method.
Install the Azure CLI first (needed for az commands)
If you see az: command not found, the Azure CLI is not installed. On Ubuntu/Debian:
# One-line installer from Microsoft
curl -sL https://aka.ms/InstallAzureCLIDeb | sudo bash
# Verify
az version
Option A: Azure CLI (quick, good for testing)
az login
az account set --subscription "<SUBSCRIPTION_ID>"
Option B: Service Principal (recommended for automation)
az ad sp create-for-rbac \
--name ansible-inventory-sp \
--role Reader \
--scopes /subscriptions/<SUBSCRIPTION_ID>
Copy the output (appId, password, tenant) and export:
export AZURE_SUBSCRIPTION_ID="<SUBSCRIPTION_ID>"
export AZURE_CLIENT_ID="<appId>"
export AZURE_SECRET="<password>"
export AZURE_TENANT="<tenant>"
export AZURE_CLIENT_ID="4f8c6b9b-8cbc-4c58-b74b-6173e9f36ea8"
export AZURE_SECRET="xYr8Q~k0OeMBt9YwgFjjZeO6Um0C.e3.pefiMbNd"
export AZURE_TENANT="726fed04-5c24-4ce7-9f26-23aede5f917f"
export AZURE_SUBSCRIPTION_ID="ce2e62f0-7f43-4675-98f5-0735bedf76c9"
az login --service-principal \
--username "$AZURE_CLIENT_ID" \
--password "$AZURE_SECRET" \
--tenant "$AZURE_TENANT"
plugin: azure.azcollection.azure_rm
auth_source: auto
include_vm_resource_groups:
- '*'
keyed_groups:
- prefix: env
key: tags.env
- prefix: os
key:
hostvar_expressions:
ansible_user: "'azureuser'"
# ansible_ssh_private_key_file: "'/root/azure_cm_key.pem'"
source ~/ansible-venv/bin/activate
export ANSIBLE_HOST_KEY_CHECKING=False
ansible-inventory -i myazuresub.azure_rm.yaml --graph
ansible -i myazuresub.azure_rm.yaml -m ping all --ask-pass
Deploy sample playbook
---
- name: Install and configure Apache2
hosts: all
become: yes
tasks:
- name: Install Apache2
ansible.builtin.apt:
name: apache2
state: present
update_cache: yes
- name: Start and enable Apache2 service
ansible.builtin.service:
name: apache2
state: started
enabled: yes
CMD
ansible-playbook -i myazuresub.azure_rm.yaml apache2.yaml --ask-pass
Ansible Azure Dynamic Inventory Setup (keyed_groups by OS)
Overview
In Ansible, azure.azcollection.azure_rm queries the Azure Resource Manager API before connecting to VMs via SSH or WinRM. Because Ansible facts (ansible_distribution and ansible_os_family) are only collected after connecting to a host, they cannot be used directly inside azure_rm.yml.
To dynamically group Azure VMs into distro_* and os_family_* groups:
- Use
azure.azcollection.azure_rmto discover VMs in theansibleresource group and setansible_user. - Enable JSON fact caching in
ansible.cfg. - Use
ansible.builtin.constructedto createkeyed_groupsfrom cached OS facts.
1. Directory Structure
project/
├── ansible.cfg
└── inventory/
├── 01_azure_rm.yml
└── 02_constructed.yml
2. Configuration Files
inventory/01_azure_rm.yml
(Note: The filename must end in azure_rm.yml or azure_rm.yaml, and compose is used to set ansible_user.)
plugin: azure.azcollection.azure_rm
auth_source: auto
cache: false
include_vm_resource_groups:
- ansible
compose:
ansible_user: "'azureuser'"
inventory/02_constructed.yml
plugin: ansible.builtin.constructed
strict: false
keyed_groups:
- prefix: distro
key: ansible_distribution | lower
- prefix: os_family
key: ansible_os_family | lower
ansible.cfg
[defaults]
inventory = ./inventory
gathering = smart
fact_caching = jsonfile
fact_caching_connection = ./.ansible_facts_cache
fact_caching_timeout = 86400
3. Usage & Verification
-
Gather and cache facts from your Azure VMs:
ansible all -m setup -
Verify the generated
distro_*andos_family_*groups:ansible-inventory --graph -
Target OS groups in a playbook:
- name: Update Ubuntu servers hosts: distro_ubuntu become: true tasks: - name: Update apt cache ansible.builtin.apt: update_cache: true
Task: Terraform and Ansible Dynamic Inventory Automation
1. Ansible Tasks
- Create an Ansible dynamic inventory using the
servertag to automatically group virtual machines. - Create three virtual machines using Terraform and assign the following tags:
- VM1:
server=app1 - VM2:
server=app2 - VM3: No
servertag (or assign a different tag).
- VM1:
- Configure unique SSH credentials for each VM using a username and password or an SSH private key.
- Verify connectivity by pinging the virtual machines using their respective Ansible groups.
- Execute Ansible ad-hoc commands against each group.
2. Terraform Tasks
- Create EC2 instances using Terraform.
- Configure EC2 User Data to install and configure Python.
- Use User Data to install the required software packages.
- Configure the EC2 instances with the required tags.
- Ensure that the instances have the necessary network access for SSH connectivity.
3. GitHub Integration and Ansible Execution
Use EC2 User Data to automate the following steps:
- Clone the Ansible project repository from GitHub.
- Configure the local Ansible inventory and execution environment.
- Execute the Ansible playbook automatically using the local connection where applicable.
- Verify that the playbook executes successfully.
4. Expected Output
- Three EC2 instances should be created successfully.
- Ansible dynamic inventory should automatically group instances based on the
servertag. - Two groups should be created:
app1andapp2. - SSH authentication should work using the configured credentials.
- Ansible ping should succeed for the respective groups.
- The Ansible playbook should execute automatically through EC2 User Data.
