Variable precedence
Tip
We recommend to use the Sandbox to play around with this example.
Tip
All the files from this section are in variable-precedence.zip.
In Hello World, Hello World with Vault and Hello World with Jinja, we saw that variables can be declared in multiple places. Best practices are
keep passwords and secrets in vault.
keep variables shared among managed nodes in the group level of the inventory. A special group named
allcan be used for variables shared among all managed nodes.keep variables specific to a managed node in the host level.
This best practices help to avoid declaring variables in two or more places and have to worry about variable precedence.
Note
The full list of variable precedence is documented in Understanding variable precedence.
Vault
The decrypt version is
ansible_password: 123
Because the vault is passed using --extra-vars, ansible_password has the highest precedence possible and will override all other occurences.
Inventory
all:
vars:
ansible_user: ansible
frontend:
vars:
hello_world_text: "Hello from frontend"
hosts:
managed_node_01:
managed_node_02:
hello_world_text: "Hello from node 02"
backend:
vars:
hello_world_text: "Hello from backend"
hosts:
managed_node_03:
The variables in the special group all are override by the variables in the group level that are override by the variables in the host level.
Playbook
- name: My first play
hosts:
- frontend
- backend
tasks:
- name: Print variable hello_world_text
ansible.builtin.debug:
msg: "{{ hello_world_text }}"
Running
cd variable-precedence
ansible-playbook \
--ask-vault-pass \
-i inventories/production.yml \
--extra-vars @vault/production \
playbook.yaml
Note
The password for the vault used in the example is 123. You must use a strong passwords, for example, a minimum of 8 randomly generated characters.
returns
PLAY [My first play] ***********************************************************
TASK [Gathering Facts] *********************************************************
ok: [managed_node_02]
ok: [managed_node_03]
ok: [managed_node_01]
TASK [Print ansible_password] **************************************************
ok: [managed_node_01] => {
"msg": "Hello from frontend"
}
ok: [managed_node_02] => {
"msg": "Hello from node 02"
}
ok: [managed_node_03] => {
"msg": "Hello from backend"
}
PLAY RECAP *********************************************************************
managed_node_01 : ok=2 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
managed_node_02 : ok=2 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
managed_node_03 : ok=2 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0