Search code examples
regexreplaceansibleline

How to replace a specfic line by also ignoring lines with a specific character using ansible?


Lets say this is my nginx configuration file for SSL

#ssl_certificate "/etc/pki/nginx/server.crt" 
    #ssl_certificate_key "/etc/pki/nginx/private/server.key";


    ssl_certificate /etc/pki/nginx/server.crt  
ssl_certificate_key /etc/pki/nginx/private/server.key      


#    ssl_certificate "/etc/pki/nginx/server.crt";
  #     ssl_certificate_key "/etc/pki/nginx/private/server.key" 

I want to be able to replace with ansible (lineinfile module) the uncommented ssl_certificate line

This is my code for "ssl_certificate" line

lineinfile:
       path: /etc/nginx/sites-enabled/site1
       regexp: '^ssl_certificate | ssl_certificate '
       line: 'ssl_certificate /etc/letsencrypt/ssl/site1/fullchain.crt'

For some reason this only works if the line I want to replace is set at the start of the line and it replaces the commented line from the bottom if "ssl_certificate" is separated from the "#".

Is there a way for lineinfile to ignore lines that have "#" in them?

I tried [^#] in combination with other things and insertbefore and inserafter and such but nothing works it either replaces the commented line or adds a new line at the bottom.


Solution

  • The below task works if you want to only replace a single reference in the file,

    - name: Replace the cert file
      lineinfile:
           path: /root/tmp.txt
           regexp: '^\s*ssl_certificate\s.*'
           line: 'ssl_certificate /etc/letsencrypt/ssl/site1/fullchain.crt'
    

    And if you want to replace multiple lines, you can use the following task,

    - name: Replace cert file
      replace:
            path: /root/tmp.txt
            regexp: '^\s*ssl_certificate\s.*'
            replace: 'ssl_certificate /etc/letsencrypt/ssl/site1/fullchain.crt'
    

    Update the file path accordingly.