ansible角色部署mysql主从复制
创建角色mariadb
[root@ansible roles]# ansible-galaxy init mariadb
编写角色执行任务
[root@ansible roles]# vim mariadb/tasks/main.yml
[root@ansible roles]# cat mariadb/tasks/main.yml
---
# tasks file for mariadb
- name: mount
mount:
src: /dev/cdrom
path: /mnt/
fstype: iso9660
state: mounted
- name: repo
shell:
cmd: rm -rf /etc/yum.repos.d/*
- name: yum_repository1
yum_repository:
file: server
name: AppStream
description: AppStream
baseurl: file:///mnt/AppStream
enabled: yes
gpgcheck: no
- name: yum_reposirtory
yum_repository:
file: server
name: BaseOS
description: BaseOS
baseurl: file:///mnt/BaseOS
enabled: yes
gpgcheck: no
- name: stop firewalld
service:
name: firewalld
state: stopped
enabled: no
- name: stop selinux
lineinfile:
path: /etc/selinux/config
regexp: '^SELINUX='
line: SELINUX=enforcing
- name: stop selinux
shell: setenforce 0
- name: install mariadb
yum:
name:
- mariadb
- mariadb-server
state: present
- name: template
template:
src: mastermy.cnf.j2
dest: /etc/my.cnf
when: inventory_hostname in {{ groups.mysql_master }}
- name: template
template:
src: slavemy.cnf.j2
dest: /etc/my.cnf
when: inventory_hostname in {{ groups.mysql_slave }}
- name: restart mariadb
service:
name: mariadb
state: restarted
enabled: yes
- name: mariadb1
shell:
cmd: mysql -uroot -e "create user 'xuanning'@'192.168.226.60' identified by '123456';"
when: inventory_hostname in {{ groups.mysql_master }}
- name: mariadb2
shell:
cmd: mysql -uroot -e "GRANT REPLICATION SLAVE ON *.* TO 'xuanning'@'192.168.226.60';"
when: inventory_hostname in {{ groups.mysql_master }}
- name: mariadb3
shell:
cmd: mysql -uroot -e "flush privileges;"
when: inventory_hostname in {{ groups.mysql_master }}
- name: slave
shell:
cmd: mysql -uroot -e "change master to master_host='192.168.226.50',master_user = 'xuanning',master_password = '123456';"
when: inventory_hostname in {{ groups.mysql_slave }}
- name: slave2
shell:
cmd: mysql -uroot -e "start slave;"
when: inventory_hostname in {{ groups.mysql_slave }}
编写所需的模板文件
[root@ansible roles]# cat mariadb/templates/mastermy.cnf.j2
[master]
log-bin=g
server-id=2000
[root@ansible roles]# cat mariadb/templates/slavemy.cnf.j2
[slave]
log-bin=g
server-id=2001
编写剧本调用角色
[root@ansible ansible]# cat mariadb.yml
---
- name: mariadb
hosts: mysql
roles:
- mariadb
执行剧本
[root@ansible ansible]# ansible-playbook mariadb.yml
验证
MariaDB [(none)]> show slave status \G
*************************** 1. row ***************************
Slave_IO_State:
Master_Host: 192.168.226.50
Master_User: xuanning
Master_Port: 3306
Connect_Retry: 60
Master_Log_File:
Read_Master_Log_Pos: 4
Relay_Log_File: node2-relay-bin.000001
Relay_Log_Pos: 4
Relay_Master_Log_File:
Slave_IO_Running: Connecting
Slave_SQL_Running: Yes