In Ansible, how to move a line into a block?

Viewed 162

I have a situation where I would like to include an existing line in a text file into a new block.

line 1
line 2
line in block
line 3
line 4

should become

line 1
line 2
line 3
line 4
# BEGIN MyBlock
line in block
other line in block
# END MyBlock

Creating the block of course involves the blockinfile module:

- blockinfile:
    path: /etc/myfile
    marker: "# {mark} MyBlock"
    block: |
      line in block
      other line in block

The lineinfile could be used to remove a line:

- lineinfile:
    path: /etc/myfile
    line: 'line in block'
    state: absent

But this solution may remove the line within the block, instead of the original one.

1 Answers

Execute both the lineinfile AND the blockinfile in a row. The first one will remove it and the second one will include it. In the end, it will be in the right place. Dirtier than it could be, but it works.

Update: In that case a working idempotent solution would be:

  - name: Slurp file
    slurp:
      src: myfile
    register: myfile

  - name: Remove line if not in block
    lineinfile:
      path: myfile
      line: 'line in block'
      state: absent
    when: >
      not (myfile.content
           | b64decode
           | regex_search('# BEGIN MyBlock(\n.*)*\nline in block(\n.*)*\n# END MyBlock'))

  - name: Add block
    blockinfile:
      path: myfile
      marker: "# {mark} MyBlock"
      block: |
        line in block
        other line in block
Related