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

如何用Ansible regex_replace/regex_search匹配提取状态中的OK值

Extract "OK" Status from Monit Output in Ansible

To pull the "OK" status string from your monit command output and store it in an Ansible variable, you can use either the regex_search filter (perfect for targeted extraction) or regex_replace if you prefer. Here's a step-by-step breakdown:

Step 1: Capture the Raw Monit Output

First, run the monit command and save its output to a variable:

- name: Fetch monit status for the target server
  shell: "monit status server.mylabserver.com"
  register: monit_raw_output
  changed_when: false  # Mark as no change since we're only checking status

This is the most straightforward approach for extracting specific substrings:

- name: Extract the server status value
  set_fact:
    server_status: "{{ monit_raw_output.stdout | regex_search('status (\\w+)', '\\1') | first }}"

Let’s break down the regex logic:

  • status : Matches the literal string "status " (including the space to avoid accidental matches elsewhere)
  • (\\w+): Captures one or more word characters (letters, digits, underscores) — this grabs the "OK" in your output
  • '\\1': Tells regex_search to return only the first captured group instead of the full matched string
  • | first: Pulls the first (and only) element from the list returned by regex_search

Alternative: Using regex_replace

If you want to stick with regex_replace, you can strip away all other text to isolate the status:

- name: Extract status with regex_replace
  set_fact:
    server_status: "{{ monit_raw_output.stdout | regex_replace('.*status (\\w+).*', '\\1') }}"

Here, .* matches any characters before and after the status, replacing the entire output string with just the captured "OK".

Verify the Result

Add a debug task to confirm the variable holds the correct value:

- name: Show the extracted status
  debug:
    var: server_status

You’ll see output like this:

ok: [target_host] => {
    "server_status": "OK"
}

Quick Notes

  • Make sure your Ansible user has permission to run the monit command on the target server.
  • If your status values ever include spaces (e.g., "Not Running"), adjust the regex to use (.*?) instead of (\\w+) to capture until the next delimiter.

内容的提问来源于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 08:30:38