I'm trying to write a single page ansible script for mysql installation and setup a new user and create a empty DB. what I've tried so far -
hosts
file
[mysql]
webapp ansible_ssh_host=xxx.xxx.xxx.xxx
mysql.yml
(The single file for all tasks/vars/handelers) (both hosts and mysql.yml in same directory) and I can login in remote system using ssh
---
- hosts: mysql
vars:
- system_packages:
- build-essential
- python-dev
- python-pip
- libmysqlclient-dev
- mysql-server
- python-mysqldb
- root_password: root
tasks:
- name: Install MySQL
apt: pkg={{ item }} state=installed update-cache=yes
with_items: system_packages
tags:
- setup
- name: Start MySQL service
action: service name=mysql state=started enabled=yes
- name: Update mysql password for root account
mysql_user: name=root host={{ item }} password={{root_password}}
with_items:
- 127.0.0.1 #In case of distributed system how should I place Ip addr of this system
- localhost
- name: create db 'mydb'
action: mysql_db db=mydb state=present
- name: Creates database user 'eric' with password 'eric' for 'mydb' and grant all priveleges
action: mysql_user state=present name=eric password=eric priv=mydb.*:ALL
handlers:
- name: start mysql
service: name=mysql state=started
when I run this script I get this output(+error)
failed: [webapp] => (item=127.0.0.1) => {"failed": true, "item": "127.0.0.1"}
msg: unable to connect to database, check login_user and login_password are correct or ~/.my.cnf has the credentials
You can't connect to mysql server before you will set root password. To do this use the following:
- name: Set password for root user
shell:
mysqladmin password "{{ root_password }}" -u root
After a default installation on ubuntu, you only can login to your mysql as root with password "root". So to change your password you will have to set your mysql login user to root (as you did in the next task)
- name: Update mysql password for root account
mysql_user:
name=root host={{ item }}
password={{root_password}}
login_user=root
login_password="root"
sudo: yes
sudo_user: root
There is also a ready-to-go solution in ansible galaxy
Please add this task inside your task/main.yml
- name: Copy the root credentials as .my.cnf file
template: src=root.cnf.j2 dest=~/.my.cnf mode=0600
and this will be your root.cnf.j2
[client]
user=root
password={{ root_password }}
What it will do is, to connect the mysql from the root user without password and perform these task. You can remove it after running all the task or leave it like this because it is under root and have tight permission.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.