Ansible group_vars variables

Viewed 923

A best practice approach for this is to start with a group_vars/ subdirectory named after the group. Inside of this subdirectory, create two files named vars and vault. Inside of the vars file, define all of the variables needed, including any sensitive ones. Next, copy all of the sensitive variables over to the vault file and prefix these variables with vault_. You should adjust the variables in the vars file to point to the matching vault_ variables using jinja2 syntax, and ensure that the vault file is vault encrypted. - Source: https://docs.ansible.com/ansible/2.8/user_guide/playbooks_best_practices.html

I am using dynamic inventory and could not understand these best practices 100%.

group_vars/all/vars
group_vars/all/vault

content of vars:

db_username: ""
db_password: ""

content of vault:

vault_db_username: admin
vault_db_password: ****

Will this work?

1 Answers

Fix the content of vars (and encrypt the vault if you want to)

db_username: "{{ vault_db_username }}"
db_password: "{{ vault_db_password }}"

For example, create the group_vars and encrypt vault

shell> cat group_vars/all/vars 
db_username: "{{ vault_db_username }}"
db_password: "{{ vault_db_password }}"

shell> cat group_vars/all/vault 
vault_db_username: admin
vault_db_password: my_secret_passwd

shell> ansible-vault encrypt group_vars/all/vault 
Encryption successful

shell> cat group_vars/all/vault
$ANSIBLE_VAULT;1.1;AES256
36623432646131366464653635643533663266343733653236376366393739386137653434313435
6339313039643636623139396162346138393938346136370a333038623933396162363462313161
32623466353234313163353837323736383161643663626132326234356561656532353838356134
3936346631383633650a373735613931373664346464353832326637393766313064653063623363
61333134386132303464373064633937393864333131613233636231303633326664613836653265
36343731396163393963373564333032393136656632373530383930383730613762633031663938
363130326538373066396534313930346262

Then the playbook

shell> cat playbook.yml
- hosts: localhost
  tasks:
    - debug:
        var: db_username
    - debug:
        var: db_password

gives

shell> ansible-playbook playbook.yml 

  db_username: admin
  db_password: my_secret_passwd
Related