Ansiable实现多台虚拟机自动安装mysql

1.首先先创建Ansible剧本目录

mkdir roles/mysql/{files,handlers,tasks,templates,vars} -p
touch roles/mysql/{handlers,tasks,vars}/main.yaml

files:存放普通文件
handlers:存放处理程序文件
tasks:存放主任务文件
templates:存放配置文件
vars:存放变量文件

创建完成树形结构表
cd roles
tree 

mysql
├── files
├── handlers
│ └── main.yaml
├── tasks
│ └── main.yaml
├── templates
└── vars
└── main.yaml

2.配置mysql官方yum源

rpm -ivh https://dev.mysql.com/get/mysql80-community-release-el7-2.noarch.rpm

配置完成将mysql源复制到files文件底下

cp /etc/yum.repos.d/mysql-community* /root/roles/mysql/files/

如果要安装5.7版本的mysql请按照如下操作(因为mysql官方源默认安装8.0版本)

打开文件mysql-community.repo修改里面的配置
将5.7中的enabled修改成1,将8.0的enabled修改成0

[mysql57-community]
name=MySQL 5.7 Community Server
baseurl=http://repo.mysql.com/yum/mysql-5.7-community/el/7/$basearch/
enabled=1
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-mysql

[mysql80-community]
name=MySQL 8.0 Community Server
baseurl=http://repo.mysql.com/yum/mysql-8.0-community/el/7/$basearch/
enabled=0
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-mysql

3.编写主任务代码

注意:在tasks目录下的main.yaml编写

---
- name: copy mysql yum
  copy: src={{ item }} dest=/etc/yum.repos.d/
  with_items:
  - mysql-community-source.repo
  - mysql-community.repo

- name: remove mariadb
  shell: rpm -e mariadb --nodeps;rm -rf /var/lib/mysql;rm -rf /etc/my.cnf 

- name: yum makecache
  shell: yum makecache

- name: install mysql5.7
  yum: name=mysql-community-server state=latest

- name: start mysql service
  service: name=mysqld state=started enabled=yes

- name: copy passwd.sh
  copy: src=passwd.sh dest=/root/

- name: change password
  shell: sh /root/passwd.sh

4.编写修改密码的shell脚本pass.sh

脚本应放在files目录下

#!/usr/bin/bash
pass=`grep "password is" /var/log/mysqld.log | awk '{print $NF}'`
mysqladmin -uroot -p"$pass" password "WWW1.com"

5.编写剧本文件site.yaml

剧本文件放在roles下与mysql目录平级

- hosts: mysql     #这个mysql为/etc/ansible/hosts解析的mysql服务器名称
  roles:
  - mysql            #这个mysql是roles文件夹中要执行的任务目录

6.运行ansible剧本

ansible-playbook site.yaml 

你可能感兴趣的:(Ansiable实现多台虚拟机自动安装mysql)