How to do mysql_secure_installation via ansible playbook?

Solution 1:

I implemented this myself for my MariaDB installations some time back, and before I trusted anyone else to do it correctly. These are the steps I performed:

  # mysql_secure_installation
- name: Update MariaDB root password
  mysql_user: name=root host={{item}} password={{mysql_root_password}}
  with_items:
    - 127.0.0.1
    - ::1
    - localhost

- name: Set ~/.my.cnf file
  template: src=dotmy.cnf.j2 dest=/root/.my.cnf mode=0600

  # mysql_secure_installation
- name: Delete anonymous MySQL user
  mysql_user: name="" host={{item}} state=absent
  with_items:
    - localhost
    - "{{ansible_nodename}}"

  # mysql_secure_installation
- name: Delete Hostname based MySQL user
  mysql_user: name=root host="{{ansible_nodename}}" state=absent

  # mysql_secure_installation
- name: Remove MySQL test database
  mysql_db: name=test state=absent

You'll have to decide how to create mysql_root_password yourself.

Solution 2:

I wrote a custom ansible module to do this: https://github.com/eslam-gomaa/mysql_secure_installation_Ansible .

Example

- name: test mysql_secure_installation
  mysql_secure_installation:
    login_password: ''
    new_password: password22
    user: root
    login_host: localhost
    hosts: ['localhost', '127.0.0.1', '::1']
    change_root_password: true
    remove_anonymous_user: true
    disallow_root_login_remotely: true
    remove_test_db: true
  register: mysql_secure
  
# To see detailed output
- debug:
    var: mysql_secure