4

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

frlan
  • 6,950
  • 3
  • 31
  • 72
user330612
  • 2,189
  • 7
  • 33
  • 64
  • Possible duplicate of [Ansible-vault errors with "Odd-length string"](http://stackoverflow.com/questions/27787412/ansible-vault-errors-with-odd-length-string) – 030 Mar 27 '17 at 17:39
  • not a duplicate, because the ansible-vault error is a result of having the wrong line-ending, not a means of changing it – Nic Oct 15 '17 at 22:20
  • Please mark a preferred answer if inclined :) – Nic Oct 15 '17 at 22:22

3 Answers3

4

You can remove the CRLF line endings with the -replace command. Your playbook might look like:

---
- hosts: all
  tasks:
    - local_action: replace dest={{my_dir}}/conf/{{item}} regexp="\r"

By not specifying the replace parameter in the - replace command, it will just remove all carriage returns. See http://docs.ansible.com/ansible/replace_module.html.

I tested this with a local file I created and it worked when testing on localhost. It also worked when I added localhost to the /etc/ansible/hosts file and had the following playbook instead:

---
- hosts: all
  tasks:
    - replace: dest={{my_dir}}/conf/{{item}} regexp="\r"

Just be sure to use the absolute filepath.

0

You can do something like this:

set_fact:
    my_content: "{{ lookup('file', "{{my_dir}}/conf/{{item}}" ) | replace('\r\n', '\n')}}"

After this you can use the content or save in the disk.

Luiz Picanço
  • 359
  • 4
  • 9
0

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 }}'
Nic
  • 1,518
  • 12
  • 26