我在我的任务中尝试了这一点,但似乎无法正常工作
- name: Fix line endings from CRLF to LF
local_action: replace dest={{my_dir}}/conf/{{item}} regexp='\r\n' replace='\n'
我通常使用sed执行此操作,如下所示
sed -i 's/\r//g' file
我想避免使用shell模块进行替换,因为它会在ansible
中抛出警告答案 0 :(得分:2)
您可以使用-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
文件并改为使用以下playbook时,它也有效:
---
- hosts: all
tasks:
- replace: dest={{my_dir}}/conf/{{item}} regexp="\r"
请务必使用绝对文件路径。
答案 1 :(得分:0)
您可以这样做:
set_fact:
my_content: "{{ lookup('file', "{{my_dir}}/conf/{{item}}" ) | replace('\r\n', '\n')}}"
在此之后,您可以使用内容或保存在磁盘中。
答案 2 :(得分:0)
以下使用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:"\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 }}'