3

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

grep SSLFile /tmp/httpd.conf
Output:
        SSLFile  /web/certs/mycert7.crt

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

以下是任何 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 }}"

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

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 }}"}

这是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

我尝试了正则表达式 ^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 }}"}

你能建议我的剧本有什么问题吗?我怎样才能让它发挥作用?

4

1 回答 1

4

你可以试试下面这样的东西。

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

  tasks:
  - debug:
     msg: "{{target }}"

或者你可以用下面的 shell 来做

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


于 2020-01-14T11:38:39.260 回答