Learning DevOps
上QQ阅读APP看书,第一时间看更新

Protecting sensitive data with Ansible Vault

The configuration of a system often requires sensitive information that should not be in the wrong hands. In the Ansible tool, there is a sub-tool called Ansible Vault that protects the data transmitted to Ansible through playbooks.

We will see in our example how to manipulate Ansible Vault to encrypt and decrypt the information of the MySQL user.

The first step is to encrypt the group_vars/database/main.yml file that contains the values of the variables by executing the following command:

ansible-vault encrypt group_vars/database/main.yml

Ansible Vault requests the inclusion of a password that will be required to decrypt the file and then shows the execution of this command to encrypt the content of a file:

After the execution of this command, the content of the file is encrypted, so the values are no longer clear. The following is a sample from it:

To decrypt the file to modify it, it will be necessary to execute the decrypt command:

ansible-vault decrypt group_vars/database/main.yml

Ansible Vault requests the password that was used to encrypt the file, and the file becomes readable again.

In an Ansible usage automation process, it is preferable to store the password in a file in a protected location, for example, in the ~/.vault_pass.txt file.

Then, to encrypt the variable file with this file, we execute the ansible-vault command and add the --vault-password-file option:

ansible-vault encrypt group_vars/database/main.yml --vault-password-file ~/.vault_pass.txt

Now that the file is encrypted and the data is protected, we will run Ansible with the following commands:

In interactive mode, we will run the following:

ansible-playbook -i inventory playbook.yml --ask-vault-pass

Ansible asks the user to enter the password shown in the following screenshot:

In automatic mode, that is, in a CI/CD pipeline, we can add the --vault-password-file parameter with the path of the file that contains the password to decrypt the data:

ansible-playbook -i inventory playbook.yml --vault-password-file ~/.vault_pass.txt

That's all right. We just executed Ansible with data that is no longer clear in the code and with the use of the ansible-vault command.

The entire source code of the inventory, playbook, and roles is available here:  https://github.com/PacktPublishing/Learning_DevOps/tree/master/CHAP03/devopsansible.

In this section, we have seen how to protect sensitive data in your playbooks using the ansible-vault utility. We encrypted and decrypted variable files to protect them, and then re-ran Ansible with these encrypted files.

In the following section, we will see how to use Ansible with a dynamic inventory.