利用ansible的playbook的user、yum、file、unarchive、copy模块实现自动化批量部署并启动mysql,具体脚本如下:
- hosts: ip或分组
remote_user: root
tasks:
- name: create user
user:
name: mysql
state: present
- name: lib #安装依赖
yum:
name: libaio
- name: unarchiveMysqldir
unarchive:
src: /data/ansible/data/mysql/mysql-5.7.38-linux-glibc2.12-x86_64.tar.gz
dest: /data/
mode: 0755
copy: yes
- name: chageName
shell: mv /data/mysql-5.7.38-linux-glibc2.12-x86_64 /data/mysql
- name: createDirectory
file:
path: /data/mysql/{{item}}
state: directory
owner: mysql
with_items:
- ['etc','binlog','relaylog']
- name: copyConf
copy:
src: /data/ansible/data/mysql/my.cnf
dest: /data/mysql/etc/my.cnf
- name: delConf
shell: rm -f /etc/my.cnf
- name: confLink
file:
src: /data/mysql/etc/my.cnf
dest: /etc/my.cnf
state: link
- name: chageMode
shell:
cmd: |
chown -R mysql:mysql /data/mysql
setfacl -m mysql:rwx /data
- name: init #初始化,并将生成的密码输出到/tmp/mysqlinit
shell: /data/mysql/bin/mysqld --initialize --user=mysql &> /tmp/mysqlinit
- name: start
shell: /data/mysql/bin/mysqld_safe --user=mysql &
- name: service #将修改好的mysqld启动文件分发,便于用service启停mysql
copy:
src: /data/ansible/data/mysql/mysqld
dest: /etc/init.d/mysqld
- name: pathLink #创建mysql和mysqldump的软连接
file:
src: /data/mysql/bin/{{item}}
dest: /usr/bin/{{item}}
state: link
with_items:
- ['mysql','mysqldump']
以上用到的my.cnf、mysqld需在ansible服务端提前准备好后才可执行
执行playbook测试命令:ansible-playbook -C mysql.yml
执行命令:ansible-playbook mysql.yml