How to use an ansible-vault encrypted password in inventory file


I want to use encrypted passoword in my inventory file with ansible-vault, then run playbooks against that file. Something like:

ansible-playbook --ask-vault-pass -i inventory test.yml

I tried for single password for all the hosts and it worked fine, but need to use different password for different hosts. How we can use the variable generated using ansible-vault in inventory file?

Below is the code I have tired:

Generate ansible-vault encrypted string

ansible-vault encrypt_string 'abc123' --name ansible_ssh_pass > a_password_file

test.yml file

- hosts: hostgroup_1
    - a_password_file
    - command: date
      register: output

    - debug:
        msg: "{{ output.stdout }}"

inventory file:

[hostgroup_1] ansible_host=xx.xx.xx.xx ansible_user=root ansible_host=xx.xx.xx.xx ansible_user=root

[hostgroup_2] ansible_host=xx.xx.xx.xx ansible_user=root


ansible-playbook -i inventory --ask-vault-pass test.yml

Vault password:

PLAY [valut test] *****************************************************************************************************************************************

TASK [Gathering Facts] ************************************************************************************************************************************
ok: []
ok: []

TASK [command] ********************************************************************************************************************************************
changed: []
changed: []

TASK [debug] **********************************************************************************************************************************************
ok: [] => {
    "msg": "XXX XXX  XX XX:XX:XX XXX XXXX"
ok: [] => {
    "msg": "XXX XXX  XX XX:XX:XX XXX XXXX"

PLAY RECAP ************************************************************************************************************************************************ : ok=3    changed=1    unreachable=0    failed=0 : ok=3    changed=1    unreachable=0    failed=0

In the above code I used same ansible_ssh_pass for all the hosts, but want to use below inventory file which include different passoword for each hosts

inventory file:

[hostgroup_1] ansible_host=xx.xx.xx.xx ansible_user=root  ansible_ssh_pass=abc123 ansible_host=xx.xx.xx.xx ansible_user=root  ansible_ssh_pass=123abc

[hostgroup_2] ansible_host=xx.xx.xx.xx ansible_user=root  ansible_ssh_pass=xyz098

Best Solution

Save vault encrypted files in host_vars subdirectory under the inventory, for each host respectively.

See Splitting Out Host and Group Specific Data for details.

Related Question