inventory-scripts.lxc/inventory_lxc.py
2024-09-20 09:49:47 +02:00

37 lines
705 B
Python
Executable file

#!/usr/bin/python3
import json
import sys
try:
import lxc
except ImportError:
print("Could not import lxc module!")
sys.exit(1)
########################################
inventory ={ '_meta':{'hostvars':{} } }
########################################
ctnames = lxc.list_containers()
for ctname in ctnames:
ct = lxc.Container(ctname)
if ct.running:
groups = ct.get_running_config_item('lxc.group')
if not groups:
groups = 'ungrouped'
for group in groups.rstrip().split('\n'):
if not group in inventory:
inventory[group] = {
'hosts': [],
'vars': {
'ansible_connection': 'lxc',
}
}
inventory[group]['hosts'].append(ctname)
print(json.dumps(inventory))