TransWikia.com

How to do mysql_secure_installation via ansible playbook?

Server Fault Asked by Prince Joseph on December 27, 2021

I managed to install Apache Mysql/Mariadb and PHP using playbook. How can I do mysql_secure_installation using ansible?

I am a beginner in Ansible. I want to set a new password to MySQL server and complete all security questions via playbook.

3 Answers

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

Answered by Eslam.Gomaa on December 27, 2021

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.

Answered by Michael Hampton on December 27, 2021

For idempotency reasons it is a good practice to implement the hardening steps done by mysql_secure_installation with dedicated Ansible tasks rather than executing mysql_secure_installation via Ansible directly.

mysql_secure_installation does the following:

  • set the root password
  • remove anonymous users
  • remove root remote access
  • remove the test database

Theses hardening tasks can be implemented with Ansible like this:

- name: test database is absent
  mysql_db: name=test state=absent
  when: mysql_remove_test_database

Check out dev-sec's MySQL hardening repository for an complete example how to implement the mysql_secure_installation steps with Ansible tasks.

Answered by Henrik Pingel on December 27, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP