[英]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
-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: path: /etc/ssh/sshd_config regexp: '^PermitRootLogin(.*)$' line: 'PermitRootLogin no'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.