Each role can have it's own unique set of variables, and there are numerous ways to define the variables that will be used by a role. This is in the order of precedence, top down, where the option higher in the list takes precedence.
- Define variables using the --extra-vars command line option
- Define variables using the vars plugin
- Define variables in vars/main.yml
- Define variables in defaults/main.yml
For example, let's say you have a role named "foo" that contain main.yml.
/usr/local/ansible/roles/foo/tasks/main.yml
Let's say main.yml contains the following.
- name: output the bar variable
debug:
var: bar
vars option
Let's say your testing.yml playbook uses the foo role. Here is how you can assign a value of "Hello World" to the bar variable using the vars option.
---
- hosts: localhost
roles:
- role: foo
vars:
bar: "Hello World"
...
Or like this.
---
- hosts: localhost
roles:
- { role: foo, vars: { bar: "Hello World" } }
...
Invoking testing.yml should return the following.
TASK [foo: output the bar variable]
ok: [localhost] => {
"bar": "Hello World"
}
vars and defaults directories
Or, variables can be put in the roles/foo/defaults/main.yml file or the roles/foo/vars/main.yml file, like this.
bar: "Hello World"
As long as you are not using the --extra-vars command line option and your testing.yml does not contain the vars option, Ansible will next check roles/foo/vars/main.yml file for the bar variable and then roles/foo/defaults/main.yml.
---
- hosts: localhost
roles:
- role: foo
...
Did you find this article helpful?
If so, consider buying me a coffee over at