lifecycle_inventory.py 2.85 KB
Newer Older
e0d committed
1 2
#!/usr/bin/env python

e0d committed
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
"""
Build an ansible inventory based on autoscaling group instance lifecycle state.

Outputs JSON to stdout with keys for each state and combination of autoscaling
group and state.

{
  "InService": [
    "10.0.47.127",
    "10.0.46.174"
  ],
  "Terminating:Wait": [
    "10.0.48.104"
  ],
  "e-d-CommonClusterServerAsGroup": [
    "10.0.47.127",
    "10.0.46.174"
  ],
  "e-d-CommonClusterServerAsGroup_InService": [
    "10.0.47.127",
    "10.0.46.174"
  ],
  "e-d-CommonClusterServerAsGroup_InService": [
    "10.0.48.104"
  ]

}
"""
e0d committed
31
import argparse
32
import boto3
e0d committed
33
import json
e0d committed
34
from collections import defaultdict
35
from os import environ
e0d committed
36 37 38

class LifecycleInventory():

39
    def __init__(self, region):
e0d committed
40
        parser = argparse.ArgumentParser()
41
        self.region = region
e0d committed
42

e0d committed
43 44 45 46 47
    def get_e_d_from_tags(self, group):

        environment = "default_environment"
        deployment = "default_deployment"

48 49 50 51 52
        for r in group['Tags']:
            if r['Key'] == "environment":
                environment = r['Value']
            elif r['Key'] == "deployment":
                deployment = r['Value']
e0d committed
53 54
        return environment,deployment

e0d committed
55
    def get_instance_dict(self):
56 57
        ec2 = boto3.client('ec2', region_name=self.region)
        reservations = ec2.describe_instances()['Reservations']
e0d committed
58 59 60

        dict = {}

61 62
        for instance in [i for r in reservations for i in r['Instances']]:
            dict[instance['InstanceId']] = instance
e0d committed
63 64 65 66

        return dict

    def run(self):
67 68 69
        asg = boto3.client('autoscaling', region_name=self.region)
    
        groups = asg.describe_auto_scaling_groups()['AutoScalingGroups']
e0d committed
70 71

        instances = self.get_instance_dict()
e0d committed
72
        inventory = defaultdict(list)
e0d committed
73 74 75

        for group in groups:

76
            for instance in group['Instances']:
e0d committed
77

78
                private_ip_address = instances[instance['InstanceId']]['PrivateIpAddress']
79
                if private_ip_address:
e0d committed
80
                    environment,deployment = self.get_e_d_from_tags(group)
81 82 83 84
                    inventory[environment + "_" + deployment + "_" + instance['LifecycleState'].replace(":","_")].append(private_ip_address)
                    inventory[group['AutoScalingGroupName']].append(private_ip_address)
                    inventory[group['AutoScalingGroupName'] + "_" + instance['LifecycleState'].replace(":","_")].append(private_ip_address)
                    inventory[instance['LifecycleState'].replace(":","_")].append(private_ip_address)
e0d committed
85 86 87

        print json.dumps(inventory, sort_keys=True, indent=2)

e0d committed
88 89 90
if __name__=="__main__":

    parser = argparse.ArgumentParser()
91
    parser.add_argument('-r', '--region', help='The aws region to use when connecting.', default='us-east-1')
e0d committed
92
    parser.add_argument('-l', '--list', help='Ansible passes this, we ignore it.', action='store_true', default=True)
e0d committed
93
    args = parser.parse_args()
94 95


96
    LifecycleInventory(args.region).run()