i have a following String that i get with Ansible debug module:
{
"ansible_facts": {
"discovered_interpreter_python": "/usr/libexec/platform-python"
},
"changed": true,
"cmd": [
"check"
],
"stderr_lines": [],
"stdout": "QMNAME(XXXXXX) STATUS(Running)",
"stdout_lines": [
"QMNAME(XXXXXX) STATUS(Running)"
]
}
The 'XXXXXXXX' varieties from server to server.
How can i get it?
i need to reuse it as part of systemd module:
- name: Check Status of the Services
systemd:
name: "{{ item }}"
state: started
with_items:
- "my-{{ server.stdout | regex_search('\\(([^()] )\\)', '\\1') | trim }}-server"
when: ('server' in group_names)
i have tried to trim it and cut it but since the size differs i get to less or to much.
- name: Check my_Server output
debug:
msg: "{{ server.stdout[7:-48] | trim }}"
failed_when: "'STATUS(Running)' not in server.stdout"
when: ('server' in group_names)
CodePudding user response:
You can use the following to get the first string between parentheses excluding the parentheses themselves:
{{ server.stdout | regex_search('\\(([^()] )\\)', '\\1') | trim }}
{{ server.stdout | regex_search('\\(([^()] )\\)', '\\1') | list | first | trim }}
The \(([^()] )\)
pattern matches a (
first, then one or more chars other than (
and )
(that are captured into Group 1, hence the \1
later), and then a )
char is matched, but not captured.
Using trim
is still fine since the captured substring may still contain whitespace at the start and end.
To get multiple matches use
{{ server.stdout | regex_findall('\\(\\s*([^()]*?)\\s*\\)') }}
The \(\s*([^()]*?)\s*\)
matches
\(
- a(
char\s*
- zero or more whitespaces([^()]*?)
- Group 1 (the return result ofregex_findall
): any zero or more chars other than(
and)
as few as possible (so that the subsequent\s*
could consume all whitespace chars before)
)\s*
- zero or more whitespaces\)
- a)
char.