How to replace Windows-style CR/LF line endings with Linux-style endings in ansible?

Viewed 6027

I tried this in my task, but doesn't seem to work

- name: Fix line endings from CRLF to LF
  local_action: replace dest={{my_dir}}/conf/{{item}} regexp='\r\n' replace='\n'

I usually do this using sed as follows and it works

sed -i 's/\r//g' file

I want to avoid using shell module to do this replacement as it throws a warning in ansible

3 Answers

The following converts line endings using the Jinja2 template engine. A line-ending directive is inserted at the beginning of the source file on the ansible machine (delegate_to: localhost). Sending the file to the downstream server can then be done by applying template or win_template to the file.

It handles source files with any line-ending, which could be useful if you're working through a list of files from more than one origin.

- name: prepare to add line endings
  lineinfile:
    insertbefore: BOF
    dest: '{{ src_file }}'
    line: '#jinja2: newline_sequence:"\n"'
    #for Linux to Windows: #line: '#jinja2: newline_sequence:"\r\n"'
  delegate_to: localhost

- name: copy changed file with correct line-endings
  template: # win_template for Linux to Windows
    src: '{{ src_file }}'
    dest: '{{ dest_file }}'
Related