From 259b05dd8e706d1e3b548f72481cea74c3ecc6d6 Mon Sep 17 00:00:00 2001 From: Ilya Kalinin Date: Fri, 17 Jul 2015 15:51:46 -0700 Subject: [PATCH] [cloud] Add stack_filters option to EC2 inventory script --- contrib/inventory/ec2.ini | 4 ++++ contrib/inventory/ec2.py | 16 ++++++++++++++-- 2 files changed, 18 insertions(+), 2 deletions(-) diff --git a/contrib/inventory/ec2.ini b/contrib/inventory/ec2.ini index ff0d8a276b..4a565979e1 100644 --- a/contrib/inventory/ec2.ini +++ b/contrib/inventory/ec2.ini @@ -153,6 +153,10 @@ group_by_elasticache_replication_group = True # Filters are key/value pairs separated by '=', to list multiple filters use # a list separated by commas. See examples below. +# If you want to apply multiple filters simultaneously, uncomment and set to True. +# Default behaviour is to apply filters one by one and concatenate results. +stack_filters = False + # Retrieve only instances with (key=value) env=staging tag # instance_filters = tag:env=staging diff --git a/contrib/inventory/ec2.py b/contrib/inventory/ec2.py index 50c002abf2..6c40bf6ea8 100755 --- a/contrib/inventory/ec2.py +++ b/contrib/inventory/ec2.py @@ -454,6 +454,12 @@ class Ec2Inventory(object): except configparser.NoOptionError: self.pattern_exclude = None + # Do we want to stack multiple filters? + if config.has_option('ec2', 'stack_filters'): + self.stack_filters = config.getboolean('ec2', 'stack_filters') + else: + self.stack_filters = False + # Instance filters (see boto and EC2 API docs). Ignore invalid filters. self.ec2_instance_filters = defaultdict(list) if config.has_option('ec2', 'instance_filters'): @@ -541,8 +547,14 @@ class Ec2Inventory(object): conn = self.connect(region) reservations = [] if self.ec2_instance_filters: - for filter_key, filter_values in self.ec2_instance_filters.items(): - reservations.extend(conn.get_all_instances(filters = { filter_key : filter_values })) + if self.stack_filters: + filters_dict = {} + for filter_key, filter_values in self.ec2_instance_filters.items(): + filters_dict[filter_key] = filter_values + reservations.extend(conn.get_all_instances(filters = filters_dict)) + else: + for filter_key, filter_values in self.ec2_instance_filters.items(): + reservations.extend(conn.get_all_instances(filters = { filter_key : filter_values })) else: reservations = conn.get_all_instances()