Hiding passwords in plain sight
Hiding passwords in plain sight is in direct contrast to the whole-file encryption we described previously. We’re still going to encrypt our sensitive data, but this time around we’ll encrypt only the sensitive data, and leave everything else in plain, unencrypted text:
- We will use the encrypt_string method. In this example, the password we want to encrypt is B@by-Y0dA and we will name the variable that identifies this password as admin_password.
$ ansible-vault encrypt_string –vault-password-file vault_password ‘B@by-Y0dA’ –name ‘admin_password’
In the terminal/console, once you press Enter you will see what ‘B@by-Y0dA’ looks like once encrypted:

Figure 8.23 – Encrypting secrets
- Next, we need to copy the output of that into a secrets.yml file (you could just append >> secrets.yml to the command entered previously to automatically copy the output to the file). Here’s an example:
$ ansible-vault encrypt_string –vault-password-file vault_password ‘B@by-Y0dA’ –name ‘admin_password’ >> secrets.yml
Your secrets.yml file should look something like this:

Figure 8.24 – Contents of secrets.yml file
IMPORTANT NOTE
You may notice the encrypted value is different every time you run the command, even when you encrypt the same value using the same password. The random salt changes each time you encrypt it; this is by design, and the intent is to ensure that the final encrypted output is never the same (even when using the same content).
- Now that you have it encrypted, you can replace the ansible_password value in your host file with the name of the variable that references the password (in this case, admin_password):
# hosts
[host1]
192.168.2.70
[host1:vars]
ansible_user=admin
ansible_password={{ admin_password }}
ansible_connection=ssh
ansible_shell_type=powershell
[host2]
192.168.2.71
[host2:vars]
ansible_user=admin
ansible_password={{ admin_password }}
ansible_connection=ssh
ansi
ble_shell_type=powershell
NOTE
The advantage of variable-level encryption is that files can still easily be read and understood because there will be a mixture of plaintext alongside the encrypted variables.
The source code for this recipe can be found at https://github.com/PacktPublishing/Oracle-Linux-Cookbook/tree/main/ch8/ansible-vault.