Make wait_for return matched groups defined in search_regex. Closes #… (#47690)

* Make wait_for return matched groups defined in search_regex. Closes #25020.

* Fix formatting issues.

* Fix issues raised in review.

- Use output_dir instead of hardcoded /tmp for temp files
- Sleep for only 3s instead of 10s
- Revert indent change
This commit is contained in:
Björn 2018-11-20 20:19:17 +01:00 committed by Brian Coca
parent 0886c20d19
commit 9c71f176f3
2 changed files with 76 additions and 22 deletions

View file

@ -134,6 +134,14 @@ EXAMPLES = r'''
path: /tmp/foo
search_regex: completed
- name: Wait until regex pattern matches in the file /tmp/foo and print the matched group
wait_for:
path: /tmp/foo
search_regex: completed (?P<task>\w+)
register: waitfor
- debug:
msg: Completed {{ waitfor['groupdict']['task'] }}
- name: Wait until the lock file is removed
wait_for:
path: /var/lock/file.lock
@ -176,6 +184,20 @@ elapsed:
returned: always
type: int
sample: 23
match_groups:
description: Tuple containing all the subgroups of the match as returned by U(https://docs.python.org/2/library/re.html#re.MatchObject.groups)
returned: always
type: list
sample: ['match 1', 'match 2']
match_groupdict:
description: Dictionary containing all the named subgroups of the match, keyed by the subgroup name,
as returned by U(https://docs.python.org/2/library/re.html#re.MatchObject.groupdict)
returned: always
type: dict
sample:
{
'group': 'match'
}
'''
import binascii
@ -468,6 +490,9 @@ def main():
else:
compiled_search_re = None
match_groupdict = {}
match_groups = ()
if port and path:
module.fail_json(msg="port and path parameter can not both be passed to wait_for", elapsed=0)
if path and state == 'stopped':
@ -537,8 +562,13 @@ def main():
try:
f = open(path)
try:
if re.search(compiled_search_re, f.read()):
# String found, success!
search = re.search(compiled_search_re, f.read())
if search:
if search.groupdict():
match_groupdict = search.groupdict()
if search.groups():
match_groups = search.groups()
break
finally:
f.close()
@ -630,7 +660,8 @@ def main():
module.fail_json(msg=msg or "Timeout when waiting for %s:%s to drain" % (host, port), elapsed=elapsed.seconds)
elapsed = datetime.datetime.utcnow() - start
module.exit_json(state=state, port=port, search_regex=search_regex, path=path, elapsed=elapsed.seconds)
module.exit_json(state=state, port=port, search_regex=search_regex, match_groups=match_groups, match_groupdict=match_groupdict, path=path,
elapsed=elapsed.seconds)
if __name__ == '__main__':