Skip to content

Instantly share code, notes, and snippets.

@stemid
Last active July 11, 2019 15:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save stemid/59fc2833590d500d068374d3299028d5 to your computer and use it in GitHub Desktop.
Save stemid/59fc2833590d500d068374d3299028d5 to your computer and use it in GitHub Desktop.
Ansible inventory script for Siptrack (https://github.com/sii/siptrackweb)
#!/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