一、概述
replace 模块可以根据我们指定的正则表达式替换文件中的字符串,文件中所有被匹配到的字符串都会被替换。
二、常用参数
- path参数 : 必须参数,指定要操作的文件,2.3版本之前,只能使用 dest, destfile, name指定要操作的文件,2.4版本中,仍然可以使用这些参数名,这些参数名作为 path 参数的别名使用。
- regexp参数 : 必须参数,指定一个 python 正则表达式,文件中与正则匹配的字符串将会被替换。
- replace参数 : 指定最终要替换成的字符串。
- backup参数 : 是否在修改文件之前对文件进行备份,最好设置为yes。
三、示例
- 把 all机中的 /root/t1.txt文件中的所有123替换成 abc。返回信息显示,替换了2个地方。
测试文件:
[root@CentOSA ~]# cat t1.txt
123
456
[root@CentOSB ~]# cat t1.txt
123
456
[root@Ansible test]# ansible all -m replace -a 'path=/root/t1.txt regexp="123" replace=abc'
192.168.0.160 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/libexec/platform-python"
},
"changed": true,
"msg": "1 replacements made"
}
192.168.0.161 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/libexec/platform-python"
},
"changed": true,
"msg": "1 replacements made"
}
查看远程主机:
[root@CentOSA ~]# cat t1.txt
abc
456
[root@CentOSB ~]# cat t1.txt
abc
456
- 把 all主机中的/root/t1.txt文文件中的所有abc替换成ABC,但是在操作文件之前进行备份。
[root@Ansible test]# ansible all -m replace -a 'path=/root/t1.txt regexp="abc" replace=ABC backup=yes'