Skip to content

Add filter_by_tags option #117

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions plugins/inventory/instance.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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:
Expand Down Expand Up @@ -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
Expand All @@ -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
Expand Down