Using git diff with Ansible Vault encrypted files

Apr 25, 2016 using tags ansible, git

If you’ve ever worked with Ansible Vault encrypted files you’re probably used to seeing diffs that look like:

diff --git a/ansible/roles/znc/vars/main.yml b/ansible/roles/znc/vars/main.yml
index d1da576..46a4242 100644
--- a/ansible/roles/znc/vars/main.yml
+++ b/ansible/roles/znc/vars/main.yml
@@ -1,391 +1,392 @@

This really doesn’t work for when you need to go back through history to figure out what actually changed. We can do better!

Newer versions of ansible-vault come with a view option that does exactly what you expect – given a vault-encrypted file and a passphrase, it will display the contents of the file to stdout.

Another notable option is the --vault-password-file flag which gives you the option of specifying either a plaintext file with the vault passphrase, or an executable script that prints the passphrase to stdout (which comes in very handy for passphrases stored as environment variables – more on that later).

Add the following adiff function to your ~/.bashrc

function adiff() {
  local commit="$1"
  local file="$2"
  local vault_password_file="$3"

  if [ -z "$commit" -o -z "$file" ]; then
    echo "usage: adiff <commit> <file> [vault_password_file]"
    return 1

  if [ -z "$vault_password_file" ]; then

  diff -u \
    <( ansible-vault --vault-password-file="${vault_password_file}" view <( git show "${commit}^":"${file}" )) \
    <( ansible-vault --vault-password-file="${vault_password_file}" view <( git show "${commit}":"${file}" ))

Your Ansible Vault diffs will now look something like:

$ adiff 102094e70a2189ad3e134b73d18b4dd5a1e4325f ansible/roles/znc/vars/main.yml ansible/vault_pass.txt
--- /dev/fd/63  2016-04-25 21:15:01.390301209 -0400
+++ /dev/fd/62  2016-04-25 21:15:01.390301209 -0400
@@ -44,8 +44,8 @@
     Allow = *
     AltNick = marvin
     AppendTimestamp = false
-    AutoClearChanBuffer = true
-    AutoClearQueryBuffer = true
+    AutoClearChanBuffer = false
+    AutoClearQueryBuffer = false
     Buffer = 50
     DenyLoadMod = false
     DenySetBindHost = false
@@ -177,6 +177,12 @@
 znc_pem: |

Vault Passphrase in an Environment Variable

If you would rather not store your Ansible Vault passphrase in a plaintext file, you have the option of using an executable script instead. This is useful if you use environment variables for this sort of thing (more information available in the Ansible docs)

Here is one example of a

#!/usr/bin/env python
import os
print os.environ['ANSIBLE_VAULT_PASSWORD']

Assuming the executable bits are set on, you should now be able to:

ansible-vault --vault-password-file="" view ansible/roles/znc/vars/main.yml