FreeKB - Ansible include_role
Ansible - include_role

Let's say you have a playbook named main.yml, and in this playbook, you want to run the foo.yml and bar.yml playbooks. This could be done using:

Let's say you have a playbook that should only invoke a role when a certain condition is met. Traditionally, you would use the when module and do something like this.

---
- hosts: all
  roles:
    - role: foo
      when: x is defined

    - role: bar
      when: y is defined

 

However, this is not ideal, as each tasks in the playbook that is not called will be skipped.

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

 

A better approach is to use include_role.

---
- hosts: all
  tasks:
    - name: include_role 'foo' when x is defined
      include_role:
        name: foo
      when: x is defined

    - name: include_role 'bar' when y is defined
      include_role:
        name: bar
      when: y is defined

 

Now, the role will be skipped, without iterating through each task in the role.

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

 


tasks_from

By default, the tasks in the main.yml file in the role will be invoked. In this example, the tasks in roles/foo/tasks/main.yml would be run.

- name: include_role 'roles/foo/tasks/main.yml'
  include_role:
    name: foo

 

If you have other yaml files in the role tasks directory, such as roles/foo/tasks/bar.yml, the tasks_from parameter can be used to invoke the tasks in bar.yml.

- name: include_role 'roles/foo/tasks/bar.yml'
  include_role:
    name: foo
    tasks_from: bar

 


vars_from

By default, the variable in the main.yml file in the role will be included. In this example, the variables in roles/foo/vars/main.yml would be included.

- name: include the variables in roles/foo/vars/main.yml
  include_role:
    name: foo

 

If you have other yaml files in the role vars directory, such as roles/foo/vars/bar.yml, the vars_from parameter can be used to invoke the variable in bar.yml.

- name: include the variables in roles/foo/vars/bar.yml
  include_role:
    name: foo
    vars_from: bar

 

Or, variables can be define for each role.

- include_role:
    name: foo
  vars:
    bar: Hello 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 53147 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   |