1#!/usr/bin/env python
2"""
3fleetctl base external inventory script. Automatically finds the IPs of the booted coreos instances and
4returns it under the host group 'coreos'
5"""
6
7# Copyright (C) 2014  Andrew Rothstein <andrew.rothstein at gmail.com>
8#
9# This program is free software: you can redistribute it and/or modify
10# it under the terms of the GNU General Public License as published by
11# the Free Software Foundation, either version 3 of the License, or
12# (at your option) any later version.
13#
14# This program is distributed in the hope that it will be useful,
15# but WITHOUT ANY WARRANTY; without even the implied warranty of
16# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17# GNU General Public License for more details.
18#
19# You should have received a copy of the GNU General Public License
20# along with this program.  If not, see <http://www.gnu.org/licenses/>.
21
22#
23# Thanks to the vagrant.py inventory script for giving me the basic structure
24# of this.
25#
26
27import sys
28import subprocess
29import re
30import string
31from optparse import OptionParser
32import json
33
34# Options
35# ------------------------------
36
37parser = OptionParser(usage="%prog [options] --list | --host <machine>")
38parser.add_option('--list', default=False, dest="list", action="store_true",
39                  help="Produce a JSON consumable grouping of servers in your fleet")
40parser.add_option('--host', default=None, dest="host",
41                  help="Generate additional host specific details for given host for Ansible")
42(options, args) = parser.parse_args()
43
44#
45# helper functions
46#
47
48
49def get_ssh_config():
50    configs = []
51    for box in list_running_boxes():
52        config = get_a_ssh_config(box)
53        configs.append(config)
54    return configs
55
56
57# list all the running instances in the fleet
58def list_running_boxes():
59    boxes = []
60    for line in subprocess.check_output(["fleetctl", "list-machines"]).split('\n'):
61        matcher = re.search(r"[^\s]+[\s]+([^\s]+).+", line)
62        if matcher and matcher.group(1) != "IP":
63            boxes.append(matcher.group(1))
64
65    return boxes
66
67
68def get_a_ssh_config(box_name):
69    config = {}
70    config['Host'] = box_name
71    config['ansible_ssh_user'] = 'core'
72    config['ansible_python_interpreter'] = '/opt/bin/python'
73    return config
74
75
76# List out servers that vagrant has running
77# ------------------------------
78if options.list:
79    ssh_config = get_ssh_config()
80    hosts = {'coreos': []}
81
82    for data in ssh_config:
83        hosts['coreos'].append(data['Host'])
84
85    print(json.dumps(hosts))
86    sys.exit(1)
87
88# Get out the host details
89# ------------------------------
90elif options.host:
91    result = {}
92    ssh_config = get_ssh_config()
93
94    details = filter(lambda x: (x['Host'] == options.host), ssh_config)
95    if len(details) > 0:
96        # pass through the port, in case it's non standard.
97        result = details[0]
98
99    print(json.dumps(result))
100    sys.exit(1)
101
102
103# Print out help
104# ------------------------------
105else:
106    parser.print_help()
107    sys.exit(1)
108