Skip to content

Commit

Permalink
Add an expand_csv_tags filter
Browse files Browse the repository at this point in the history
  • Loading branch information
flowerysong committed Jul 2, 2020
1 parent a2b775e commit 72f998e
Show file tree
Hide file tree
Showing 3 changed files with 45 additions and 4 deletions.
Empty file added plugins/filter/__init__.py
Empty file.
29 changes: 29 additions & 0 deletions plugins/filter/expand_csv_tags.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
# Copyright (c) 2020 Paul Arthur
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)

from __future__ import (absolute_import, division, print_function)
__metaclass__ = type

from ansible.errors import AnsibleFilterError
from ansible.module_utils.common._collections_compat import Mapping


def expand_csv_tags(mydict, separator=','):
''' Takes a dictionary and transforms it into a list of key_value strings,
possibly after splitting the value using the supplied separator. '''

if not isinstance(mydict, Mapping):
raise AnsibleFilterError("expand_csv_tags requires a dictionary, got %s instead." % type(mydict))

ret = []

for key in mydict:
for val in mydict[key].split(separator):
ret.append('{0}_{1}'.format(key, val))

return ret


class FilterModule(object):
def filters(self):
return { 'expand_csv_tags': expand_csv_tags }
20 changes: 16 additions & 4 deletions plugins/inventory/aws_ec2.py
Original file line number Diff line number Diff line change
Expand Up @@ -120,26 +120,38 @@
keyed_groups:
# Add e.g. x86_64 hosts to an arch_x86_64 group
- prefix: arch
key: 'architecture'
key: architecture
# Add hosts to tag_Name_Value groups for each Name/Value tag pair
- prefix: tag
key: tags
# Add hosts to tag_Name_Value groups for each Name/Value tag pair,
# expanding comma-separated Values into multiple groups.
- prefix: tag
key: tags | amazon.aws.expand_csv_tags
# Add hosts to e.g. instance_type_z3_tiny
- prefix: instance_type
key: instance_type
# Create security_groups_sg_abcd1234 group for each SG
- key: 'security_groups|json_query("[].group_id")'
prefix: 'security_groups'
- key: security_groups | map(attribute='group_id')
prefix: security_groups
# Create a group for each value of the Application tag
- key: tags.Application
separator: ''
# Create a group per region e.g. aws_region_us_east_2
- key: placement.region
prefix: aws_region
# Create a group (or groups) based on the value of a custom tag "Role" and add them to a metagroup called "project"
- key: tags['Role']
prefix: foo
parent_group: "project"
parent_group: project
# Set individual variables with compose
compose:
# Use the private IP address to connect to the host
Expand Down

0 comments on commit 72f998e

Please sign in to comment.