Search code examples
ansiblepassword-encryptionansible-inventoryansible-vault

How can I 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
  vars_files:
    - a_password_file
  tasks:
    - command: date
      register: output

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

inventory file:

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

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

Output:

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

Vault password:

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

TASK [Gathering Facts] ************************************************************************************************************************************
ok: [xxx.xxx.com]
ok: [xxx.xxx.com]

TASK [command] ********************************************************************************************************************************************
changed: [xxx.xxx.com]
changed: [xxx.xxx.com]

TASK [debug] **********************************************************************************************************************************************
ok: [xxx.xxx.com] => {
    "msg": "XXX XXX  XX XX:XX:XX XXX XXXX"
}
ok: [xxx.xxx.com] => {
    "msg": "XXX XXX  XX XX:XX:XX XXX XXXX"
}

PLAY RECAP ************************************************************************************************************************************************
xxx.xxx.com : ok=3    changed=1    unreachable=0    failed=0
xxx.xxx.com : 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]
xxx.xxx.com ansible_host=xx.xx.xx.xx ansible_user=root  ansible_ssh_pass=abc123
xxx.xxx.com ansible_host=xx.xx.xx.xx ansible_user=root  ansible_ssh_pass=123abc

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

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.