Written with Ansible 2.7.6
Define remote hosts in /etc/ansible/hosts
preferably in groups along with their variable groups. Write the variables simply in plain text.
# Inventory File /etc/ansible/hosts
[home]
192.168.0.103
192.168.0.105
[home:vars]
ansible_user=YOUR_REMOTE_USER
ansible_ssh_pass=YOUR_PASSWORD_FOR_SSH
From the docs, we see that host and group variables can be stored in individual files relative to the inventory file. As our Inventory file is at /etc/ansible/hosts
, our variables must be at /etc/ansible/group_vars/home
for the group home
.
So, our inventory file is reduced as :
# Inventory File /etc/ansible/hosts
[home]
192.168.0.103
192.168.0.105
and our new variable file is written as (in YAML) :
# Variables for group "home" in file /etc/ansible/group_vars/home
---
ansible_user: YOUR_REMOTE_USER
ansible_ssh_pass: YOUR_PASSWORD_FOR_SSH
As suggested in above linked article and Best Practices, we can separate the sensitive vars and encrypt them while refering them from another variables' file. Entire layout is shown below :
# Inventory File /etc/ansible/hosts
[home]
192.168.0.103
192.168.0.105
# vars file /etc/ansible/group_vars/home/vars
---
ansible_user: "{{ vault_ansible_user }}"
ansible_ssh_pass: "{{ vault_ansible_ssh_pass }}"
# vault file /etc/ansible/group_vars/home/vault
# Write actual sensitive stuff here
---
vault_ansible_user: YOUR_REMOTE_USER
vault_ansible_ssh_pass: YOUR_PASSWORD_FOR_SSH
Now, finally, encrypt the vault
file by ansible-vault encrypt /etc/ansible/group_vars/home/vault
. This will ask for a new password. Enter that and remember it!.
$ ansible home --ask-vault-pass -m ping
192.168.0.103 | SUCCESS => {
"changed": false,
"ping": "pong"
}
192.168.0.105 | SUCCESS => {
"changed": false,
"ping": "pong"
}