How to elegantly change root password with mysql_user

When I install mysql, default root password is empty. I then use ansible to set the password:


- name: set root password, if it is empty now
mysql_user: login_user=root login_password='' name=root password='{{desired_pass}}' state=present

But 2nd time this playbook runs, the task fails. I can set ignore_errors: True, but this is prone to other failures as well.

Alternatively, I have the approach of settings the desired password twice: once logging in with login_password={{desired_pass}}, once with login_password=‘’. If one of those succeeds, we’re fine:

- name: set root password, if it is empty now
mysql_user: login_user=root login_password='{{item}}' login_host=localhost name=root password='{{desired_pass}}' state=present
with_items:
- '{{root_pass}}'
- ''
register: set_root_pass_result
ignore_errors: True

- fail: msg="could not login with any of the provided passwords"
when: "(set_root_pass_result.results[0].failed is defined) and (set_root_pass_result.results[1].failed is defined)"

Is this supposed to be this tricky, or is there a simpler way?

I do this (in this order):

`

  • name: set password
    mysql_user: name={{ mysql_user }} password={{ hostvars[product + ‘’ + inventory_hostname + '’ + mysql_user].password }}

  • name: create client config
    template: src=client.my.cnf dest=~/.my.cnf mode=0600

`

client.my.cnf:

`
[client]
user={{ mysql_user }}
password={{ hostvars[product + ‘’ + inventory_hostname + '’ + mysql_user].password }}

`

By using .my.cnf with [client]-config you would have the login information to the database on the server (for example in /root/.my.cnf with 600). The variable for the password is just an example from my inventory…