Skip to content

Instantly share code, notes, and snippets.

@marcelomgarcia
Last active October 23, 2023 12:48
Show Gist options
  • Save marcelomgarcia/d4f7a8f62fecac8bbeb751c6444cbca5 to your computer and use it in GitHub Desktop.
Save marcelomgarcia/d4f7a8f62fecac8bbeb751c6444cbca5 to your computer and use it in GitHub Desktop.
Using Ansible vault to read passwords in a dictionary

Read Passwords from Ansible Vault

Declaring username and password in a vault and reading the dictionary into a playbook.

The files mysql_vault and mysql_users were renamed to library_vault_key and library_vault to include other secrets than MySQL only.

The Vault

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
(...)

Reading the Vault

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 }}"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment