-
-
Save jostmart/762d4f7be92caf7eaf85222b5755abca to your computer and use it in GitHub Desktop.
Ansible inventory script for Siptrack (https://github.com/sii/siptrackweb)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# Siptrack dynamic inventory script for Ansible. | |
# Depends on siptracklib | |
# * https://github.com/sii/siptracklib | |
# | |
#http://docs.ansible.com/ansible/latest/dev_guide/developing_inventory.html | |
# | |
# by Stefan Midjich <swehack at gmail dot com> | |
import sys | |
import json | |
from argparse import ArgumentParser | |
from siptracklib.config import SiptrackConfig | |
from siptracklib.connections import ConnectionManager | |
HOSTGROUP_ATTR_NAME = 'ansible_hostgroup' | |
inventory_data = {} | |
json_output_fd = sys.stdout | |
parser = ArgumentParser() | |
parser.add_argument( | |
'--debug', | |
action='store_true', | |
default=False, | |
help='Show verbose output' | |
) | |
parser.add_argument( | |
'--list', | |
action='store_true', | |
default=True, | |
help='List instances (default: True)' | |
) | |
args = parser.parse_args() | |
config = SiptrackConfig() | |
cm = ConnectionManager(config=config, interactive=True) | |
object_store = cm.connect() | |
devices = object_store.quicksearch( | |
'{hostgroup_name}:*'.format(hostgroup_name=HOSTGROUP_ATTR_NAME), | |
max_results=500 | |
) | |
for device in devices: | |
device_name = device.attributes.get('name', 'unknown-name') | |
# Get ansible host group | |
host_group = device.attributes.get(HOSTGROUP_ATTR_NAME, None) | |
if not host_group: | |
continue | |
if host_group not in inventory_data: | |
inventory_data[host_group] = [] | |
# Loop through all the ansible_hostgroup variables for multiple group | |
# memberships. | |
for attr in device.attributes: | |
if attr.name == HOSTGROUP_ATTR_NAME: | |
if attr.name not in inventory_data: | |
inventory_data[attr.value] = [] | |
inventory_data[attr.value].append(device_name) | |
if args.list: | |
json.dump(inventory_data, json_output_fd, indent=2) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment