One way of storing secrets within Ansible is to use the built-in
Vault and the
respective command-line tool ansible-vault
. A common use case is to
have a key file available locally (a file containing the secret key
information) and to use ansible-vault
to encrypt/decrypt files as
needed. The documentation on Ansible
Vault should get
you started.
Let’s assume that there is an encrypted file in
group_vars/mygroup/vault.yml
. In order change the content of the file,
one has to run:
$ ansible-vault edit group_vars/mygroup/vault.yml
$ # Your EDITOR of choice is spawned
The file gets decrypted and a fresh instance of your EDITOR of choice is loaded. On exit, the content of the buffer gets encrypted and saved back to the file.
There are some issues with this model:
- A fresh instance of Vim is spawn with every change
- Transparent editing is not possible
- No use of nice editing features such as diffing with Fugitive
- The interruption of the current workflow. For example, I need to background Vim or spawn a new shell, edit the encrypted file and get back to my previous Vim session.
One solution is to put the following snippet of Vim autocommands into
your ~/.vimrc
to handle Ansible Vault files transparently:
augroup ansible-vault
autocmd!
autocmd BufReadPre,FileReadPre vault.yml setlocal viminfo=
autocmd BufReadPre,FileReadPre vault.yml setlocal noswapfile noundofile nobackup
autocmd BufReadPost,FileReadPost vault.yml silent %!ansible-vault decrypt
autocmd BufWritePre,FileWritePre vault.yml silent %!ansible-vault encrypt
autocmd BufWritePost,FileWritePost vault.yml silent undo
augroup END
The snippet above creates a new autocommand group named ansible-vault and resets any existing autocommands within this group. Before loading, a few settings are adjusted to avoid the leakage of secret data. After the file is loaded, it gets decrypted on the fly and the buffer content is replaced with the clear text representation of the encrypted file. The content of the buffer is encrypted before it is written back to disk. After writing, the undo command is executed once to keep the clear text representation in the buffer in case further edits are needed.
Note: This autocommand group only kicks in for files named
vault.yml
(that’s how I name those files). If you have a different
naming schema, you need to adjust this pattern to suit your needs.
Hint: Take a look at this Stack Overflow
answer,
if you want use git diff
for Vault files.
Happy Vimming!