Roberto Jobet
Roberto Jobet

Reputation: 323

Idempotent code creating a MySQL user with Ansible

I'm using an Ansible script to create a MySQL user that manages a database.

The username is created with a random name.

- set_fact:
    wp_db_user: "{{ lookup('password', '/dev/null length=10 chars=ascii_letters') }}"

And password with the same idea.

- set_fact:
    wp_db_password: "{{ lookup('password', '/dev/null length=20 chars=ascii_letters,hexdigits') }}"

And this is the code to create the user.

- name: Create mysql user
  community.mysql.mysql_user:
    login_user: root
    login_unix_socket: /var/run/mysqld/mysqld.sock
    name: "{{ wp_db_user }}"
    password: "{{ wp_db_password }}"
    priv: "{{ wp_db_name }}.*:ALL" 

Everything is fine, if I run the code once. The problem is if I have to run it a second time on the same remote server, as each time a new user is being created since the username is random.

Which could be the best approach to avoid creating a different user each time I run the code on the same remote server?

Upvotes: 0

Views: 237

Answers (1)

Chris Doyle
Chris Doyle

Reputation: 12199

So you have competing requirements here. On one hand you want the password to be random. On the other hand you want it to be consistent between runs. The way to achieve that is to seed the password with something that is consistent between runs. If you're using the same host then you could use the hosts name. This is actually one of the examples given in the ansible password docs

- name: create random but idempotent password
  ansible.builtin.set_fact:
    password: "{{ lookup('ansible.builtin.password', '/dev/null', seed=inventory_hostname) }}"

Upvotes: 3

Related Questions