FreeKB - Ansible Role Variables
Ansible - Role Variables

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 module
  • Define variables in vars/main.yml
  • Define variables in defaults/main.yml

For example, let's say you have two roles, "foo" and "bar". Here is how to define variables using the vars module.

---
- hosts: all
  roles:
    - role: foo
      vars:
        var: "Hello"
    - role: bar
      vars:
        var: "World"

 

Or like this.

---
- hosts: all
  roles:
    - { role: foo, vars: { var: "Hello" } }
    - { role: bar, vars: { var: "World" } }

 

Let's say /etc/ansible/roles/foo|bar/tasks/main.yml contains:

- name: variable test
  debug:
    msg: "{{ var }}"

 

Invoking master.yml should return the following.

TASK [/etc/ansible/roles/foo: variable test] 
ok: [server1.example.com] => {
    "msg": "Hello"
}

TASK [/etc/ansible/roles/bar: variable test] 
ok: [server1.example.com] => {
    "msg": "World"
}

 

Or, variables can be put in the defaults/main.yml file or the vars/main.yml file. Let's say /etc/ansible/roles/foo/vars/main.yml contains:

var: "Hello"

 

Let's say /etc/ansible/roles/bar/vars/main.yml contains:

var: "World"

 

Invoking master.yml should return the following.

TASK [/etc/ansible/roles/foo: variable test] 
ok: [server1.example.com] => {
    "msg": "Hello"
}

TASK [/etc/ansible/roles/bar: variable test] 
ok: [server1.example.com] => {
    "msg": "World"
}


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