繁体   English   中英

如何在ansible中用Linux风格的结尾替换Windows风格的CR / LF线路结尾?

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

我在我的任务中试过这个,但似乎没有用

- 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中发出警告

您可以使用-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"

请务必使用绝对文件路径。

你可以这样做:

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

在此之后,您可以使用内容或保存在磁盘中。

以下内容使用Jinja2模板引擎转换行结尾。 在ansible机器( delegate_to: localhost )上的源文件的开头插入一个行结束指令。 然后可以通过将templatewin_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 }}'

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM