You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从Ansible输出提取指定内容并存储为变量用于Jinja2模板

Extract Monit Status Values in Ansible for Jinja2 Templates

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.
  • | first grabs the first match (since regex_search returns 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 07:12:06