Home encrypt_all_vars_on_commit_with_ansible_vault
Post
Cancel

encrypt_all_vars_on_commit_with_ansible_vault

Encrypting sensitive information automatically on git commit for ansible

I have a large git repo that I use to manage all of my ansible configurations on my development box. I have my a lot of my user login passwords and keys stored in group and host var files on my machine, and I want to make a backup of them.
Because pushing unencrypted secrets in Github is bad, I created a blank file at hooks/pre-commit and made it executable

1
2
touch "path to repo/.git/hooks/pre-commit"
chmod +x "path to repo/.git/hooks/pre-commit"

Inside the file I put:

1
2
3
4
5
#!/bin/bash
# Change the password location and environment
for i in $(find ansible/inventories/{environment}/group_vars -type f); do ansible-vault encrypt $i  --vault-password-file "{Location of the password  file}" && echo $i encrypted ; done
for i in $(find ansible/inventories/{environment}/host_vars -type f); do ansible-vault encrypt $i  --vault-password-file "{Location of the password file}" && echo $i encrypted ; done
echo "Commiting"

This will automatically encrypt all of my group and host vars before they are committed, when ever I run git commit.

I thought it might be a good idea to write a decrypting script as well for when I wanted to work with them.

1
2
3
4
5
6
#!/bin/bash
# tools/unlock_ansible.sh
# Change the password location and environment
for i in $(find ansible/inventories/{environment}/group_vars -type f); do ansible-vault decrypt $i  --vault-password-file "{Location of the password  file}" && echo $i decrypted ; done
for i in $(find ansible/inventories/{environment}/host_vars -type f); do ansible-vault decrypt $i  --vault-password-file "{Location of the password  file}" && echo $i decrypted ; done
echo "Files decrypted"

I hope you find this useful when working with ansible in git repos!

This post is licensed under CC BY 4.0 by the author.