How to create Ansible Vaults with examples

Ansible vaults are used to store secrets, sensitive data, and passwords.

How to create/encrypt/decrypt a file using Ansible Vault

We might have sensitive information like passwords to be used in our playbooks. It is a bad practice to save it as plain text. Ansible vault feature is of great help here.

Suppose, we have a variable file details.yml as below

---
username: John
password: pAss4JohN
details.yml

To include these details in the playbook, we use include_vars as below.

tasks:
  - name: Include var file
    include_vars: details.yml
main.yml

As we mentioned above, passwords should never be given as plain text files. Hence, this file needs to be encrypted. Execute the below command to encrypt the file. Provide a password when prompted.

ansible-vault encrypt details.yml

Once the file is encrypted you can use the variables username and password in your tasks. Additionally use no_log: true so that the the sensitive information is not displayed in the output.

If the password in details.yml needs to be edited at a later stage, we need to decrypt the file using the below command.

ansible-vault decrypt details.yml

These vault passwords can be stored in vaults like keepass or keystores.

How to escape special characters in Ansible Vault

In some cases, passwords might have special characters.

For example: abc{qwe%$:1

Method 1: Use unsafe keyword

---
user: John
password: !unsafe 'abc{qwe%$:1'

Method 2: Use '>-' operator

---
user: John
password: >-
          'abc{qwe%$:1'

How to run an Ansible playbook that has a vault

A playbook that has a vault included in it cannot be run using the usual ansible-playbook command. You need to include --ask-vault-pass or pass the vault password file.

ansible-playbook main.yml --ask-vault-pass
ansible-playbook main.yml --vault-password-file  /home/user/vaultfile.txt

How to add the Ansible vault credentials in Ansible Tower

To create a vault, we need a server where Ansible is installed. Create a vault using the steps mentioned below in the command prompt.

vi details.yml
---
username: John
password: pAss4JohN

Encrypt the file using the command below.

ansible-vault encrypt details.yml
Password: ******

In Ansible tower, navigate to Credentials and click on create new credential. Select type as vault  and create a credential and provide the password of the vault created above.  This credential can then be used in the job template.

Vipin

Vipin

I am a dreamer. I admire the web. I admire anything about the web.