#!/usr/bin/env python3
"""
Ansible dynamic inventory that combines all inventory files into a single one.
This is useful for Semaphore, since it allows to select only one inventory per run.
"""
import configparser
import json
import sys
import os
# List your inventory files here
INVENTORY_FILES = [
'tertiary',
'secondary',
'tertiary'
]
def parse_ini_inventory(files):
inventory = {}
hosts_vars = {}
for file in files:
if not os.path.exists(file):
continue
config = configparser.ConfigParser(allow_no_value=True, delimiters=(' ', '='))
config.optionxform = str # preserve case
config.read(file)
for section in config.sections():
if section.endswith(':vars'):
group = section[:-5]
if group not in inventory:
inventory[group] = {'hosts': [], 'vars': {}}
for k, v in config.items(section):
inventory[group]['vars'][k] = v
else:
if section not in inventory:
inventory[section] = {'hosts': [], 'vars': {}}
for host, _ in config.items(section):
inventory[section]['hosts'].append(host)
return inventory
def to_ansible_json(inventory):
result = {}
for group, data in inventory.items():
result[group] = {}
if data['hosts']:
result[group]['hosts'] = data['hosts']
if data['vars']:
result[group]['vars'] = data['vars']
# Add _meta for hostvars (optional, for advanced use)
result['_meta'] = {'hostvars': {}}
return result
def main():
if len(sys.argv) == 2 and sys.argv[1] == '--list':
inventory = parse_ini_inventory(INVENTORY_FILES)
print(json.dumps(to_ansible_json(inventory), indent=2))
elif len(sys.argv) == 3 and sys.argv[1] == '--host':
# Not implemented, but required for dynamic inventory
print(json.dumps({}))
else:
print("Usage: all --list or all --host <hostname>", file=sys.stderr)
sys.exit(1)
if __name__ == '__main__':
main()