From bb8d1168ac58c24f4b83d60a86dcdaade3b9eee1 Mon Sep 17 00:00:00 2001 From: Wayne Witzel III Date: Thu, 14 Jul 2016 22:10:39 -0400 Subject: [PATCH] Added the ability to filter gce grouped_instances by region/zone (#14138) --- contrib/inventory/gce.py | 20 ++++++++++++++++++-- 1 file changed, 18 insertions(+), 2 deletions(-) diff --git a/contrib/inventory/gce.py b/contrib/inventory/gce.py index 307d6efa2cc..ff2feeb1cc4 100755 --- a/contrib/inventory/gce.py +++ b/contrib/inventory/gce.py @@ -125,8 +125,10 @@ class GceInventory(object): pretty=self.args.pretty)) sys.exit(0) + zones = self.parse_env_zones() + # Otherwise, assume user wants all instances grouped - print(self.json_format_dict(self.group_instances(), + print(self.json_format_dict(self.group_instances(zones), pretty=self.args.pretty)) sys.exit(0) @@ -233,6 +235,14 @@ class GceInventory(object): ) return gce + def parse_env_zones(self): + '''returns a list of comma seperated zones parsed from the GCE_ZONE environment variable. + If provided, this will be used to filter the results of the grouped_instances call''' + import csv + reader = csv.reader([os.environ.get('GCE_ZONE',"")], skipinitialspace=True) + zones = [r for r in reader] + return [z for z in zones[0]] + def parse_cli_args(self): ''' Command line argument processing ''' @@ -289,7 +299,7 @@ class GceInventory(object): except Exception as e: return None - def group_instances(self): + def group_instances(self, zones=None): '''Group all instances''' groups = {} meta = {} @@ -312,6 +322,12 @@ class GceInventory(object): meta["hostvars"][name] = self.node_to_dict(node) zone = node.extra['zone'].name + + # To avoid making multiple requests per zone + # we list all nodes and then filter the results + if zones and zone not in zones: + continue + if groups.has_key(zone): groups[zone].append(name) else: groups[zone] = [name]