This assumes you have gone through our Ansible - Getting Started with SSH article. Use the ansible-vault create command is used to create an encrypted file. In this example, password.yml is created.
ansible-vault create password.yml
You will be prompted to create a new vault password. Ensure your vault password is different from your SSH password.
New Vault password:
After entering your new vault password, the file will open in your default editor. Enter your ssh password and save password.yml.
-rw-------. 1 john.doe john.doe 355 Mar 16 18:48 password.yml
Use the cat command to view the encrypted data returned by password.yml.
$ANSIBLE_VAULT;1.1;AES256
66303833643731313633343266616162613965636161313534376563383639646463376630626635
3136316663626536303061333531303234616562323637330a373633393736393863373566623261
65643764336263613730666665663763383063386137383331386136366232666637626566653032
3933393061666138650a656238386665343838613833643435623932306539633138376533613039
6531
Create the group_vars directory and all.yml file.
mkdir /etc/ansible/group_vars
touch /etc/ansible/group_vars/all.yml
Update the all.yml file to contain your SSH username and the encrypted content of password.yml.
IMPORTANT - Indentation matters here. There must be exactly 2 spaces before the encrypted password string
ansible_connection: ssh
ansible_user: john.doe
ansible_ssh_pass: !vault |
$ANSIBLE_VAULT;1.1;AES256
66303833643731313633343266616162613965636161313534376563383639646463376630626635
3136316663626536303061333531303234616562323637330a373633393736393863373566623261
65643764336263613730666665663763383063386137383331386136366232666637626566653032
3933393061666138650a656238386665343838613833643435623932306539633138376533613039
6531
Remove the password.yml file, as it is no longer needed, since the encrypted password has been embedded into all.yml.
rm password.yml
Create a file that contains the vault password you created.
echo 'your_vault_password' > vault_password.txt
Update the vault_password.txt file so that it can only be read by the file owner.
chmod 400 vault_password.txt
You can now use the --vault-password-file option on the command line. In this scenario, you will not be prompted for the vault password.
ansible all -m ping --vault-password-file 'vault_password.txt'
Better yet, update /etc/ansible/ansible.cfg to contain the vault_password file.
vault_password_file=/path/to/password.txt
You should now be able to issue an ansible command without having to provide your SSH password.
ansible all -m ping