我在任务中尝试过这个,但似乎不起作用
- name: Fix line endings from CRLF to LF
local_action: replace dest={{my_dir}}/conf/{{item}} regexp='rn' replace='n'
我通常使用 sed 如下方式执行此操作,它可以工作
sed -i 's/r//g' file
我想避免使用 shell 模块进行此替换,因为它会在 ansible 中引发警告
-replace
命令删除 CRLF 行尾。您的行动手册可能如下所示:
---
- hosts: all
tasks:
- local_action: replace dest={{my_dir}}/conf/{{item}} regexp="r"
通过在 - replace
命令中不指定 replace
参数,它只会删除所有回车符。请参阅 http://docs.ansible.com/ansible/replace_module.html。
用我创建的本地文件对此进行了测试,它在 localhost 上测试时有效。当我将 localhost 添加到 /etc/ansible/hosts
文件中并改用以下剧本时,它也起作用:
---
- hosts: all
tasks:
- replace: dest={{my_dir}}/conf/{{item}} regexp="r"
只需确保使用绝对文件路径即可。
你可以做这样的事情:
set_fact:
my_content: "{{ lookup('file', "{{my_dir}}/conf/{{item}}" ) | replace('rn', 'n')}}"
在此之后,您可以使用内容或保存在磁盘中。
Jinja2 模板引擎转换行尾。行尾指令插入到 ansible 机器上源文件的开头 ( delegate_to: localhost
)。然后,可以通过对文件应用template
或win_template
将文件发送到下游服务器。
它处理具有任何行尾的源文件,如果您正在处理来自多个源的文件列表,这可能很有用。
- 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:"rn"'
delegate_to: localhost
- name: copy changed file with correct line-endings
template: # win_template for Linux to Windows
src: '{{ src_file }}'
dest: '{{ dest_file }}'