簡體   English   中英

Ansible - 使用正則表達式檢查文件中是否存在字符串

[英]Ansible - Check if string exists in file with regex

我需要驗證PermitRootLogin參數是否等於“否”,例如:

PermitRootLogin no

但有時這些詞之間有不止一個空格。 出於這個原因,我使用了正則表達式,但顯然我做錯了。 這是似乎不好的行:

when: check_config.stdout.find('PermitRootLogin\s+no') != -1

知道如何解決這個問題嗎?

- hosts: redhat
  tasks:

  - name: check file
    shell: cat /etc/ssh/sshd_config
    register: check_config

  - name: compare string 
    when: check_config.stdout.find('PermitRootLogin\s+no') != -1
    debug: msg="this server is ok"

問: “驗證PermitRootLogin參數等於no 。”

A: 將下面的聲明放入vars

match_lines: "{{ check_config.stdout_lines|
                 map('regex_search', '^\\s*PermitRootLogin\\s+no$')|
                 select }}"

並測試列表的長度

    - debug:
        msg: this server is OK
      when: match_lines|length > 0

  • 用於測試的完整劇本示例
- hosts: localhost vars: match_lines: "{{ check_config.stdout_lines| map('regex_search', '^\\s*PermitRootLogin\\s+no$')| select }}" tasks: - command: cat /etc/ssh/sshd_config register: check_config - debug: var: match_lines - debug: msg: This server is OK when: match_lines|length > 0

給出,例如(刪節)

 TASK [debug] ******************************************* ok: [localhost] => match_lines: - PermitRootLogin no TASK [debug] ******************************************* ok: [localhost] => msg: This server is OK

  • 給定以下清單 set hosts -hosts: rehat
 shell> cat hosts [redhat] test_11 test_12 test_13

該劇本給出了例如(刪節)

 TASK [debug] ******************************************* ok: [test_11] => match_lines: - PermitRootLogin no ok: [test_12] => match_lines: [] ok: [test_13] => match_lines: [] TASK [debug] ******************************************* skipping: [test_12] ok: [test_11] => msg: This server is OK skipping: [test_13]

  • 如果播放僅在本地主機上運行,您可以使用查找來簡化任務。 例如,下面的劇本給出了相同的結果
- hosts: localhost tasks: - debug: msg: This server is OK when: match_lines|length > 0 vars: match_lines: "{{ lookup('file', '/etc/ssh/sshd_config').splitlines()| map('regex_search', '^\\s*PermitRootLogin\\s+no$')| select }}"

  • 如果您想在配置中放置/替換該行,請使用lineinfile 例如,
 - lineinfile: path: /etc/ssh/sshd_config regexp: '^PermitRootLogin(.*)$' line: 'PermitRootLogin no'

暫無
暫無

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

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