How to do mysql_secure_installation via ansible playbook?

Prince Joseph asked:

I managed to install Apache Mysql/Mariadb and PHP using a playbook. How can I do mysql_secure_installation using ansible or can I? I am a beginner in Ansible. I want to set a new password to MySQL server and complete all security questions via playbook.

Thank you.

My answer:

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}}
    - ::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
    - 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.

View the full question and any other answers on Server Fault.

Creative Commons License
This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.