Skip to content

Instantly share code, notes, and snippets.

@wilvk
Last active November 21, 2016 04:05
Show Gist options
  • Save wilvk/97c24e21435d442f9dc624d5dde31c9d to your computer and use it in GitHub Desktop.
Save wilvk/97c24e21435d442f9dc624d5dde31c9d to your computer and use it in GitHub Desktop.
Selects a subset of a list based on a matching regular expression
#!/usr/bin/python
DOCUMENTATION = '''
---
module: select_list_regex
short_description: Selects a subset of a list based on a matching regular expression
'''
EXAMPLES = '''
- name: Select hosts with the word Admin from a list of all hosts
select_list_regex:
regex: '.*Admin.*'
input_list: "{{ all_stacks }}"
register: result
'''
import re
from ansible.module_utils.basic import *
# WANT_JSON
def main():
fields = {
"regex": {
"required": True, "type": "str"
},
"input_list": {
"required": True, "type": "list"
},
}
module = AnsibleModule(argument_spec=fields)
regex_string = module.params["regex"]
input_list = module.params["input_list"]
match_list = []
for item in input_list:
match_regex = re.search(regex_string, item)
if match_regex is not None:
match_string = match_regex.group(0)
if len(match_string) > 0:
match_list.append(match_string)
module.exit_json(changed=True, meta=match_list)
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment