#!/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()
#!/usr/bin/env python3
"""Ansible dynamic inventory combining multiple INI inventory files.
This script aggregates inventory data from several INI files into a single
JSON output compatible with Ansible's dynamic inventory specification. It's
particularly useful for platforms like Semaphore that require a single
inventory source per execution.
"""
import configparser
import json
import os
import sys
# --- Configuration ---
# List your inventory files here. The script will read and combine them.
# Files are processed in the order they appear in this list.
# Note: 'tertiary' is listed twice in the original example. This might be
# intentional or a typo. Ensure the paths are correct relative to where
# this script is executed.
INVENTORY_FILES = [
'tertiary',
'secondary',
'tertiary'
]
# --- Core Logic ---
def parse_ini_inventory(files):
"""Parses multiple INI inventory files into a structured dictionary.
Reads inventory data from a list of INI files. Sections in the INI files
are treated as Ansible groups. Sections ending with ':vars' are parsed
as group variables. Other sections list hosts belonging to that group.
The function skips files that do not exist or cannot be read.
Args:
files (list[str]): A list of file paths pointing to the INI inventory
files to be parsed.
Returns:
dict: A dictionary representing the combined inventory. The structure
is suitable for conversion into Ansible's dynamic inventory
JSON format, with group names as keys and values containing
'hosts' (list) and 'vars' (dict).
"""
inventory = {}
# Configure configparser to handle INI files correctly for inventory.
# allow_no_value=True supports entries like 'hostname' without an '='.
# delimiters=(' ', '=') allows both space and equals sign as separators.
config = configparser.ConfigParser(
allow_no_value=True,
delimiters=(' ', '=')
)
# Preserve case sensitivity in section and option names (groups and vars).
config.optionxform = str
for filename in files:
if not os.path.exists(filename):
# Skip files that don't exist
print(f"Warning: Inventory file '{filename}' not found, skipping.",
file=sys.stderr)
continue
try:
with open(filename, 'r') as f:
config.read_file(f)
except IOError as e:
print(f"Error reading file '{filename}': {e}", file=sys.stderr)
continue # Continue processing other files if one fails
except configparser.Error as e:
print(f"Error parsing INI file '{filename}': {e}", file=sys.stderr)
continue # Continue processing other files if parsing fails
# Process sections from the current file
for section in config.sections():
if section.endswith(':vars'):
# This section defines variables for a group
group_name = section[:-5] # Remove ':vars' suffix
if group_name not in inventory:
# Initialize group if it doesn't exist
inventory[group_name] = {'hosts': [], 'vars': {}}
# Add variables to the group
for key, value in config.items(section):
inventory[group_name]['vars'][key] = value
else:
# This section defines hosts for a group
group_name = section
if group_name not in inventory:
# Initialize group if it doesn't exist
inventory[group_name] = {'hosts': [], 'vars': {}}
# Add hosts to the group
for host_name, _ in config.items(section):
# Ensure host is not already added to prevent duplicates
# within the same group definition.
if host_name not in inventory[group_name]['hosts']:
inventory[group_name]['hosts'].append(host_name)
# Remove groups that ended up with no hosts after parsing.
# This handles cases where a group might only have :vars defined or
# if all hosts from a group definition were duplicates.
inventory = {
group: data for group, data in inventory.items() if data['hosts']
}
return inventory
def to_ansible_json(inventory):
"""Converts the internal inventory structure to Ansible's JSON format.
This function takes the structured dictionary created by `parse_ini_inventory`
and transforms it into the JSON output expected by Ansible for a '--list'
request. It includes the standard '_meta' key with an empty 'hostvars'
dictionary, which is a placeholder for host-specific variables often
provided by more complex dynamic inventories.
Args:
inventory (dict): The inventory data, structured as
{group_name: {'hosts': [...], 'vars': {...}}}.
Returns:
dict: A dictionary formatted according to Ansible's dynamic inventory
JSON specification.
"""
result = {}
for group, data in inventory.items():
# Skip empty groups which might occur if only :vars section existed
# and no hosts were added to the primary group section.
if not data.get('hosts'):
continue
result[group] = {}
# Add 'hosts' key if there are hosts in the group
result[group]['hosts'] = data['hosts']
# Add 'vars' key if there are variables defined for the group
if data.get('vars'):
result[group]['vars'] = data['vars']
# Add the _meta key as required by Ansible dynamic inventory scripts.
# It typically contains hostvars, but we leave it empty here as per the
# original script's intent (no hostvars implementation).
result['_meta'] = {'hostvars': {}}
return result
def main():
"""Entry point for the Ansible dynamic inventory script.
Handles command-line arguments required by Ansible:
- '--list': Returns the combined inventory in JSON format.
- '--host <hostname>': Currently returns an empty JSON object, as host
variable lookup is not implemented.
- Other arguments: Prints usage instructions to stderr and exits with
an error code (1).
"""
script_name = os.path.basename(sys.argv[0])
if len(sys.argv) == 2 and sys.argv[1] == '--list':
# Parse all specified inventory files
combined_inventory = parse_ini_inventory(INVENTORY_FILES)
# Convert to Ansible JSON format and print to stdout
ansible_json_output = to_ansible_json(combined_inventory)
print(json.dumps(ansible_json_output, indent=2))
elif len(sys.argv) == 3 and sys.argv[1] == '--host':
# The '--host' argument is required for dynamic inventories,
# but host variable lookup is not implemented in this script.
# Return an empty JSON object as per convention.
print(json.dumps({}))
else:
# Print usage instructions if arguments are incorrect
print(f"Usage: {script_name} --list", file=sys.stderr)
print(f" or: {script_name} --host <hostname>", file=sys.stderr)
sys.exit(1)
# --- Script Execution ---
if __name__ == '__main__':
main()