Kevin Keane
Kevin Keane

Reputation: 1658

In Ansible, how to move an existing line to the end of a file?

I am looking for a way in Ansible (2.9) to move a line in a text file to the end of the file.

line 1
line 2
line at end of file
line 3
line 4

should become

line 1
line 2
line 3
line 4
line at end of file

The lineinfile module can add a new line to the end, but if the line already exists, it will not move it.

# This does not move an existing line
- name: Move line to end of file
  lineinfile:
    path: /etc/myfile
    line: 'line at end of file'
    insertafter: EOF

My current solution is to first remove the line, and then re-add it, but this is of course not idempotent, and causes two changes on each run.

Upvotes: 2

Views: 809

Answers (1)

Vladimir Botka
Vladimir Botka

Reputation: 68189

There are more options to make the procedure idempotent. Put the tasks into a file, and include them only when needed. For example

 - shell: '[ "$(tail -1 myfile)" = "line at end of file" ] && echo OK || echo KO'
   changed_when: false
   register: result
 - include_tasks: move_line.yml
   when: result.stdout == 'KO'

This solution doesn't care about the body if the last line is alright.


The next option is to edit the file on your own. For example

 - command: cat myfile
   changed_when: false
   register: result
 - copy:
     dest: myfile
     content: |
       {% for line in lines %}
       {{ line }}
       {% endfor %}
       line at end of file
   vars:
     lines: "{{ result.stdout_lines|
                difference(['line at end of file']) }}"

Upvotes: 1

Related Questions