Ansible: replace one line of code in multiple files in a directory

We are going to use lineinfile module and register statement.

Task that ‘ls’ the directory, and store in register statement.

- name: list of the .conf files and store it in register
  raw: find /etc/httpd/conf.d -type f -name "*.conf"
  register: certs_dir
  tags: update-cert

Task that replace one line on every *.conf file.

- name: update certs with the new name in *conf
  lineinfile: dest={{item}} backup=yes state=present regexp="^  SSLCertificateFile" insertafter="^  SSLCertificateFile" line="  SSLCertificateFile      /etc/pki/tls/certs/new_cert.cer"
  with_items: certs_dir.stdout_lines
  tags: update-cert

Test

ansible-playbook -i hosts sites.yaml -u root --ask-pass --tags update-cert

Leave a comment