ansible 文件行操作

在Ansible中,对文件进行行操作通常使用
lineinfile
模块。以下是一些基本的操作示例:
修改匹配行,如果不存在则添加
:
“`yaml
name: Ensure SELinux is set to enforcing mode
lineinfile:
path: /etc/selinux/config
regexp: ‘^SELINUX=’
line: SELINUX=enforcing
”
这段代码会将
/etc/selinux/config
文件中以
SELINUX=
开头的行替换为
SELINUX=enforcing`,如果该行不存在,则会添加这行内容。
删除文件中的行
:
“`yaml
name: Ensure sudoers configuration does not contain the wheel group
lineinfile:
path: /etc/sudoers
state: absent
regexp: ‘^%wheel’
”
这段代码会删除
/etc/sudoers
文件中所有以
%wheel`开头的行。
在匹配行前添加一行内容
:
“`yaml
name: Add a line of text before a matching line
lineinfile:
path: /path/to/file
insertbefore: ‘^matching-line’
line: ‘text-to-prepend’
”
这段代码会在文件
/path/to/file
中找到以
matching-line
开头的行,并在这行之前添加新的内容
text-to-prepend`。
在文件末尾添加内容
:
“`yaml
name: Add a line to a file if it does not exist
lineinfile:
path: /path/to/file
create: yes
line: “This is a new line”
“
如果文件
/path/to/file
不存在,这段代码会创建文件并添加新行
This is a new line`。如果文件已存在,它将检查文件是否包含该行,如果没有则添加。
使用正则表达式替换文件中的字符串
:
可以使用
replace
模块来根据正则表达式替换文件中的字符串。例如:
“`yaml
name: ‘Replace all occurrences of a string’
replace:
path: /tmp/test.txt
regexp: ‘old-string’
replace: ‘new-string’
”
这段代码会将
/tmp/test.txt
文件中所有出现的
old-string
替换为
new-string`。
这些是使用Ansible进行文件行操作的一些基本方法。根据你的具体需求,可以调整模块的参数来实现更复杂的操作。