ansible模块之blockinfile,
ansible模块之blockinfile,
一、模块说明
二、常用参数
三、案例演示
一、模块说明
blockinfile: 在指定文件中插入一段"文本",这段文本是被标记的,以便于我们后续通过标记找到这段文本
二、常用参数 常用参数:
详细参数执行:
ansible-doc blockinfle
常用参数:
backup: 是否备份文件
block: 指定要插入标记内的文本
create: 如果文件不存在,则创建新文件
group: 文件属组
insertafter: 如果指定,文本将插入到最后一次匹配项的后面
insertbefore: 如果指定,文本讲插入到最后一次匹配项的前面
maker: 假如我们想要在指定的文件中插入一段文本,ansible会自动为这段文本添加2个标记,一个开始标记,一个结束标记;
默认情况下,开始标记为:# BEGIN ANSIBLE MANAGED BLOCK,结束标记为# END ANSIBLE MANAGED BLOCK
path: 文件路径
state: 可选present或absent,默认为将指定的文本插入到文件中,如果文件中存在该文本,则会更新对应的段落,如果为absent,则删除对应的段落
三、案例演示
1. 创建文本并输入block内容
ansible cluster -m blockinfile -a "path=/tmp/aa.txt block='this is a test' create=True"
[root@node1 tmp]# cat aa.txt
# BEGIN ANSIBLE MANAGED BLOCK
this is a test
# END ANSIBLE MANAGED BLOCK
2. 自定义标记
ansible cluster -m blockinfile -a 'path=/tmp/aa.txt block="this is bob\nthis is tim" marker="#{mark} start to mark"'
[root@node1 tmp]# cat /tmp/aa.txt
# BEGIN ANSIBLE MANAGED BLOCK
this is a test
# END ANSIBLE MANAGED BLOCK
#BEGIN start to mark
this is bob
this is tim
#END start to mark
3. 文件中存在的内容更新(因为标记存在,匹配的内容就会做更新)
ansible cluster -m blockinfile -a 'path=/tmp/aa.txt block="this is lxm" marker="#{mark} start to mark"'
# BEGIN ANSIBLE MANAGED BLOCK
this is a test
# END ANSIBLE MANAGED BLOCK
#BEGIN start to mark
this is lxm
#END start to mark
4. 删除指定块
ansible cluster -m blockinfile -a 'path=/tmp/aa.txt marker="{mark} start to mark" state=basent'
[root@node1 tmp]# cat aa.txt
# BEGIN ANSIBLE MANAGED BLOCK
this is a test
# END ANSIBLE MANAGED BLOCK
5. 插入文件开头
BOF就是begin of file
ansible cluster -m blockinfile -a 'path=/tmp/aa.txt block="this is wuhan" marker="#{mark}wuhan" insertbefore=BOF'
注意:insertbefore可以指定正则匹配,当有多个匹配,默认插入第一个匹配项前面
[root@node1 tmp]# cat aa.txt
#BEGINwuhan
this is wuhan
#ENDwuhan
# BEGIN ANSIBLE MANAGED BLOCK
this is a test
# END ANSIBLE MANAGED BLOCK
6. 正则匹配
ansible cluster -m blockinfile -a 'path=/tmp/aa.txt block="bbbbb" insertbefore=aaaa'
[root@node1 tmp]# cat aa.txt
#BEGINwuhan
this is wuhan
#ENDwuhan
# BEGIN ANSIBLE MANAGED BLOCK
bbbbb
# END ANSIBLE MANAGED BLOCK
aaaa
aaaa
评论暂时关闭