Usually, when I want to open a file encrypted by ansible-vault for editing, I just run ansible-vault edit <filename> - this decrypts the file to a temporary file and opens it for editing.

However, what I want to know is how to achieve this from within vim, e.g. by running a shell command using the :! ...command... syntax. For instance, I know that I can decrypt the file by open the encrypted file in vim, then running this:

:! ansible-vault edit %

But that opens the file with ansible-vault in a different window, and then you have to press a key to return to vim.

What I want to do is to be able to open this file with vim such that I can edit it alongside other regular files or files that are encrypted with ansible-vault. Currently I'm doing this by opening several tmux panes, but that's kind of a PITA.

  • Have you tried running :r! asnsible-vault edit ... . Editing normal files within vi(m) would be :e filename May 19, 2017 at 12:08

2 Answers 2


I've been doing this from inside vim when editing an encrypted vault file:

:!ansible-vault --vault-password-file=~/.vault_pass decrypt %

Make a change and then re-encrypt the file:

:!ansible-vault --vault-password-file=~/.vault_pass encrypt %

The vault password goes in ~/.vault_pass as plaintext

To just view the contents and then go back to the original encrypted file (using git as the SCM and fugitive.vim plugin), first decrypt and when done:

:Git checkout %

I might create a function or aliases for those commands to make it quicker in the future. For now I do a command history search so I don't have to type the whole thing every time:

q: /decrypt N enter


I managed to do that using

%! ansible-vault decrypt --output -

To encrypt the buffer, use

%! ansible-vault encrypt --output -

It would be great to be able to automate this. I achieved some degree of success with

autocmd BufNewFile,BufRead *
  \ if getline(1) =~ '$ANSIBLE_VAULT;.*;AES256'     |
  \   execute '%! ansible-vault decrypt --output -' |
  \ endif

I was however unable to set an autocmd for reencrypting the content of the buffer at exit.

  • This looks great. I'm not great with Vim programming, but could we use the BufWrite autocmd-event to encrypt the contents of the file? Nov 26, 2021 at 9:37
  • 1
    If you find a way, I am interested! Unfortunately, I was never able to get it to work flawlessly.
    – user48678
    Nov 26, 2021 at 9:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.