summaryrefslogtreecommitdiffstats
path: root/bin/ansibleutil.py
blob: f5f699918c0e19761e180e058ecc16b6582ec36f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
# vim: expandtab:tabstop=4:shiftwidth=4

import subprocess
import sys
import os
import json
import re

class AnsibleUtil(object):
    def __init__(self):
        self.file_path = os.path.join(os.path.dirname(os.path.realpath(__file__)))
        self.multi_ec2_path = os.path.realpath(os.path.join(self.file_path, '..','inventory','multi_ec2.py'))

    def get_inventory(self,args=[]):
        cmd = [self.multi_ec2_path]

        if args:
            cmd.extend(args)

        env = os.environ

        p = subprocess.Popen(cmd, stderr=subprocess.PIPE,
                         stdout=subprocess.PIPE, env=env)

        out,err = p.communicate()

        if p.returncode != 0:
            raise RuntimeError(err)

        return json.loads(out.strip())

    def get_environments(self):
        pattern = re.compile(r'^tag_environment_(.*)')

        envs = []
        inv = self.get_inventory()
        for key in inv.keys():
            m = pattern.match(key)
            if m:
                envs.append(m.group(1))

        return envs

    def get_security_groups(self):
        pattern = re.compile(r'^security_group_(.*)')

        groups = []
        inv = self.get_inventory()
        for key in inv.keys():
            m = pattern.match(key)
            if m:
                groups.append(m.group(1))

        return groups

    def build_host_dict(self, args=[]):
        inv = self.get_inventory(args)

        inst_by_env = {}
        for dns, host in inv['_meta']['hostvars'].items():
            if host['ec2_tag_environment'] not in inst_by_env:
                inst_by_env[host['ec2_tag_environment']] = {}
            host_id = "%s:%s" % (host['ec2_tag_Name'],host['ec2_id'])
            inst_by_env[host['ec2_tag_environment']][host_id] = host


        return inst_by_env


    def get_hostnames(self, args=[]):
        inv = self.get_inventory(args)

        import collections
        hostnames = collections.defaultdict(list)

        for dns, host in inv['_meta']['hostvars'].items():
            hostnames['ec2_tag_Name'].append(host['ec2_id'])

        return hostnames

    def get_host_ids(self, args=[]):
        inv = self.get_inventory(args)

        ids = {}

        for dns, host in inv['_meta']['hostvars'].items():
            ids['ec2_id'] = host

        return ids