You can misuse ~/.my.cnf for being able to change the mysql-root-password.
The trick is to have a task "Set root password"(nr.1), which will set the password. Afterwards, you have a task, which creates a ~/.my.cnf with the correct credentials (nr.2).
On a new system, ~/.my.cnf is not present. Task nr.1 will create mysql-root-user with given credentials. On a present system, credentials from ~/.my.cnf are used to login and set password to mysql_root_password. Task nr.2 will create ~/.my.cnf, oroverwrite existing old credentials ~/.my.cnf with new ones.
The big advantage of this approach is having only one variable "mysql_root_password", which is always the correct one from a playbook's point-of-view. On the present system(s), ~/.my.cnf is kind of storage for current local mysql-credentials.
- name: Set root user password
# If .my.cnf already exists, this will cause an mysql-root-password update.
mysql_user:
name: root
password: "{{ mysql_root_password}}"
check_implicit_admin: true
- name: Create .my.cnf
template:
src: "client.my.cnf.j2"
dest: "/root/.my.cnf"
owner: root
group: root
mode: 0600
with client.my.cnf.j2:
[client]
user=root
password={{ mysql_root_password }}
Further reading
Relevant notes from ansible-mysql_user_module-documentation:
Note1:
To secure this user as part of an idempotent playbook, you must create at least two tasks: the first must change the root user’s password, without providing any login_user/login_password details. The second must drop a ~/.my.cnf file containing the new root credentials. Subsequent runs of the playbook will then succeed by reading the new credentials from the file. ansible-mysql_user_module, notes
Note2:
Both login_password and login_user are required when you are passing credentials. If none are present, the module will attempt to read the credentials from ~/.my.cnf, and finally fall back to using the MySQL default login of ‘root’ with no password. ansible-mysql_user_module, notes