#!/usr/bin/env python

import os
import sys
import json
import lxc
import re
import ConfigParser

if os.geteuid() != 0:
    os.execvp("sudo", ["sudo"] + sys.argv)

config = ConfigParser.ConfigParser()
config.read('/etc/stackforce/parameters.ini')

result = {}
result['all'] = {}
hostvars = {}
os_vars = {
    'os_rabbit_host': config.get('public', 'address'),
    'os_rabbit_port': config.get('os', 'rabbit_port')}


containers = lxc.list_containers(active=True, defined=False)
for container_name in containers:
    srv = re.split('_', container_name)
    group = srv[0]
    if not group in result:
        result[group] = {}
        result[group]['hosts'] = []
        result[group]['vars'] = os_vars
    if isinstance(result[group], dict):
        result[group]['hosts'].append(container_name)
    # get ip from container object
    container = lxc.Container(name=container_name)
    result['all']['hosts'] = containers
    if container.get_interfaces():
        ips = container.get_ips()
        if len(ips):
            hostvars[container_name] = dict(ansible_ssh_host=ips[0])

result['all'] = containers
result['_meta'] = {'hostvars': hostvars}

if len(sys.argv) == 2 and sys.argv[1] == '--list':
    print(json.dumps(result))
elif len(sys.argv) == 3 and sys.argv[1] == '--host':
    print("TODO: SSH support")
else:
    print("Need an argument, either --list or --host <host>")

@@ -89,16 +89,158 @@
 igParser
+%0Afrom ansible.parsing.dataloader import DataLoader%0Afrom ansible.inventory.group import Group%0Afrom ansible.inventory.ini import InventoryParser
 %0A%0Aif os.
@@ -336,16 +336,102 @@
 arser()%0A
+# setting defaults%0Aconfig.add_section(%22os%22)%0Aconfig.set(%22os%22, %22inventory_file%22, None)%0A%0A
 config.r
@@ -469,16 +469,17 @@
 .ini')%0A%0A
+%0A
 result =
@@ -638,16 +638,496 @@
 ort')%7D%0A%0A
+# TODO: Handle hosts with same name%0Ainventory_file = config.get(%22os%22, %22inventory_file%22)%0Aif inventory_file:%0A    dl = DataLoader()%0A    inv = InventoryParser(dl, %7B%22ungrouped%22:Group(%22ungrouped%22), %22all%22:Group(%22all%22)%7D, inventory_file)%0A    for grp in inv.groups:%0A        if grp not in result:%0A            result%5Bgrp%5D=%7B'hosts':%5B%5D, 'vars':os_vars%7D%0A        for host in inv.groups%5Bgrp%5D.hosts:%0A            result%5Bgrp%5D%5B'hosts'%5D.append(host.name)%0A            hostvars%5Bhost.name%5D=host.vars%0A    %0A
 %0Acontain

Use inventory file from config both with lxc dynamic inventory