Q: What is the purpose of main.yml file in vars folder in ansible role?
A: Main reason is to customize role's default variables.
The variables defined in role/vars/main.yml override all variables defined in roles defaults, inventories, group_vars, host_vars, and all variables defined in the play before the role was included in the play. See Variable precedence: Where should I put a variable? for details.
For example, let's create a playbook
shell> cat playbook.yml
- hosts: localhost
vars:
test_var: test_var defined in the playbook vars
roles:
- role1
and let's create a role with empty roles/role1/vars/main.yml and simple debug task in roles/role1/tasks/main.yml
shell> cat roles/role1/tasks/main.yml
- debug:
var: test_var
shell> cat roles/role1/vars/main.yml
---
# vars file for role1
The play will display the variable defined in the playbooks' vars
shell> ansible-playbook test-14.yml
...
test_var: test_var defined in the playbook vars
Now, define the variable test_var in role's role1/vars/main.yml
shell> cat roles/role1/vars/main.yml
---
# vars file for role1
test_var: test_var defined in the role vars
The variable defined in the role's vars overridden the variable defined in the playbook's vars.
shell> ansible-playbook playbook.yml
...
test_var: test_var defined in the role vars
Notes:
- Do not put roles' vars/main.yml into the Ansible Galaxy git. This will preserve local customizations from updates and upgrades.