Manage MySQL users & grants with Ansible
Ansible manages users and privileges through the community-maintained
community.mysql.mysql_user
module. The collection can manage far more than users, so read the docs to see every option and use case.
Create a user with different privileges per database
- name: Create a user with different privileges per database
community.mysql.mysql_user:
login_user: mysql_admin
login_password: "{{ mysql_admin_password }}"
name: demo
password: "{{ demo_password }}"
state: present
priv: "mydb.*:INSERT,UPDATE/anotherdb.*:SELECT/yetanotherdb.*:ALL"
Create read-only users for an analytics database
- name: Create read-only users for the analytics database
community.mysql.mysql_user:
login_user: mysql_admin
login_password: "{{ mysql_admin_password }}"
name: "{{ item }}"
password: "{{ vault_analytics_password }}"
state: present
priv: "analytics.*:SELECT"
loop:
- user1
- user2
- user3
Why Ansible for MySQL users & grants?
Ansible is an agentless configuration-management tool: it pushes changes to your hosts over SSH, so the targets only need Python and an SSH server — no long-running agent to install or maintain. Its strengths are simple YAML-based playbooks, on-demand execution, and a huge library of community roles and collections that are largely plug-and-play.
Defining users as code means every access change is version-controlled and peer-reviewed, environments are
reproducible, and the mysql_user module is idempotent — re-running a playbook converges to the
declared state instead of piling up duplicate grants. Keep passwords in Ansible Vault rather than
plain text in your repository.