第一節(jié):部署數(shù)據(jù)庫主從的前提條件
1.兩臺或兩臺以上的數(shù)據(jù)庫實例
2.主庫要開啟二進制日志
3.主庫要有復制用戶
4.主庫的server_id和從庫不同
5.從庫需要在開啟復制功能前,要獲取到主庫之前的數(shù)據(jù)(主庫備份,并且記錄binlog當時位置)
6.從庫在第一次開啟主從復制時,時必須獲知主庫:ip,port,user,password,logfile,pos
IP:10.0.0.51
Port:3306
User:rep
Password:123456
logFile:mysql-bin.000002 <--在主庫上獲取值
Pos:120 <--在主庫上獲取值
7.從庫要開啟相關線程:IO、SQL
8.從庫需要記錄復制相關用戶信息,還應該記錄到上次已經從主庫請求到哪個二進制日志
9.從庫請求過來的binlog,首先要存下來,并且執(zhí)行binlog,執(zhí)行過的信息保存下來
第二節(jié): 使用Ansible自動部署主從復制
Ansible部署主從復制出現(xiàn)的問題:由于主庫的logfile,和pos不是固定的所以,我們所寫的ansible前提是要在主庫上執(zhí)行命令,進行查看logfile和pos
show master status;
主機文件:
[mysql]
172.16.1.51
172.16.1.52
第三節(jié):使用register來注冊變量
這里我使用了register注冊變量,但是注冊的變量只能針對當前主機生效。通過設置全局的fact變量來實現(xiàn)跨主機變量的使用,從而自動獲取到logfile和pot。
#將logfile注冊成變量。
- name: Get logfile
shell: mysql -uroot -p123456 -e "show master status;"|awk 'NR==2{print $1}'
register: file
when: ( ansible_hostname is match "mysql01" )
#將pot注冊成變量
- name: master-bin-pot
shell: mysql -uroot -p123456 -e "show master status;"|awk 'NR==2{print $2}'
register: pot
when: ( ansible_hostname is match "mysql01" )
第四節(jié):跨主機變量的使用
1.通過set_fact模塊來設置全局的fact變量
- name: set facts file
set_fact: masterbin={{ file.stdout_lines[0] }} <--將獲取到的logfile賦值給masterbin
when: ( ansible_hostname is match "mysql01")
- name: set facts position
set_fact: position={{ pot.stdout_lines[0] }} <--將獲取到的pot賦值給position
when: ( ansible_hostname is match "mysql01")
2.從庫上執(zhí)行change master to 命令
- name: Changemaster to
mysql_replication:
login_user: root
login_password: '123456'
mode: changemaster
master_user: web
master_password: '123456'
master_host: 172.16.1.51
master_log_file: "{{ hostvars['172.16.1.51']['masterbin'] }}" <--引用51的主機變量
master_log_pos: "{{ hostvars['172.16.1.51']['position'] }}" <--引用51的主機變量
when: ( ansible_hostname is match "mysql02" )