我正在使用 Ansible 2.9.20 并为 8.0.26 版本的 mysql 安装创建了剧本。此 mysql 版本安装有一些更改,因此在此处添加对我有用的解决方案。
MySQL.yml
---
# tasks file for mysql_setup
- name: Upgrade all packages
yum:
name: "*"
state: latest
- name: Install MySQL repository
yum:
name: "https://dev.mysql.com/get/mysql80-community-release-el7-1.noarch.rpm"
state: present
- name: Install MySQL
yum:
name: ['mysql-community-devel*', 'mysql-community-server*', 'MySQL-python']
state: present
- name: copy my.cnf
copy:
src: ../files/etc/my.cnf
dest: /etc/my.cnf
mode: 0644
- name: Enable the MySQL service
service:
name: mysqld
state: restarted
enabled: true
- name: Read secret file
include_vars: "defaults/secret.yml"
- name: get root password
shell: "grep 'A temporary password is generated for root@localhost' /var/log/mysqld.log | awk -F ' ' '{print $(NF)}'"
register: root_password
- name: Ensure root can login into MySQL localhost using temporary password
shell: "mysql -uroot -p'{{ root_password.stdout }}' --connect-expired-password"
with_items:
- 127.0.0.1
- ::1
- localhost
register: root_login_tmp_pass
ignore_errors: yes
- name: update expired root user password
command: mysql --user root --password={{ root_password.stdout }} --connect-expired-password --execute="ALTER USER 'root'@'localhost' IDENTIFIED BY '{{ secret.passwd_mysql_root }}';"
when: root_login_tmp_pass is succeeded
- name: update root user password
command: mysql --user root --password={{ secret.current_passwd_mysql_root }} --execute="ALTER USER 'root'@'localhost' IDENTIFIED BY '{{ secret.passwd_mysql_root }}';"
when: root_login_tmp_pass is failed
- name: Copy root .my.cnf file
template:
src: ../templates/root-my.cnf.j2
dest: /root/.my.cnf
owner: root
group: root
mode: 0600
- name: Create a database
mysql_db: name={{ db_name }}
collation=utf8_general_ci
encoding=utf8
state=present
- name: Create a database user
mysql_user: name={{ db_user }}
password={{ secret.db_user_password }}
priv="{{ db_name }}.*:ALL"
host=localhost
state=present
模板/根-my.cnf.j2
[client]
user=root
password={{ secret.passwd_mysql_root }}
文件/etc/my.cnf
[mysqld]
datadir=/var/lib/mysql
socket=/var/lib/mysql/mysql.sock
log-error=/var/log/mysqld.log
pid-file=/var/run/mysqld/mysqld.pid
default-authentication-plugin=mysql_native_password
默认值/main.yml
---
# defaults file for mysql_setup
db_name: mydb
db_user: iamuser
默认值/secret.yml
secret:
passwd_mysql_root: RootPassword2!3
db_user_password: iamdbpassword
current_passwd_mysql_root: currRootPass2!3
运行此 playbook 两次后,您必须使用当前密码 (current_passwd_mysql_root) 和要设置的 root 密码 (passwd_mysql_root) 更新此 secret.yml 文件。