From 908e54db68b7bdf1129416c9c3450e259389973f Mon Sep 17 00:00:00 2001 From: Markus Opolka Date: Mon, 12 Dec 2022 11:06:54 +0100 Subject: [PATCH] Add filter_by_tags option - This option allows the inventory instances to be filtered by one or more tags. --- plugins/inventory/instance.py | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/plugins/inventory/instance.py b/plugins/inventory/instance.py index 9d579ba0..ab692a35 100644 --- a/plugins/inventory/instance.py +++ b/plugins/inventory/instance.py @@ -45,6 +45,9 @@ filter_by_vpc: description: Only return instances in the provided VPC. type: string + filter_by_tags: + description: Only return instances with the provided tags. + type: dict extends_documentation_fragment: - constructed - ngine_io.cloudstack.cloudstack @@ -64,6 +67,10 @@ filter_by_vpc: vpc1 filter_by_zone: EU +# Return only instances with the tier:dev tag +filter_by_tags: + - tier: dev + # Group instances with a disk_offering as storage # Create a group dmz for instances connected to the dmz network groups: @@ -243,6 +250,14 @@ def normalize_instance_data(self, instance): inventory_instance = yaml.load(inventory_instance_str, Loader=yaml.FullLoader) return inventory_instance['instance'] + def filter_instance_by_tags(self, instance={}, filter_tags=[]): + # Matches the instances tags with the filter tags + # Returns false if one tag doesn't match + for tag in filter_tags: + if not tag.items() <= instance.get('tags', {}).items(): + return False + return True + def parse(self, inventory, loader, path, cache=False): # call base method to ensure properties are available for use with other helper methods @@ -263,6 +278,11 @@ def parse(self, inventory, loader, path, cache=False): # Retrieve the filtered list of instances instances = self.query_api('listVirtualMachines', **self.get_filters()) + # Filter instances by tags if filter_by_tags is defined + filter_tags = self.get_option('filter_by_tags') + if filter_tags: + instances = [i for i in instances if filter_instance_by_tags(self.normalize_instance_data(i), filter_tags)] + for instance in instances: # we normalize the instance data using the embedded J2 template