In this post we are going to learn how to use NetBox as a dynamic inventory source for Ansible playbooks. I’m going to set up a NetBox instance as a dynamic inventory for Ansible, then add a host and then run an Ansible Playbook which will use Netbox as it’s inventory source.
This will show how you can create dynamic inventories for Ansible to pull data from Netbox for your playbooks.
What is a Dynamic Inventory?
A dynamic inventory is the live, real-time version of your infrastructure inventory. It contrasts with the traditional static inventory e.g. Ansible inventory ini files that lead to configuration drift.
Using a Network Source of Truth will elevate your network automation from running a few scripts on your laptop to a production ready system
Netbox Ansible Dynamic Inventory Example

Ansible Netbox Inventory Plugin
First you need to install the Ansible Galaxy collection for Netbox.
Netbox has already written the code to provide a dynamic inventory you will need to install this first using the following command.
ansible-galaxy collection install netbox.netbox
1. Create netbox_inventory.yml
Now you have the Netbox Ansible collection installed you can now reference this in your inventory file.
Create a file called netbox_inventory.yml in the root of your Ansible install.
This simple example will group your devices by device role
--- plugin: netbox.netbox.nb_inventory validate_certs: false config_context: false api_endpoint: http://my-netboxserver/ token: 0562e56ee40f345f92da370dbf1017a91c6a39 validate_certs: false group_by: - device_roles
2. Filter devices by Site, Role or Tag
You can group devices by any Netbox field you wish in this example we are grouping the devices by device_role. If you want you can filter even further using device_query_filters.
For this example we are just going to use all of the available data
3. Change ansible.cfg to use dynamic inventory
When running Ansible with a local inventory your ansible.cfg would have this line
[defaults] inventory = ./hosts
Then in a file called hosts you would define your devices
[routers] router1.domain.com router2.domain.com CSR-1 ansible_host=192.168.1.199 [switches] switch1.domain.com switch2.domain.com
To transition your local Ansible inventory to use a dynamic inventory change these bits in your ansible.cfg file.
[defaults] inventory = ./netbox_inventory.yml [inventory] enable_plugins = netbox.netbox.nb_inventory
We need to make sure we have a device in Netbox – then we can test if Ansible can query the device info from Netbox
4. Verify your Netbox Dynamic Inventory with ansible-inventory
Check Ansible can talk to Netbox using this command
ansible-inventory -i inventory/netbox.yml --list

Leave a Reply