Variables
Precedence
- command line values (for example,
-u my_user
, these are not variables)- role defaults (as defined in Role directory structure) 1
- inventory file or script group vars 2
- inventory group_vars/all 3
- playbook group_vars/all 3
- inventory group_vars/* 3
- playbook group_vars/* 3
- inventory file or script host vars 2
- inventory host_vars/* 3
- playbook host_vars/* 3
- host facts / cached set_facts 4
- play vars
- play vars_prompt
- play vars_files
- role vars (as defined in Role directory structure)
- block vars (only for tasks in block)
- task vars (only for the task)
- include_vars
- set_facts / registered vars
- role (and include_role) params
- include params
- extra vars (for example,
-e "user=my_user"
)(always win precedence)
group_vars
group_vars
is a special folder to store variable for an Ansible Group.
You can specify: group_vars/group_name/some_name_file.yml
. Ansible will then go and parse all the files from group_vars/group_name/*.(yml|json)
Example
Given the inventory file
app:
hosts:
app1:
ansible_host: 192.168.60.4
app2:
ansible_host: 192.168.60.5
db:
hosts:
app3:
ansible_host: 192.168.60.6
server:
children:
db:
app:
vars:
ansible_user: vagrant
ansible_ssh_private_key_file: ~/.vagrant.d/insecure_private_key
In here, the groups are app
and db
and server
We want to create variables for db
Create group_vars/db
. Note again that ansible will parse all the *.yml
files in here*.
Create proxy.yml
proxy_setting:
http_proxy: localhost
https_proxy: localhost
Create regions.yml
---
regions:
available:
- us-west
- au-east
active: au-east
Now we can use this variable in our yml file like {{ proxy_setting }}
or {{ regions.available.active }}
Create a playbook variable-test.yml
- name: test the variables
hosts: db
tasks:
- name: print variables out
debug:
msg: "regions: {{regions}} proxy: {{proxy_setting}}"
Run with:
ansible-playbook -i staging.yml variable-test.yml
ok: [app3] => {
"msg": "regions: {'available': ['us-west', 'au-east'], 'active': 'au-east'} proxy: {'http_proxy': 'localhost', 'https_proxy': 'localhost'}"
}
Note
We can also declare our variable as json format. For example: group_vars/all/others.json
{
"available_commands": ["help", "top", "ps"],
"available_users": {
"austin": {
"is_admin": false
},
"david": {
"is_admin": true
}
}
}
We can then parse this variable in anywhere, for example tasks:
- name: print json variables
debug:
msg: "available_commands: {{available_commands}} available_users: {{available_users}}"
will print out:
ok: [app3] => {
"msg": "available_commands: ['help', 'top', 'ps'] available_users: {'austin': {'is_admin': False}, 'david': {'is_admin': True}}"
}
Or we can use it in another variable files (e.g group_vars/db/user.yml
):
admin_user: "{{available_users["david"]}}"