Ansible - Passing variables into a Role

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.

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
...

 



Add a Comment




We will never share your name or email with anyone. Enter your email if you would like to be notified when we respond to your comment.





Please enter 1a952 in the box below so that we can be sure you are a human.




Comments

Web design by yours truely - me, myself, and I   |   jeremy.canfield@freekb.net   |