# How to elegantly change root password with mysql\_user

**URL:** <https://forum.ansible.com/t/how-to-elegantly-change-root-password-with-mysql-user/19166>\
**Category:** Ansible Project\
**Created:** [September 2, 2015, 10:28am UTC](https://forum.ansible.com/t/how-to-elegantly-change-root-password-with-mysql-user/19166 "2015-09-02T10:28:37Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Eric\_Feliksik1](https://avatars.discourse-cdn.com/v4/letter/e/c67d28/32.png) [@Eric\_Feliksik1](https://forum.ansible.com/u/Eric_Feliksik1)\
**Post date:** [September 2, 2015, 10:28am UTC](https://forum.ansible.com/t/how-to-elegantly-change-root-password-with-mysql-user/19166/1 "2015-09-02T10:28:37Z")

</div>

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

```auto

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

```auto
- 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?

---

<div class="post-metadata">

**Author:** ![esco\_real](https://avatars.discourse-cdn.com/v4/letter/e/c89c15/32.png) [@esco\_real](https://forum.ansible.com/u/esco_real)\
**Post date:** [September 2, 2015, 12:22pm UTC](https://forum.ansible.com/t/how-to-elegantly-change-root-password-with-mysql-user/19166/2 "2015-09-02T12:22:28Z")

</div>

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…
