Skip to main content

RHCE Certification Course

Chapter #25: How to Use Ansible Vault in Playbooks to Protect Sensitive Data

In this chapter, you'll learn how to use Ansible Vault to encrypt secrets, protect sensitive data, and securely manage automation tasks.

As you go about using Ansible, you may be required to key in some confidential or secret information in playbooks, which includes SSH private and public keys, passwords, and SSL certificates, to mention just a few.

As we already know, it's bad practice to save this sensitive information in plain text for obvious reasons. This information needs to be kept under lock and key because we can only imagine what would happen if hackers or unauthorized users got hold of it.

Thankfully, Ansible provides us with a handy feature known as Ansible Vault. As the name suggests, the Ansible Vault helps secure vital secret information, as we have discussed earlier.

Ansible Vault can encrypt variables or even entire files and YAML playbooks, as we shall later demonstrate. It’s a very handy and user-friendly tool that requires the same password when encrypting and decrypting files.

Let’s now dive in and have an overview of the various operations that can be carried out using Ansible Vault.

How to Create an Encrypted File in Ansible

If you want to create an encrypted Playbook file, simply use the ansible-vault create command and provide the filename as shown.

ansible-vault create filename

You will thereafter be prompted for a password, and after confirming it, a new window will open using the vi editor where you can begin writing your plays.

Fig 1: Create an Encrypted File in Ansible

Below is a sample of some information. Once you are done, simply save and exit the playbook. And that’s just about it when creating an encrypted file.

Fig 2: Encrypted File in Ansible

You can also encrypt multiple files at once using a wildcard or space-separated list, which is especially helpful when working on larger projects with several sensitive files..

ansible-vault encrypt file1.yml file2.yml

To verify the file encryption, use the cat command as shown.

cat mysecrets.yml
Fig 3: Verify Encrypted File in Ansible

How to View an Encrypted File in Ansible

If you want to view an encrypted file, simply pass the ansible-vault view command as shown below.

ansible-vault view mysecrets.yml

Once again, you will be prompted for a password. Once again, you will have access to your information.

Fig 4: View Encrypted File in Ansible

How to Edit an Encrypted File in Ansible

To make changes to an encrypted file, use the ansible-vault edit command as shown.

ansible-vault edit mysecrets.yml

As always, provide the password and thereafter proceed with editing the file.

Fig 5: Edit Encrypted File in Ansible

After you are done editing, save and exit the Vim editor.

How to Change Ansible Vault Password