How to build an Ansible dynamic inventory from your IPAM
How to generate an Ansible dynamic inventory from your IPAM's REST API, so that playbooks run against the devices the network has today.
A static hosts file describes your network as it was on the day someone last edited it, and the network has usually changed since then. This post shows how to point Ansible at your IPAM instead. Every playbook run then targets the devices that exist at that moment, and they are grouped by role, site and tag without anyone editing a file.
Why static inventory files go out of date
An inventory file that people maintain by hand starts to differ from the network almost immediately. Someone racks a new switch and forgets to add it. A server is decommissioned but stays in [webservers] for another six months. A site is renamed in one place and keeps its old name in the other.
The failure this causes is hard to notice, because the playbook runs successfully against the wrong set of hosts. Nothing reports an error. A machine that should have been patched is skipped, or a decommissioned box receives a config push it should never have had.
The way out is to treat the inventory as a query you run and stop treating it as a document you edit. Your IPAM should already be the source of truth for what exists. If it is, Ansible can ask it directly each time it runs.
How a dynamic inventory works
A dynamic inventory is an inventory source that Ansible resolves on every run. Ansible does not read a file. It runs a program that returns the current host list as JSON, and that program pulls the devices from your IPAM over its REST API and sorts them into Ansible groups.
Danbyte models IP space, physical devices, sites and tags in one place, so it already holds everything an inventory needs:
- Devices and their management addresses, which tell Ansible what to connect to
- Roles such as router, switch, hypervisor or edge firewall, which become functional groups
- Sites and racks, which become location groups
- Tags such as
pci,stagingorneeds-reboot, which become groups that cut across roles and sites
You map those to Ansible groups once. After that the inventory follows the IPAM and needs no separate upkeep.
Step 1: make the IPAM the source of truth
This step is about how the team works, and it involves no code. If every device is created in the IPAM when it is racked, addressed and given a role and tags, the inventory is correct because it is built from those records. If people still add hosts on the side "just for Ansible", the two will start to differ again.
Danbyte's REST API exposes devices, addresses, sites, roles and tags for this kind of automation. All of Danbyte's features are in the open-source release, so there is no separate automation tier to pay for. Create an API token, confirm that you can list devices, and you are ready for the next step.
Step 2: choose a dynamic inventory approach
There are two ways to do this, and either one works:
- An inventory script is any executable that prints inventory JSON when called with
--list. It is the simplest to understand, works with any Ansible version and is easy to run anywhere. It suits a first attempt and CI jobs. - An inventory plugin is a Python plugin driven by a small YAML config. It is the more usual choice in current Ansible, supports caching and composed groups, and is easier to maintain when the inventory is large.
Start with a script to prove the idea. Move to a plugin later if you want caching and more group logic. The data source is the same in both cases.
Step 3: map tags, roles and sites to groups
The script below is a minimal skeleton. It sends a GET request for the devices and prints the JSON structure that Ansible expects. The endpoints and field names are illustrative, so check the Danbyte docs for the exact paths and query parameters.
#!/usr/bin/env python3
import json, os, requests
BASE = os.environ["IPAM_URL"] # e.g. https://ipam.example.net/api
TOKEN = os.environ["IPAM_TOKEN"]
headers = {"Authorization": f"Token {TOKEN}"}
# Ask the IPAM for active devices (paginate for real deployments)
devices = requests.get(f"{BASE}/devices",
params={"status": "active"},
headers=headers).json()["results"]
inv = {"_meta": {"hostvars": {}}}
def group(name):
inv.setdefault(name, {"hosts": []})
return inv[name]
for d in devices:
name = d["name"]
ip = d.get("primary_ip") # management address
if not ip:
continue
inv["_meta"]["hostvars"][name] = {"ansible_host": ip}
# Group by role, site, and every tag
if d.get("role"):
group(f"role_{d['role']}")["hosts"].append(name)
if d.get("site"):
group(f"site_{d['site']}")["hosts"].append(name)
for tag in d.get("tags", []):
group(f"tag_{tag}")["hosts"].append(name)
print(json.dumps(inv))
A production version should do a few more things:
- Paginate the device query. One page will not hold every device in a larger network.
- Filter on the server with parameters such as
status=active, a specific site or a role, so that you transfer only the devices you need. - Set useful hostvars: the management address, the platform and any connection details your playbooks rely on.
- Cache the results if you resolve the inventory hundreds of times a day. The plugin approach makes this easy.
Step 4: run it
Make the script executable and look at what Ansible sees. This is the quickest check, because it calls the API and prints the resolved inventory without connecting to any host:
export IPAM_URL=https://ipam.example.net/api
export IPAM_TOKEN=****
chmod +x ipam_inventory.py
ansible-inventory -i ipam_inventory.py --list # full JSON
ansible-inventory -i ipam_inventory.py --graph # group tree
ansible all -i ipam_inventory.py -m ping # smoke test
--limit tag_pci, --limit site_ams1 and --limit role_switch now all work, and they reflect the state of the IPAM at the time of the run. When you decommission a device in the IPAM, it is gone from the next run and nobody has to edit a hosts file.
Where to go from here
Once the inventory comes from the IPAM, the same API can serve the rest of your automation. Provisioning scripts, Terraform runs and compliance checks can all read from the one source of truth and write back to it. The REST API is the same when you self-host Danbyte on your own hardware.
Danbyte can run air-gapped and sends no telemetry and makes no calls home, so this setup works on an isolated management network as well as anywhere else.
When the dynamic inventory returns every host your playbooks need, you can retire the hosts file.
