使用 Ansible 正则表达式在文件中搜索字符串

Ash*_*har 3 regex grep ansible

我有一个文件,其中包含多个条目之一,如下面的 grep 命令所示:

grep SSLFile /tmp/httpd.conf
Output:
        SSLFile  /web/certs/mycert7.crt
Run Code Online (Sandbox Code Playgroud)

我希望使用 Ansible 正则表达式从输出中获取文件名第二列,即“/web/certs/mycert7.crt”,以获取以 SSLFile 开头的所有条目。

以下是任何 ansible 剧本:

- name: Find file
  lineinfile:
    path: "/tmp/httpd.conf"
    regexp: '^SSLFile .*'
    state: absent
  check_mode: yes
  changed_when: false
  register: getfiles

- debug:
    msg: "{{ item.split()[1] }}"
  with_items:
    - "{{ getfiles.stdout_lines }}"
Run Code Online (Sandbox Code Playgroud)

不幸的是,我没有得到 grep 字符串,也没有得到如下运行时错误:

TASK [Find file] ***************************************
task path: /app/test.yml:895
ok: [10.9.9.34] => {"backup": "", "changed": false, "found": 0, "msg": ""}

TASK [debug] *******************************************************************
task path: 
/app/test.yml:905
fatal: [10.9.9.34]: FAILED! => {"msg": "template error while templating string: unexpected char u'_' at 7. String: {{ getfiles.stdout_lines }}"}
Run Code Online (Sandbox Code Playgroud)

这是httpd.conf

<VirtualHost *:443>
        <LimitExcept GET POST>
        order deny,allow
        deny from all
        </LimitExcept>
        </Location>
        SSLCipherSuite EECDH+AESGCM:EDH+AESGCM:RSA+AESGCM:RSA+AES:!SHA:!MD5:!RC4:!3DES
        SSLHonorCipherOrder On
        SSLFile  /tmp/certs/mycert.crt
        SSLKeyFile  /tmp/certs/mycert.key
Run Code Online (Sandbox Code Playgroud)

我尝试了 regex ^SSLFile 它甚至与https://regex101.com/上的字符串不匹配

更新:尝试 regexp: '\\sSSLFile.*' 获得匹配项,但由于以下错误而无法打印。

task path: /tmp/test.yml:914
ok: [10.9.9.34] => {"backup": "", "changed": false, "found": 1, "msg": "1 line(s) removed"}

TASK [debug] *******************************************************************
task path: /tmp/test.yml:924
fatal: [10.9.9.34]: FAILED! => {"msg": "template error while templating string: unexpected char u'_' at 7. String: {{ getfiles.stdout_lines }}"}
Run Code Online (Sandbox Code Playgroud)

您能否建议我的剧本有什么问题以及如何让它发挥作用?

Smi*_*ily 5

你可以尝试像下面这样的东西吗?

- hosts: localhost
  vars:
    input : "{{ lookup('template', '/tmp/httpd.conf') }}"
    target: "{{ input | regex_replace('\\sSSLFile\\s*(.*)', '\\1')}}"

  tasks:
  - debug:
     msg: "{{target }}"
Run Code Online (Sandbox Code Playgroud)

或者你也可以使用 shell 来完成,如下所示

  - name: test
    shell: cat /tmp/httpd.conf | grep -v '^#'| grep SSLFile | awk '{print $2}'
    register: op
  - debug:
     msg: "{{op.stdout_lines}}"


Run Code Online (Sandbox Code Playgroud)