Search code examples
variablesansiblersyslog

How to uncomment more than one line in Ansible?


I want to uncommnent this lines, but leaving "privides UDP/TCP..." commented:

# provides UDP syslog reception
# module(load="imudp")
# input(type="imudp" port="514")

# provides TCP syslog reception
# module(load="imudp")
# input(type="imudp" port="514")

This is my current task for uncommenting one line:

- name: Change rsyslog configuration
  lineinfile:
    dest: /etc/rsyslog.conf
    regex: '^module(load="imudp")'
    line: 'module(load="imudp")'

But how can I extend this task to uncomment more lines? I think it can be done adding variables in regex and parse values using loop with_items, but don't know how to achieve it. What is the best practice to do this?


Solution

  • Module lineinfile will place the line into the file even when regex is not matched.

    The task below

      tasks:
        - lineinfile:
            # firstmatch: true
            dest: rsyslog.conf
            regex: '^#\s*{{ item.regex }}(.*)$'
            line: '{{ item.line }}'
          loop:
            - regex: 'module\(load="imudp"\)'
              line: 'module(load="imudp")'
            - regex: 'input\(type="imudp" port="514"\)'
              line: 'input(type="imudp" port="514")'
    

    gives

    # provides UDP syslog reception
    # module(load="imudp")
    # input(type="imudp" port="514")
    
    # provides TCP syslog reception
    module(load="imudp")
    input(type="imudp" port="514")
    

    and with "firstmatch: true" gives

    # provides UDP syslog reception
    module(load="imudp")
    input(type="imudp" port="514")
    
    # provides TCP syslog reception
    # module(load="imudp")
    # input(type="imudp" port="514")
    

    The module replace will replace all instances of a pattern within the file

    - replace:
        dest: rsyslog.conf
        regexp: '^#\s*{{ item.regex }}(.*)$'
        replace: '{{ item.replace }}'
      loop:
        - regex: 'module\(load="imudp"\)'
          replace: 'module(load="imudp")'
        - regex: 'input\(type="imudp" port="514"\)'
          replace: 'input(type="imudp" port="514")'
    

    gives

    # provides UDP syslog reception
    module(load="imudp")
    input(type="imudp" port="514")
    
    # provides TCP syslog reception
    module(load="imudp")
    input(type="imudp" port="514")