David Hedges

  • Home
  • About
  • Contact
  • Business Blog
  • IT Blog

Using Ansible to generate inventory data

April 7, 2021 by dhedges Leave a Comment

Ansible can be used to collect a lot of usable data that can be imported into an api or database driven inventory system, creating an automated way of updating hardware information.

Creating an ansible yml file to pull inventory to a json file is fairly simple:

---
- hosts: all
  gather_facts: no
  tasks:
    - setup:
      register: myinv
    - copy:
        content: "{{ myinv | to_nice_json }}"
        dest: /some/local/path/{{ inventroy_hostname }}.json
      delegate_to: localhost

running the ansible playbook generates a json file for each host. This data can then be parsed and pushed directly into a database, update a system using an api, parsed and pushed into a spreadsheet, or any number of other things that can be thought of.

using python to parse the json files, below is a snippet of how I take the data contained within the json files, and pull them into variables.

#!/usr/bin/python
import glob, json
for file in glob.glob('/path/to/json/files/*.json'):
     hwinf = json.load(open(file))
     if 'ansible_facts' in hwinfo:
          hostfqdn = hwinfo['ansible_facts']['ansible_nodename']
          hostip = hwinfo['ansible_facts']['ansible_default_ipv4']['address']

the json file is fairly easy to pull data from. From here though you have the data, and just need to determine how you will use it.

Filed Under: IT Blog

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Copyright © 2025 · Beautiful Pro Theme on Genesis Framework · WordPress · Log in