Ansible dynamic inventory
- cloud provider plugin to get ipaddress
Features static inventory vs dynamic inventory
- Source of truth – A file you can edit – Itself (azure/aws/GCP)
- new vm created – manually update info vm – Pickup automatically
- Deleted vm – manually need to remove – Disappers automatically
- Grouping – manually – based on tags, locations, resource group …etc
- Best – samll and fixed env -Cloud and autoscalling enviroments
Ansible inventory plugin works
Steps:
- Ansible read
*.azurerm.yaml - plugin is auth to azure
- it calls all RM get listed vm and ipaddress
- it converts to host (hosts varibale and group)
- run playbook against the resulting inventory
Pre-requests:
- az auth
- install azure plugins
sudo apt update
# Install Python and virtual environment
sudo apt install -y python3-pip python3-venv
# Create virtual environment
python3 -m venv ansible-venv
# Activate environment
source ansible-venv/bin/activate
# Install Ansible
pip install ansible-core
ansible-galaxy collection install azure.azcollection
az login
MSYS_NO_PATHCONV=1 \
az ad sp create-for-rbac \
--name "ansible-azure-sp" \
--role "Contributor" \
--scopes "/subscriptions/ce2e62f0-7f43-4675-98f5-0735bedf76c9"
# out put
information, see https://aka.ms/azadsp-cli
{
"appId": "ks",
"displayName": "ansible-azure-sp",
"password": "k",
"tenant": "ss"
}
login sp
curl -fsSL 'https://azurecliprod.blob.core.windows.net/$root/deb_install.sh' | sudo bash
export AZURE_CLIENT_ID="ks"
export AZURE_SECRET="k"
export AZURE_TENANT="s-5c24-4ce7-9f26-ss"
export AZURE_SUBSCRIPTION_ID="ss"
az login --service-principal \
--username "$AZURE_CLIENT_ID" \
--password "$AZURE_SECRET" \
--tenant "$AZURE_TENANT"
create dynamic inventory file
myazuresub.azure_rm.yaml
plugin: azure.azcollection.azure_rm
auth_source: cli
include_vm_resource_groups:
- ansible
conditional_groups:
webserver: "tags.ansible | default('') == 'webserver'"
