community.windows.win_lineinfile 模块 – 确保文件中存在特定行,或使用反向引用的正则表达式替换现有行
注意
此模块是 community.windows 集合(版本 2.3.0)的一部分。
如果您正在使用 ansible
包,您可能已经安装了此集合。它不包含在 ansible-core
中。要检查是否已安装,请运行 ansible-galaxy collection list
。
要安装它,请使用:ansible-galaxy collection install community.windows
。
要在 playbook 中使用它,请指定:community.windows.win_lineinfile
。
概要
此模块将搜索文件中的某一行,并确保该行存在或不存在。
当您只想更改文件中的单行时,这主要很有用。
参数
参数 |
注释 |
---|---|
与 如果 选项
|
|
确定是否应创建备份。 当设置为 选项
|
|
与 选项
|
|
指定要操作的源文本文件的编码(因此也是输出编码)。 可以将显式编码作为字符串传递,该字符串是传递给 .NET 框架 System.Text.Encoding.GetEncoding() 方法的有效值 - 请参阅 https://msdn.microsoft.com/en-us/library/system.text.encoding%28v=vs.110%29.aspx。 如果您想使用特定编码创建新文件,则这主要与 默认值: |
|
与 如果指定的正则表达式没有匹配项,则将改为使用 EOF。不能与 选项
|
|
与 如果指定的正则表达式没有匹配项,则该行将插入到文件末尾。不能与 选项
|
|
请注意,该行首先在控制器上处理,因此取决于 yaml 引号规则。任何双引号行都会展开控制字符,例如 ‘\r\n’。要按字面意思打印此类字符,请使用单引号或不使用引号。 |
|
指定用于修改文件的行分隔符样式。默认为 Windows 行分隔符 ( 选项
|
|
要修改的文件的路径。 请注意,当行使用双引号时,Windows 路径分隔符 |
|
要在文件的每一行中查找的正则表达式。对于 |
|
该行是否应该存在。 选项
|
|
在复制到位之前要运行的验证。在命令中使用 %s 来指示要验证的当前文件。 该命令是安全传递的,因此 shell 功能(如扩展和管道)将不起作用。 |
参见
参见
- ansible.builtin.assemble
从片段组装配置文件。
- ansible.builtin.lineinfile
管理文本文件中的行。
示例
- name: Insert path without converting \r\n
community.windows.win_lineinfile:
path: c:\file.txt
line: c:\return\new
- community.windows.win_lineinfile:
path: C:\Temp\example.conf
regex: '^name='
line: 'name=JohnDoe'
- community.windows.win_lineinfile:
path: C:\Temp\example.conf
regex: '^name='
state: absent
- community.windows.win_lineinfile:
path: C:\Temp\example.conf
regex: '^127\.0\.0\.1'
line: '127.0.0.1 localhost'
- community.windows.win_lineinfile:
path: C:\Temp\httpd.conf
regex: '^Listen '
insertafter: '^#Listen '
line: Listen 8080
- community.windows.win_lineinfile:
path: C:\Temp\services
regex: '^# port for http'
insertbefore: '^www.*80/tcp'
line: '# port for http by default'
- name: Create file if it doesn't exist with a specific encoding
community.windows.win_lineinfile:
path: C:\Temp\utf16.txt
create: true
encoding: utf-16
line: This is a utf-16 encoded file
- name: Add a line to a file and ensure the resulting file uses unix line separators
community.windows.win_lineinfile:
path: C:\Temp\testfile.txt
line: Line added to file
newline: unix
- name: Update a line using backrefs
community.windows.win_lineinfile:
path: C:\Temp\example.conf
backrefs: true
regex: '(^name=)'
line: '$1JohnDoe'
返回值
常见返回值在此处记录 这里,以下是此模块独有的字段
Key |
描述 |
---|---|
创建的备份文件的名称。 现在已弃用,请改用 返回: 如果 backup=yes 示例: |
|
创建的备份文件的名称。 返回: 如果 backup=yes 示例: |