tomcatansiblejvmkeystoretruststore

How to add a string to file under given condition with Ansible


I'm creating an ansible playbook that it's supposed to add a string to Tomcat's setenv.sh file in order to point it to a new truststore path.

The string to add to the setenv.sh file is the following:

-Djavax.net.ssl.trustStore=/path/to/truststore -Djavax.net.ssl.trustStorePassword=pwd -Djavax.net.ssl.trustStoreType=pkcs12

Now, there are 2 possible scenarios:

  1. For the cases in which the setenv.sh file already has this string (pointing to the old truststore), I could use the REPLACE module with something like this:
    - name: Add new Truststore reference in Tomcat's setenv.sh file
      replace: 
        path: "{{ path_to_setenv.sh }}"
        regexp: '-Djavax.net.ssl.trustStore=old_truststore'
        replace: '{{ STRING }}
  1. For the cases in which the setenv.sh file does not has that string already (pointing to the old truststore), I could use the LINEINFILE module like this:
    - name: Add new Truststore reference in Tomcat's setenv.sh file
      lineinfile: 
        path: "{{ path_to_setenv.sh }}"
        line: '{{ STRING }}'
        state: present`

Now, how could I achieve both things in just one task? in case there is already a string in the file to replace it and in case there is not, to add it to the EOF, but everything in just one task, is it doable?

Thanks in advance!

What I want to achieve is to check if the string is present to replace if, and if its not to add it to the end of the file.


Solution

  • In a nutshell:

        - name: Make sure truststore ref is in Tomcat's setenv.sh file
          vars:
            truststore_regex: '-Djavax.net.ssl.trustStore=\S+ -Djavax.net.ssl.trustStorePassword=pwd -Djavax.net.ssl.trustStoreType=pkcs12'
            truststore_line: '-Djavax.net.ssl.trustStore={{ truststore_path }} -Djavax.net.ssl.trustStorePassword=pwd -Djavax.net.ssl.trustStoreType=pkcs12'
          ansible.builtin.lineinfile:
            path: "{{ path_to_setenv }}"
            regexp: "{{ truststore_regex }}"
            line: "{{ truststore_line }}"