Search code examples
ansiblehashicorp-vaultansible-vault

Ansible, get variable from vault before gathering facts


I used to store ansible_ssh_pass in host_vars, enctypted with ansible-vault, but now i want to move it to hashicorp-vault. I wrote a simple role to get this variable from hashicorp-vault and set it as ansible_ssh_pass, so i can connect to host via it. But unless i do it i can't gather facts, so the only way is to set gather_facts: no and run

- name: Gathering facts
  setup:

at the end of my role. But now i need to change my playbooks and some roles for this. Is there a better way to run role before gathering facts or force Ansible to get variable from hashicorp-vault?


Solution

  • It sounds like you should be using the hashi_vault lookup plugin.

    For example, you could set in your inventory something like this:

    all:
      vars:
        ansible_ssh_pass: "{{ lookup('hashi_vault', 'secret=secret/ssh_password:value' }}
      hosts:
        host1:
        host2:
    ...
    

    This would require you to have VAULT_ADDR and VAULT_TOKEN set appropriately in your environment.

    NB: I don't have a Vault instance to play with, but I do something very similar using the aws_secret lookup.