使用ansible初始化mysql数据库
时间: 2023-06-17 22:06:17 浏览: 81
新建SQL数据库并初始化
可以使用 Ansible 来初始化 MySQL 数据库,下面是一个示例 playbook:
```yaml
- hosts: db
become: true
vars:
mysql_root_password: "your_mysql_root_password"
tasks:
- name: Install MySQL packages
yum:
name: mysql-server
state: present
- name: Start MySQL service
service:
name: mysqld
state: started
- name: Set MySQL root password
mysql_user:
login_user: root
login_password: ""
user: root
password: "{{ mysql_root_password }}"
host_all: true
priv: "*.*:ALL,GRANT"
- name: Create database and user
mysql_db:
login_user: root
login_password: "{{ mysql_root_password }}"
name: mydatabase
encoding: utf8
collation: utf8_general_ci
- name: Create database user
mysql_user:
login_user: root
login_password: "{{ mysql_root_password }}"
name: myuser
password: "mypassword"
priv: "mydatabase.*:ALL"
```
在运行 playbook 之前,需要在 inventory 文件中指定目标主机,如:
```
[db]
db-server
```
然后,运行 playbook:
```
ansible-playbook -i inventory playbook.yml
```
这会在目标主机上安装 MySQL,设置 root 密码,创建一个名为 `mydatabase` 的数据库,以及一个名为 `myuser` 的用户并授予其对 `mydatabase` 的访问权限。
阅读全文