Image: Pexels - Pixabay

Rekey with Ansible

ansible Mar 3, 2023

A few days ago there was a situation where all encrypted files in Ansible encrypted by ansible-vault had to be changed, re-encrypted with a new key.

Since I have a habit of encrypting any file in my inventory regardless of its contents this meant there were a lot of files that needed to change.

While researching through a famous search engine there already are a lot of posts on the internet about it and i tried one.

It looked promising but unfortunately didnt work.

Digging in some more it turned out to be so simple. There is no need for tools to do this.

To do a step by step.

Create new key

openssl rand -hex 32 >> ~/.ansible_new_key
chmod 600 ~/.ansible_new_key

Ansible.cfg

For now check and comment out vault_password_file in the ansible.cfg

Rekeying

Be sure to be in the ansible directory. And that you have sourced the virtualenvironment if applicable. My objective is to rekey my inventory but you could adopt the script to target roles and playbooks as well. Just be sure not to target the root of the Ansible directory.

for name in $(find ../ansible-inventory/ -type f -exec grep -q AES256 {} \; -print) ; do
  ansible-vault rekey --vault-password-file ~/.ansible_OLD_key \
    --new-vault-password-file ~/.ansible_new_key $name
done

Ansible.cfg

Change the vault_password_file to look at the new key. Be sure to store the old one somewhere in case you might need to fall back to it.

And thats all.

Tags

Riccardo B.

Riccardo is an all round Linux Systems Engineer with over 20 years of experience and a knack for Automation. Favoring acronyms like NAO, IaC, SRE and more. Also hardly ever writes in third person :)