In using Ansible, I'm trying to use a vaulted vars file to store private variables, and then using those in another vars file, in the same role. (The idea from 'Vault Pseudo leaf encryption' here.)
e.g. I have one standard vars file, roles/myrole/vars/main.yml
:
---
my_variable: '{{ my_variable_vaulted }}'
and then one which is encrypted, roles/myrole/vars/vaulted_vars.yml
:
---
my_variable_vaulted: 'SECRET!'
But when I run the playbook I always get '"ERROR! ERROR! 'my_variable_vaulted' is undefined"'.
I've tried it without encrypting the second file, to make sure it's not an issue with encryption, and I'm getting the same error.
That is not the best way to handle vault in ansibles. Much better approach is outlined in vault documentation for ansible. So you would create your basic variable for environment in
group_vars/all.yml
like that:And then in your
inventories/main
you decide which hosts should load which vault file to satisfy this variable. As example you can have that in yourinventories/main
:Then ansible will automatically fetch
production_vault.yml
ordevelopment_vault.yml
respectively fromgroup_vars
depending on which environment box belongs to. And then you can usemy_variable
in your roles/playbooks as before, without having to worry about fetching it from the right place.The reason why
my_variable_vaulted
wasn't available was because I hadn't included the variable file. I'd assumed that all files in a role'svars/
directory were picked up automatically, but I think that's only the case withvars/main.yml
.So, to make the vaulted variables available to all tasks within the role, in
roles/myrole/tasks/main.yml
I added this before all the tasks: