本文详细描述ansible文件模块中的lineinfile
文章目录
作用
此模块确保文件中有特定的行,或使用反向引用的正则表达式替换现有行。这个
当您只想更改一个文件中的一行时,它非常有用。如果要多样化更改,请参阅[replace]模块;如果要在文件中插入/更新/删除行块,请选择多行、类似行或选中[blockinfile]模块。其他情况下,请参阅[copy]或[template]模块。
常用作添加一个用户的sudo权限;增删改文件某一行等
使用
话不多说,第一步查看帮助文档。
[haiyang@ssh-server ansible]$ ansible-doc lineinfile
> LINEINFILE (/usr/lib/python3.6/site-packages/ansible/modules/files/lineinfile.py)
This module ensures a particular line is in a file, or replace an existing line using a back-referenced regular expression. This
is primarily useful when you want to change a single line in a file only. See the [replace] module if you want to change
multiple, similar lines or check [blockinfile] if you want to insert/update/remove a block of lines in a file. For other cases,
see the [copy] or [template] modules.
* This module is maintained by The Ansible Core Team
OPTIONS (= is mandatory):
由于下面详细的参数太多,这里就不列出来了。本想按照帮助文档的顺序来讲解,但是有些必用的参数直接使用在示例中可能不清楚,下面提前讲下。
- line
变量类型:str
默认值:null
别名:value
功能:插入或者替换到文件中的内容。
- path
变量类型:path 例:path=/etc/ansible/testfile.txt
别名:dest, destfile, name
功能:待修改的文件
- regexp
变量类型:str
默认值:null
别名:regex
功能:使用python的正则表达式规则,如果state=present则替换匹配到的最后一个值;
如果state=absent,则删除所有匹配到的值;如果不匹配,则line的内容将添加的’insertbefore’ or `insertafter’参数设置的地方。
- state
变量类型:str
默认值:present
可选择值: absent, present
功能:添加或删除line行的内容。
cat > /etc/ansible/testfile.txt << EOF
aaa
bbb
ccc
EOF
[haiyang@ssh-server ansible]$ ansible localhost -m lineinfile -a 'path=/etc/ansible/testfile.txt line="bbb" state=absent'
localhost | CHANGED => {
"backup": "",
"changed": true,
"found": 1,
"msg": "1 line(s) removed"
}
[haiyang@ssh-server ansible]$ cat /etc/ansible/testfile.txt
aaa
ccc
- attributes
变量类型:str
默认值:null
功能:同Linux系统中的chattr命令,用于改变文件属性。
[haiyang@ssh-server ansible]$cat > /etc/ansible/testfile.txt << EOF
This is a testfile!
EOF
[haiyang@ssh-server ansible]$ ls -l /etc/ansible/testfile.txt
-rw-rw-r--. 1 haiyang haiyang 20 Jul 16 10:47 /etc/ansible/testfile.txt
[haiyang@ssh-server ansible]$ lsattr /etc/ansible/testfile.txt
------------------ /etc/ansible/testfile.txt
[haiyang@ssh-server ansible]$ ansible localhost -m lineinfile -a "path=/etc/ansible/testfile.txt attr=+i line='This is test for attributes'" -b
localhost | CHANGED => {
"backup": "",