Why is data_dirs | regex_findall('statusDescription(.*)') a poor way to extract the script output, even though it returns something?
regex_findall works on text, so Ansible first turns the whole nested result into one long Python-style string; the greedy (.*) then grabs everything from the first statusDescription to the end of that line, including the other fields and the second target.
data_dirs is a dictionary. A regex filter needs a string, so the dictionary is stringified into a single line like {'changed': True, 'run-script': {...}}. In that string:
- there are no line breaks, so
(.*)(greedy: as much as possible) runs to the very end of the data; - the match therefore starts with
': 'and containstaskNotification,gatewayId, the Base64responseMessage, and the other target's data; - the quoting is Python's, not JSON's, so it is awkward to parse again.
Regular expressions on serialised structures are fragile: any change in field order or quoting breaks them. When the data is already structured, address the field by its path instead, with json_query (or plain Jinja: item['task-details'][0].responseMessage). Keep regexes for real text, such as a line of command output.
Go deeper:
regex_findall filter (Ansible docs) โ what it returns and its options.