From db9b4575fd2921a26a8b72d6f946c777c209745d Mon Sep 17 00:00:00 2001 From: Justin Wind Date: Mon, 3 Apr 2017 11:00:50 -0700 Subject: [PATCH] group inventory by instance tags as well --- inventory/asg-inventory.py | 32 ++++++++++++++++++++++++++++++-- 1 file changed, 30 insertions(+), 2 deletions(-) diff --git a/inventory/asg-inventory.py b/inventory/asg-inventory.py index 34c6e1c..d7141b6 100755 --- a/inventory/asg-inventory.py +++ b/inventory/asg-inventory.py @@ -1,8 +1,15 @@ #!/usr/bin/env python '''\ Generate a JSON object containing the names of all the AWS Autoscaling -Groups in an account and the IPs of the Instances within them, suitable -for use as an Ansible inventory. +Groups in an account, the IDs of the Instances within them, as well +as all the Tags on those Instances, each containing a list of the IPs +of the Instances, suitable for use as an Ansible inventory. + +This output is similar to the default ec2.py inventory script, but is +far more limited in the scope of information is has to retreive, parse, +and render. + +It does not currently deal with hostvars at all. ''' import argparse @@ -58,6 +65,23 @@ def allInstanceIPs(ec2c, InstanceIds=None, publicIPs=False): return instances +def tagsOfInstances(ec2c, InstanceIds=None): + tags = {} + args = {'Filters': [{'Name': 'resource-type', 'Values': ["instance"]}]} + if InstanceIds: + args['Filters'] += [{'Name': 'resource-id', 'Values': InstanceIds}] + while True: + response = ec2c.describe_tags(**args) + for tag in response['Tags']: + tagname = "tag_{}_{}".format(tag['Key'], tag['Value']) + tagvalue = tag['ResourceId'] + tags.setdefault(tagname, []).append(tagvalue) + if 'NextToken' not in response: + break + args['NextToken'] = response['NextToken'] + return tags + + def regionInventory(sessionArgs, publicIPs=False): 'Return dict results for one region.' session = boto3.session.Session(**sessionArgs) @@ -76,6 +100,10 @@ def regionInventory(sessionArgs, publicIPs=False): # add ASG dict, replacing ASG Instance Id with instance IP inventory.update({asg:[AllInstanceIPs[iid] for iid in ASGs[asg] if iid in AllInstanceIPs] for asg in ASGs}) + # group up instance tags as well + tags = tagsOfInstances(ec2c, AllInstanceIds) + inventory.update({tag:[AllInstanceIPs[iid] for iid in tags[tag] if iid in AllInstanceIPs] for tag in tags}) + return inventory -- 2.45.2