Skip to content

Use or Create a Password#

Problem#

How do I provide a password and store it somewhere just using Ansible?

Solution#

- name: Create MySQL users
  community.mysql.mysql_user:
    name: "{{ item.service_name }}"
    password: "{{ lookup('ansible.builtin.password', '~/.secrets/' + item.service_name + '/mysql_password', length=15) }}"
    priv: "{{ item.service_name }}.*:ALL"
  with_items:
    - service_name: service_a
    - service_name: service_b
    - service_name: service_c

Explanation#

Lookups are executed on the controller, using the ansible.builtin.password lookup uses the password found under the path provided or create a new and stores it here.

graph LR
  A(Lookup Password) --> B{exists?};
  B -->|Yes| C[Use it];
  B -->|No| D[Create new & save it];
  C --> F(End);
  D --> F(End);

Passwords are not encrypted

These passwords are not encrypted by default, use ansible-vault or similar to encrypt it. Alternatively use a path outside of your git repo or add the path to the .gitignore.