Skip to content

Instantly share code, notes, and snippets.

@sakshamsaxena
Last active February 14, 2019 07:30
Show Gist options
  • Save sakshamsaxena/514b0393413f41e8f7c5ca117254e89a to your computer and use it in GitHub Desktop.
Save sakshamsaxena/514b0393413f41e8f7c5ca117254e89a to your computer and use it in GitHub Desktop.
A simple gist dscribing how to manage variables for Ansible Inventory

3 Ways To Manage Variables in Ansible Inventory

Written with Ansible 2.7.6

1. Straight Up Simple

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

2. Mention Variables in group_vars

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

3. Separate sensitive variables in group_vars and encrypt them

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!.

Invoke Ansible !

$ 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"
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment