1#!/usr/bin/env python
2#
3# (c) 2015-16 Florian Haas, hastexo Professional Services GmbH
4# <florian@hastexo.com>
5# Based in part on:
6# libvirt_lxc.py, (c) 2013, Michael Scherer <misc@zarb.org>
7#
8# This file is part of Ansible,
9#
10# Ansible is free software: you can redistribute it and/or modify
11# it under the terms of the GNU General Public License as published by
12# the Free Software Foundation, either version 3 of the License, or
13# (at your option) any later version.
14#
15# Ansible is distributed in the hope that it will be useful,
16# but WITHOUT ANY WARRANTY; without even the implied warranty of
17# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18# GNU General Public License for more details.
19#
20# You should have received a copy of the GNU General Public License
21# along with Ansible.  If not, see <http://www.gnu.org/licenses/>.
22"""
23Ansible inventory script for LXC containers. Requires Python
24bindings for LXC API.
25
26In LXC, containers can be grouped by setting the lxc.group option,
27which may be found more than once in a container's
28configuration. So, we enumerate all containers, fetch their list
29of groups, and then build the dictionary in the way Ansible expects
30it.
31"""
32from __future__ import print_function
33
34import sys
35import lxc
36import json
37
38
39def build_dict():
40    """Returns a dictionary keyed to the defined LXC groups. All
41    containers, including the ones not in any group, are included in the
42    "all" group."""
43    # Enumerate all containers, and list the groups they are in. Also,
44    # implicitly add every container to the 'all' group.
45    containers = dict([(c,
46                        ['all'] +
47                        (lxc.Container(c).get_config_item('lxc.group') or []))
48                       for c in lxc.list_containers()])
49
50    # Extract the groups, flatten the list, and remove duplicates
51    groups = set(sum([g for g in containers.values()], []))
52
53    # Create a dictionary for each group (including the 'all' group
54    return dict([(g, {'hosts': [k for k, v in containers.items() if g in v],
55                      'vars': {'ansible_connection': 'lxc'}}) for g in groups])
56
57
58def main(argv):
59    """Returns a JSON dictionary as expected by Ansible"""
60    result = build_dict()
61    if len(argv) == 2 and argv[1] == '--list':
62        json.dump(result, sys.stdout)
63    elif len(argv) == 3 and argv[1] == '--host':
64        json.dump({'ansible_connection': 'lxc'}, sys.stdout)
65    else:
66        print("Need an argument, either --list or --host <host>", file=sys.stderr)
67
68
69if __name__ == '__main__':
70    main(sys.argv)
71