Ansible批量部署MySQL

1.1 将mysql软件包同步到客户端服务器,做安装前期准备

首先将mysql安装包拖到ansible服务端的/ansible/roles/mysql/files目录下

vim /ansible/roles/mysql/tasks/main.yml

- name: copy mysql_tar_gz to client
  copy: src=mysql-5.6.35.tar.gz dest=/tmp/mysql-5.6.35.tar.gz
- name: copy install_script to client
  copy: src=mysql_install.sh dest=/tmp/mysql_install.sh owner=root group=root mode=755
- name: install mysql
  shell: /bin/bash /tmp/mysql_install.sh

1.2 创建mysql 安装脚本

/ansible/roles/mysql/files/mysql_install.sh

#!/bin/bash

####定义mysql数据库路径,和mysql登录密码
DBDIR='/application/mysql/data'
PASSWD='bingoclo123'

####判断数据目录是否存在如果不存在递归创建目录
[ -d $DBDIR ] || mkdir $DBDIR -p

####安装mysql组件
yum install cmake make gcc-c++ bison-devel ncurses-devel -y
id mysql &> /dev/null

####如果执行id mysql输出为0 那么就是执行正确创建mysql用户
if [ $? -ne 0 ];then
 useradd mysql -s /sbin/nologin -M
fi

####赋予数据目录权限
chown -R mysql.mysql $DBDIR

####切换到tmp目录,解压mysql,编译安装mysql到/application/mysql
cd /tmp/
tar xf mysql-5.6.35.tar.gz
cd mysql-5.6.35
cmake . -DCMAKE_INSTALL_PREFIX=/application/mysql \
-DMYSQL_DATADIR=$DBDIR \
-DMYSQL_UNIX_ADDR=$DBDIR/mysql.sock \
-DDEFAULT_CHARSET=utf8 \
-DEXTRA_CHARSETS=all \
-DENABLED_LOCAL_INFILE=1 \
-DWITH_READLINE=1 \
-DDEFAULT_COLLATION=utf8_general_ci \
-DWITH_EMBEDDED_SERVER=1

####判断如果以上执行结果不等于0,说明执行失败,退出!
if [ $? != 0 ];then
 echo "cmake error!"
 exit 1
fi

####判断执行成功,继续往下走
make && make install
if [ $? -ne 0 ];then
 echo "install mysql is failed!" && /bin/false
fi
sleep 2

####做软连接
ln -s /application/mysql/bin/* /usr/bin/

####复制mysql配置文件
cp -f /application/mysql/support-files/my-default.cnf /etc/my.cnf

####复制mysql启停脚本到init.d
cp -f /application/mysql/support-files/mysql.server /etc/init.d/mysqld

####执行权
chmod 700 /etc/init.d/mysqld

####初始化mysql
/application/mysql/scripts/mysql_install_db  --basedir=/application/mysql --datadir=$DBDIR --user=mysql

####如果mysql初始化失败提示install mysql is failed!  否则/etc/init.d/mysqld start
if [ $? -ne 0 ];then
 echo "install mysql is failed!" && /bin/false
fi
/etc/init.d/mysqld start

####如果mysql开启失败提示install mysql is failed! 否则继续往下走
if [ $? -ne 0 ];then
 echo "install mysql is failed!" && /bin/false
fi

####开机自启
chkconfig --add mysqld
chkconfig mysqld on
/application/mysql/bin/mysql -e "update mysql.user set password=password('$PASSWD') where host='localhost' and user=
'root';"
/application/mysql/bin/mysql -e "update mysql.user set password=password('$PASSWD') where host='127.0.0.1' and user=
'root';"
/application/mysql/bin/mysql -e "delete from mysql.user where password='';"
/application/mysql/bin/mysql -e "flush privileges;"
if [ $? -eq 0 ];then
 echo "ins_done"
fi

1.3 执行ansible 命令

cd /ansible
ansible-playbook web.yml --syntax-check  #检查语法
ansible-playbook web.yml  #执行
    原文作者:InnocenceYWQ
    原文地址: https://www.jianshu.com/p/b84315232a84
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞