Last Updated: December 26, 2018
· naxhh

Mysql server installation with custom password in Ansible

When you install mysql-server with Ansible like this:

- name: Install Mysql
  apt: pkg=mysql-server state=latest

The package manager will prompt for a root password, but ansible will just enter nothing or null...
And change the password before can be a pain in the ass.

So, the way you can set the root password you want is pretty simple:

- name: Mysql | Set root password
  shell: debconf-set-selections <<< 'mysql-server mysql-server/root_password password put_your_root_password'

- name: Mysql | Set root repassword
  shell: debconf-set-selections <<< 'mysql-server mysql-server/root_password_again password put_your_root_password'

This way the package manager won't ask for a password and will use this one instead.

Tested with: 1.5 (devel)

Here is a way to change the password when you already installed mysql, but didn't work for me:

3 Responses
Add your response

I like that you're using Ansible. It puts you on track for making the installation and configuration of mysql a simple, repeatable process. You're off to a good start!

I think there might be a better way to do this though. Firstly, ansible includes several mysql modules, one of which is mysqluser. The mysqluser module will let you modify users, create users, change passwords, etc. This would be preferred over a shell task. Check it out in the documentation here:

Secondly, there is a really good role on the Galaxy community site that gives you everything needed for installing, configuring and hardening a mysql host. It's available here:

over 1 year ago ·

Ansible also has a debconf module now so you don't need to run that in the shell module

over 1 year ago ·

Set MySQL's root password using Ansible's debconf module:

    mysql_root_pass: yourRootPassword


  - name: Set MySQL root password before installing
    debconf: name='mysql-server' question='mysql-server/root_password' value='{{mysql_root_pass | quote}}' vtype='password'

  - name: Confirm MySQL root password before installing
    debconf: name='mysql-server' question='mysql-server/root_password_again' value='{{mysql_root_pass | quote}}' vtype='password'
over 1 year ago ·