mysql_user module - adding users if they don't exist.

Hello Everyone,

I’ve been working on a simple playbook to add multiple-users to a mysql-database using the mysql_user module.

One thing I’ve discovered is that every time I rerun the playbook, it’ll reset the password, for an already-existing account, to whatever is set in the mysql_user module.
This makes sense given the nature of the command

Example:

name: create mysql_prod user(s)
mysql_user: login_host=database.foo.com login_user=${LOGIN_USER} login_password=${LOGIN_PASS} name=${item} host=${HOST} password=${PASS} priv=${PRIV} state=${STATE}
with_items: ${users}

Obviously this behavior is fine for new users, however as time progresses and the number of users increase, the likelihood of overwriting a user-password increases.

Is there a way where I could test if the user exists and skip the password change?

Hopefully this makes sense.

Thank you.

–Mike

There’s nothing available currently in Ansible to do that, so you’d probably have to execute some SQL through a mysql command and check the return code. It seems like this should be more idempotent, so feel free to open a feature request on github to add a check to the mysql_user module to support not overwriting an existing user.

The mysql_user module both creates users and changes their password.
What you can do is use the password lookup plugin, which creates a
password and stores it in a file if the file doesn't exist, and reads
it from the file if the file does exist.

So instead of password=${PASS}, you have, assuming with_items: users ...

password=$PASSWORD(files/mysqlpasswords/${item}),

Or, using the new syntax (thanks mdehaan for helping me with this on
the IRC channel):

password="{{ lookup('password', 'files/mysqlpasswords/%s' % item) }}"

Regards,

Javier Candeira