Skip to content

Instantly share code, notes, and snippets.

@tkjaer
Last active May 8, 2020 16:10
Show Gist options
  • Save tkjaer/6d606b14d4413f7101b6eb6cc28c9e22 to your computer and use it in GitHub Desktop.
Save tkjaer/6d606b14d4413f7101b6eb6cc28c9e22 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Dynamic Ansible Inventory based on LibreNMS API access.
"""
#######################################################################
# #
# This script has been superseded by: #
# #
# https://github.com/tkjaer/ansible-dynamic-inventory #
# #
#######################################################################
import requests
import json
import re
headers = {
'X-Auth-Token': 'XXXXXXXXXX',
}
r = requests.get('https://XXXXXXXXXX/api/v0/devices', headers=headers)
librenms_devices = json.loads(r.text)
# Create the basic inventory structure.
# - http://docs.ansible.com/ansible/devel/dev_guide/developing_inventory.html
ansible_inventory = {
"_meta": {
"hostvars": {},
},
"all": {
"children": [
"ungrouped",
]
},
"ungrouped": {},
}
for device in librenms_devices['devices']:
# Get the devices type, based on the internal Naming Scheme
# - https://XXXXXXXXXX/plugin/p=Namingscheme
device_type = re.match("^([a-zA-Z]*).*", device['hostname']).group(1)
try:
if (ansible_inventory[device_type]):
pass
except KeyError:
ansible_inventory[device_type] = {
'hosts': [],
'vars': {
#'ansible_connection': 'local',
'connection': 'network_cli',
}
}
ansible_inventory['all']['children'].append('device_type')
hostname = device['hostname']
ansible_inventory[device_type]['hosts'].append(hostname)
ansible_inventory['_meta']['hostvars'][hostname] = {
'sysname': device['sysName'],
'hardware': device['hardware'],
'location': device['location_id'],
'type': device['type'],
'ansible_network_os': device['os'],
}
print(ansible_inventory)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment