一、常用需求
1、替换某行内容
2、在某行前插入内容
3、在某行后面插入内容
4、删除某行
二、测试文件内容
[client]
port=3306
socket=/tmp/mysql.sock
[mysqld]
user = mysql
basedir = /app/mysql
datadir = /app/mysql/data
port=3306
server-id = 1
socket=/tmp/mysql.sock
[mysqldump]
quick
max_allowed_packet = 16M
三、playbook 文件
---
- hosts: test
remote_user: cedar
become: yes
tasks:
- name: "在socket=/tmp/mysql.sock前插入内容"
lineinfile:
path: /etc/my_bak.cnf
insertbefore: 'socket=/tmp/mysql.sock'
line: 我是socket前面的内容
- name: "在server-id后插入内容"
lineinfile:
path: /etc/my_bak.cnf
insertafter: 'server-id = 1'
line: 我是server-id后面的内容
- name: "user=mysql 替换"
lineinfile:
path: /etc/my_bak.cnf
regexp: '^user = mysql'
line: user = mingkang
- name: "删除quick这行"
lineinfile:
path: /etc/my_bak.cnf
regexp: 'quick'
state: absent
四、运行结果
[root@Ansible playbook]# ansible-playbook lineinfile.yaml
PLAY [test] *****************************************************************************************************************************************************
TASK [Gathering Facts] ******************************************************************************************************************************************
ok: [10.3.153.8]
TASK [在socket=/tmp/mysql.sock前插入内容] *****************************************************************************************************************************
changed: [10.3.153.8]
TASK [在server-id后插入内容] ******************************************************************************************************************************************
changed: [10.3.153.8]
TASK [user=mysql 替换] ********************************************************************************************************************************************
changed: [10.3.153.8]
TASK [删除quick这行] ************************************************************************************************************************************************
changed: [10.3.153.8]
PLAY RECAP ******************************************************************************************************************************************************
10.3.153.8 : ok=5 changed=4 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
五、验证结果
[root@ansible-test etc]# cat my_bak.cnf
[client]
port=3306
socket=/tmp/mysql.sock
[mysqld]
user = mingkang
basedir = /app/mysql
datadir = /app/mysql/data
port=3306
server-id = 1
我是server-id后面的内容
我是socket前面的内容
socket=/tmp/mysql.sock
[mysqldump]
max_allowed_packet = 16M