Search code examples
ansiblejinja2ansible-vault

How to include encrypted file in Ansible jinja template?


I have 2 jinja templates containing private key:

  • private.key (encrypted)
  • private-copy.key (need to include content of private.key)

private.key file is encrypted using ansible vault, e.g.

ansible-vault encrypt --vault-password-file ~/.pass.txt private.key

so its content looks like this:

$ANSIBLE_VAULT;1.1;AES256
123456789[...]

I'm trying to get the decrypted content of private.key

-----BEGIN RSA PRIVATE KEY-----
ABCDEfgh[...]
-----END RSA PRIVATE KEY-----

inside private-copy.key (and not its encrypted value).

I've tried the include jinja statement inside private-copy.key:

{% include "private.key" %}

but the result gives me the encrypted value in private-copy.key instead of the decrypted content of private.key.

I also know that I can use an encrypted variable and put it in private-copy.key instead of including encrypted file. For simplification purpose, I want to use directly the encrypted file (on certificates renewal, we get a file, I just wanted to use it directly).


Solution

  • Use the file lookup plugin: Ansible allows you to read the content of a file using the lookup('file', ...) plugin. When combined with ansible-vault for encrypted files, it automatically decrypts the content if the file is encrypted.

    # This is private-copy.key
    {{ lookup('file', 'private.key') }}