Issue
I have a file which has one of more entries like seen in the grep command below:
grep SSLFile /tmp/httpd.conf
Output:
SSLFile /web/certs/mycert7.crt
I wish to grab the filename 2nd column from the output i.e "/web/certs/mycert7.crt" using ansible for all entries that start with SSLFile using Ansible regex.
Below is any ansible playbook:
- 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 }}"
Unfortunately I do not get the greped string as well as got a runtime error as below:
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 }}"}
Here is the 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
I tried regex ^SSLFile and it does not even match string on https://regex101.com/
Update: Trying regexp: '\\sSSLFile.*' got the match however unable to print due to the error below.
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 }}"}
Can you please suggest what is the issue with my playbook and how can I get it to work ?
Solution
Can you try something like below.
- hosts: localhost
vars:
input : "{{ lookup('template', '/tmp/httpd.conf') }}"
target: "{{ input | regex_replace('\\sSSLFile\\s*(.*)', '\\1')}}"
tasks:
- debug:
msg: "{{target }}"
Or you can do it just with shell as below
- name: test
shell: cat /tmp/httpd.conf | grep -v '^#'| grep SSLFile | awk '{print $2}'
register: op
- debug:
msg: "{{op.stdout_lines}}"
Answered By - Smily