ganch.dev

Encrypt Ansible playbooks data with Vaults & git-crypt

· Georgi Ganchev

hugo-unpony-logo

When working with Ansible, we normally want to store all our playbooks somewhere in a repository, however, we also often need to store sensitive data that our playbooks rely on. The recommended way to store this data is to use vaults. Vaults are basic files, often created in vars directory and we can create as many vaults as we like. We then need to encrypt every single vault file with a password which should also be encrypted before pushing to our repository, this could be achieved with git-crypt - a tool that enables transparent encryption and decryption of files in a Git repository.

Let’s see how this all works in practice.

Vaults

The very first thing to do here is to create the ansible vault password which is used for encrypting our vault files, we’d create it like so:

$ echo "securepassword" > .vault-password

Add that password to the ansible configuration file ansible.cfg using the key vault_password_file

[defaults]
...
vault_password_file = ./.vault-password

Now create the vault itself

$ ansible-vault create group_vars/caddy/vault.yml

The file should automatically be encrypted with the password above. If we want to decrypt it to edit contents we could do:

$ ansible-vault decrypt group_vars/caddy/vault.yml

And then encrypt again before any git commits

$ ansible-vault encrypt group_vars/caddy/vault.yml

Git-Crypt

Let’s now setup git-crypt in our playbooks repository so that we can safely push our secrets. We obviously need to have git and git-crypt installed

$ sudo apt install git-crypt

Then go to the local repository location and initialize git-crypt

$ git-crypt init
Generating key...

There are two ways of encrypting a repository with git-crypt. The first method uses the repository key generated by the git-crypt init command which can also be shared with other repository contributors. We can to export it with

$ git-crypt export-key /path/to/key
It is recommended to store it safely and treat this key as the “master key” to the repository.

The second method is by using a GPG key. Chances are, you already have a GPG key, check with

gpg --list-keys

Then add the valid user GPG key to the repo, we can also add other contributors GPG keys

$ git-crypt add-gpg-user some.email@mymail.com

To get things encrypted, we first need to create a .gitattrubutes file in our ansible root repository containing all files that need to be encrypted, in our example this is the .vault_password file

$ echo ".vault-password filter=git-crypt diff=git-crypt" > .gitattributes

Commit and push

$ git add .
$ git commit -m 'encrypt vault password'
$ git push origin main

That’s it!

The .vault_password will now be encrypted in our repository.