Declaring username and password in a vault and reading the dictionary into a playbook.
The files
mysql_vault
andmysql_users
were renamed tolibrary_vault_key
andlibrary_vault
to include other secrets than MySQL only.
The dictionary, mysql_users
has the database name as key, and the values are the username and the password. The password for the vault is in the file mysql_vault,
which is a simple text file like this
a-garcm0b@lthlibtest2:~$ echo "my super secret password" >> mysql_vault
To create an encrypted file from a plain text file use the option encrypt
in the ansible-vault
command.
a-garcm0b@lthlibtest2:~$ ansible-vault encrypt --vault-id mysql_vault mysql_users
Encryption successful
a-garcm0b@lthlibtest2:~$
To open the file for editing
a-garcm0b@lthlibtest2:~$ ansible-vault edit --vault-id mysql_vault mysql_users
Then edit the file
Database users and passwords
#
db_1:
user: user_db_1
password: user_pass_1
db_2:
user: user_db_2
password: user_pass_2
(...)
Read the vault in the playbook via include_vars
module with the name db_users.
Next transform the dictionary in to a list. Finally loop over the list
tasks:
- name: Read DB credentials from a file
include_vars:
file: more_secrets.yml
name: db_users
- name: Set user name and password on the databases
debug:
msg: "DB: {{ item.key }}, User {{ item.value.user }}, password {{ item.value.password }}"
loop:
"{{ db_users | dict2items }}"