ansibledos2unix

Ansible lineinfile adding ^M to end of lines?


I am using ansible's lineinfile to update a file.

Once I've updated the file - which works - the file has ^M chars at the end of every line.

This behaviour is undesirable - how do I turn it off? It seems counter intuitive that I would then need to dos2unix in order to rectify?

- name: Update database.php - username
  lineinfile:
    dest: /var/www/html/database.php
    regexp: '^\$username.*$'
    line: "$username = '{{ mariadb_rc_user }}';"
    backrefs: yes

edit note Template and copy are possible but difficult to use in this situation for reasons I wont go into, but suffice to say: I'd use them if it made sense.


Solution

  • I found the answer and it was the opposite of what I expected. Neither lineinfile nor replace (see the duplicate link for a suggested solution) were the issue. In fact, they were doing their respective jobs - and ending lines with a line feed.

    The problem arises because before that the file only has CLRF terminators, which are invisible when they exist exclusively.

    When an LF is introduced, the CRLF (^M) is printed in vim to distinguish that there are now two types of line terminations.