如何用Ansible regex_replace/regex_search匹配提取状态中的OK值
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
Step 2: Extract "OK" Using regex_search
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': Tellsregex_searchto return only the first captured group instead of the full matched string| first: Pulls the first (and only) element from the list returned byregex_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

