satya
satya

Reputation: 131

need to add block of lines into the text file

I need to add a block of the code into the configuration file on the remote servers if the content already exists in the conf file it should not add to the configuration file. The code is working fine when the values are fixed but the timeout value and session value changes from one server to other for example on the first server Timeout are 100 and on the second server, it is 150 in that case code is not working.

- shell: cat /tmp/httpd.conf | egrep -i "Timeout 100| session 200"| wc -l

   register: test_grep

- debug: var=test_grep.stdout

- blockinfile:
      path: /tmp/httpd.conf

      block: |

        Timeout 100
        session 200

   when test_grep.stdout == "0"

Expected value always should be

Timeout 100
Session 200

Upvotes: 0

Views: 54

Answers (1)

larsks
larsks

Reputation: 311988

One option would be to use the lineinfile module to remove any matching lines first. For example:

- lineinfile:
    path: /tmp/httpd.conf
    state: absent
    regexp: '^ *(Timeout|Session) \d+'

- blockinfile:
      path: /tmp/httpd.conf
      block: |

        Timeout 100
        Session 200

This would remove any Timeout or Session lines from the configuration, and then add your desired block. The downside to this solution is that it will always result in a change.

If you don't want that, you could potentially do this using only lineinfile, like this:

- lineinfile:
    path: /tmp/httpd.conf
    state: present
    regexp: '^ *{{ item.0 }} \d+'
    line: '{{ item.0 }} {{ item.1 }}'
  loop:
    - [Timeout, 100]
    - [Session, 200]

This has the advantage that the task won't show any changes if the file already contains the lines you want.

Upvotes: 1

Related Questions