簡體   English   中英

Ansible regex_replace或regex_search

[英]Ansible regex_replace or regex_search

我正在嘗試將以下輸出中的“ OK”與正則表達式進行匹配,並將其存儲在變量中:

System 'server.mylabserver.com'
  status                       OK
  monitoring status            Monitored
  monitoring mode              active
  on reboot                    start
  load average                 [0.00] [0.01] [0.05]
  cpu                          0.1%us 0.1%sy 0.0%wa
  memory usage                 367.9 MB [20.0%]
  swap usage                   0 B [0.0%]
  uptime                       2h 10m
  boot time                    Mon, 02 Apr 2018 06:51:01
  data collected               Mon, 02 Apr 2018 09:01:02

我嘗試過的帶有“ regex_replace”的Ansible代碼:

  - name: Fetch the monit status
    shell: "monit status | tail -n +3"
    register: monit_status_raw
    tags: basic_monitoring
  - name: Extract monit variables
    set_fact:
        vmstatus: "{{ monit_status_raw | regex_replace('^\s\s([a-z]*)\s+', '\\1:')}}"

錯誤:

The offending line appears to be:

    set_fact:
       vmstatus: "{{ monit_status_raw | regex_replace('^\s\s([a-z]*)\s+', '\\1')}}"
                                                        ^ here
We could be wrong, but this one looks like it might be an issue with
missing quotes.  Always quote template expression brackets when they
start a value. For instance:

    with_items:
      - {{ foo }}

Should be written as:

    with_items:
      - "{{ foo }}"

我嘗試過的帶有“ regex_search”的Ansible代碼:

- name: Fetch the monit status
  shell: "monit status | tail -n +3"
  register: monit_status_raw
- name: Extract monit variables
  set_fact:
     vmstatus: "{{ monit_status_raw | regex_search('^\s\sstatus\s+(.*)$') }}"

錯誤:

The offending line appears to be:

    set_fact:
      vmstatus: "{{ monit_status_raw | regex_search('^\s\sstatus\s+(.*)$') }}"
                                                      ^ here
We could be wrong, but this one looks like it might be an issue with
missing quotes.  Always quote template expression brackets when they
start a value. For instance:

    with_items:
      - {{ foo }}

Should be written as:

    with_items:
      - "{{ foo }}"

知道正則表達式有什么問題嗎?

謝謝丹

我認為,如果您想使用regexp_search-您需要提供一個字符串並考慮轉義字符,然后需要使用以下構造:

with_items
  - "{{ monit_status_raw.stdout_lines }}"

但我認為這會更簡單:

- name: Fetch the monit status
  shell: 'monit status | tail -n +2 | grep "^\s*status" '
  register: monit_status_raw
- set_fact:
    vmstatus: "{{ monit_status_raw.stdout.split('status')[1]| replace(' ','')}}"

如果使用示例,將獲得vmstatus ='Ok'。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM