Absolutely! You can achieve this by writing a simple dynamic inventory script in Python (or any language), which reads your three INI inventory files, merges them, and outputs the combined inventory in JSON (Ansible expects JSON from dynamic inventory scripts).
Let’s assume your three inventory files are named inv1.ini, inv2.ini, and inv3.ini.
Step 1: Write the Dynamic Inventory Script
Create a file called all (no extension, make it executable):
#!/usr/bin/env python3
import configparser
import json
import sys
import os
# List your inventory files here
inventory_files = ['inv1.ini', 'inv2.ini', 'inv3.ini']
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()
Step 2: Make the Script Executable
chmod +x all
Step 3: Use the Script as Inventory
Now you can run:
ansible -i ./all all -m ping
or
ansible-inventory -i ./all --list
Notes
- This script is a basic merger. If you have overlapping groups or hosts, you may want to add logic to deduplicate hosts.
- If you want to support host variables (
host1 var1=val1), you’ll need to extend the script to parse those as well.
- You can place the script anywhere, just reference it with
-i.
Let me know if you want a version that supports host variables or more advanced merging!