在Ansible主机上定义hosts文件和准备安装包,目录结构如下:
hosts配置如下:(本次示例只演示1台机器)
install.yml内容如下:(示例采用mysql-5.7.35源码包,数据目录自定义)
- hosts: mysql
tasks:
- name: 复制安装包
copy: src=mysql-5.7.35-el7-x86_64.tar.gz dest=/opt force=no
- name: 解压安装包
unarchive: src=/opt/mysql-5.7.35-el7-x86_64.tar.gz dest=/opt copy=no
- name: 创建mysql组
group: name=mysql state=present
- name: 创建mysql用户
user: name=mysql group=mysql state=present
- name: 创建数据目录
file:
path: "{{ item }}"
state: directory
owner: mysql
group: mysql
with_items:
- /data/mysql
- /data/log
- /data/tmp
- name: 复制my.cnf文件
copy: src=my.cnf dest=/etc/my.cnf
- name: 初始化数据库
shell: /opt/mysql-5.7.35-el7-x86_64/bin/mysqld --initialize
- name: 再次更改数据目录权限
file: path=/data owner=mysql group=mysql recurse=yes
- name: 复制开机启动文件
copy: src=mysqld.service dest=/lib/systemd/system/
- name: 添加/etc/profile环境变量
lineinfile: dest=/etc/profile line="export PATH=$PATH:/opt/mysql-5.7.35-el7-x86_64/bin"
- name: 生效环境变量
shell: "source /etc/profile"
- name: 添加/root/.bashrc环境变量
shell: /bin/echo "export PATH=$PATH:/opt/mysql-5.7.35-el7-x86_64/bin" >> /root/.bashrc; source /root/.bashrc
- name: 设置开机自启动
service: name=mysqld state=started enabled=yes
my.cnf简易配置:
[client]
port = 3306
socket = /data/tmp/mysql.sock
[mysqld]
user= mysql
port = 3306
basedir = /opt/mysql-5.7.35-el7-x86_64
datadir = /data/mysql
tmpdir = /data/tmp
socket = /data/tmp/mysql.sock
pid-file = /data/log/mysql.pid
log_error = /data/log/error.log
slow_query_log_file = /data/log/slow.log
mysqld.service使用systemctl管理mysql服务:
[Unit]
Description=mysqld
After=network.target
[Service]
Type=forking
ExecStart=/opt/mysql-5.7.35-el7-x86_64/support-files/mysql.server start
ExecReload=/opt/mysql-5.7.35-el7-x86_64/support-files/mysql.server restart
ExecStop=/opt/mysql-5.7.35-el7-x86_64/support-files/mysql.server stop
PrivateTmp=true
[Install]
WantedBy=multi-user.target
部署阶段:
验证机器连通性:
检查语法:
语法错误修正后执行:
检查安装结果:
可以看到mysql进程和3306端口已启动。