This blog post will show you how to create a dynamic inventory for Microsoft Azure with Ansible.
Dynamic Inventory
Ansible dynamic inventory allows us to manage resources on Azure or other cloud providers without maintaining a static inventory file. A dynamic inventory allows us to target all the hosts inside a resource group or hosts that have specific tags.
Create Azure Credentials
The first step in creating a dynamic inventory is to authenticate to Microsoft Azure, and the recommended method is using a credentials file.
Download Ansible Dynamic Inventory Plug-In (azure_rm.py)
The next step is to download the Ansible dynamic inventory plug-in from Github. The plug-in is a python script—the link to the plug-in below.
https://github.com/ansible/ansible/blob/stable-2.9/lib/ansible/plugins/inventory/azure_rm.py
After you download the file, make sure you set the permissions on the file using the following command.
chmod +x azure_rm.py
Create an Inventory Configuration file
The next step is to create an inventory configuration file (YML) in the same directory as the plug-in file (.py) from the previous step. The file name must contain the word azure_rm in the name and therefore I called it in.azure_rm.yml
In my case, I will target all the resources inside a resource group called ubuntu-resources.
plugin: azure_rm include_vm_resource_groups: - ubuntu-resources auth_source: auto keyed_groups: - prefix: tag key: tags
Before you run the file in the terminal, run the following command to disable host key checking.
export ANSIBLE_HOST_KEY_CHECKING=False
To test that everything is working, I will ping all the VM in the resource-group Ubuntu-resources. Note: I am also passing a variable for the SSH key and the username of the VMs.
ansible all -m ping -i ./in.myazure_rm.yml --private-key=~/.ssh/id_rsa --user=vmuser
The output is shown below.
ubuntuvm | SUCCESS => { "ansible_facts": { "discovered_interpreter_python": "/usr/bin/python" }, "changed": false, "ping": "pong"
Leave a Reply