3

I need to encrypt a file using ansible-vault. I would like to perform the encryption only if the file is not already encrypted by ansible vault. I am trying to use this task in my Ansible playbook:

- local_action: command
    ansible-vault encrypt path/to/file
  when: <when file is not already encrypted by ansible-vault>

Is there a logic to use in the conditional statement that will check if a file is already encrypted by ansible-vault?

edesz
  • 11,756
  • 22
  • 75
  • 123

1 Answers1

2

There is likely a myriad of ways to do it, all having little to do with Ansible and Ansible Vault itself. Here's one:

- local_action: shell
    head -1 {{ file }} | grep -v -q \$ANSIBLE_VAULT && ansible-vault encrypt {{ file }}

You'll also need --vault-password-file otherwise Ansible will stop processing and wait on prompt.

techraf
  • 64,883
  • 27
  • 193
  • 198
  • Thanks! Yup, I have the vault password file set up as you were saying. In `grep -v -q \$ANSIBLE_VAULT` are you just checking if the file starts with the text `$ANSIBLE_VAULT`? – edesz Nov 05 '17 at 01:16
  • 1
    Checking if the line in stdin does not have `$ANSIBLE_VAULT` string. – techraf Nov 05 '17 at 01:17
  • Oh, yeah, only encrypt if it does not have it. I see it is simpler than I was thinking....I thought ansible-vault had some built-in functionality for this. Thanks! – edesz Nov 05 '17 at 01:18