ansible之lineinfile模块

本文详细描述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": "",
  • 3
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值