如何从Ansible输出提取指定内容并存储为变量用于Jinja2模板
Got it, here's a straightforward way to pull the status ("OK") and uptime ("3m") from sudo monit status output and store them in variables for your Jinja2 templates:
Step 1: Capture the Monit Status Output
First, run the monit status command with sudo and register the output to a variable so we can process it later:
- name: Fetch Monit status details ansible.builtin.command: sudo monit status become: true register: monit_status_result
Step 2: Extract the System Status (Variable A)
Use Ansible's regex_search filter to yank the "OK" status from the output. The regex targets the specific line with your server's system status:
- name: Set variable A with system status ansible.builtin.set_fact: var_A: "{{ monit_status_result.stdout | regex_search('System \\'server\\' status (\\w+)', '\\1') | first }}"
- The regex
System \\'server\\' status (\\w+)matches the exact line segment and captures the status word (like "OK") into a group. | firstgrabs the first match (sinceregex_searchreturns a list of matches here).
Step 3: Extract the Uptime (Variable B)
Similarly, extract the uptime value using another regex to target the "uptime: 3m" part of the output:
- name: Set variable B with Monit uptime ansible.builtin.set_fact: var_B: "{{ monit_status_result.stdout | regex_search('Monit \\d+\\.\\d+\\.\\d+ uptime: (\\d+m)', '\\1') | first }}"
- The regex
Monit \\d+\\.\\d+\\.\\d+ uptime: (\\d+m)matches the Monit version line and captures the uptime value (like "3m").
Use Variables in Jinja2 Templates
Once you've set var_A and var_B, you can reference them directly in your templates like this:
System Status: {{ var_A }} Monit Uptime: {{ var_B }}
A quick heads-up: If your server's hostname in the Monit output isn't "server", adjust the regex to match your actual hostname. Also, if the uptime format ever changes (e.g., to "1h30m"), you can tweak the regex to (\\d+[hm]) to capture both hours and minutes.
内容的提问来源于stack exchange,提问作者Romain

