Roles and Includes

Writing playbooks you need a mechanism for reusability / composeability. You actually got three:

- inclusion
- generalize your playbooks and organize them in roles
- move stuff in modules and have them merged

In [ ]:
cd /notebooks/exercise-09/

Import playbooks and Include tasks

You can:

To work on tasklist:

  • import static tasklists with import_tasks
  • include dynamic tasklists with include_tasks

Remember:

The use of the OLD 'include' for tasks has been deprecated. This feature will be removed in a future release.


In [ ]:
# This tasklist requires a variable!
!cat documentroot.yml

In [ ]:
# and here's a play using the include
!cat  web-1.yml

Exercise

Reuse the previously create files:

  • ansible.cfg
  • docker-inventory.py

to run web-1.yml on the web hosts.

Remember to reference to the ssh-key id_ansible!

Modify the playbook at will!


In [ ]:
!ansible-playbook  -v web-1.yml

Exercise

In web-1.yml:

- replace import_tasks with `include_tasks`
- read carefully the error message 

Write a simple web-3.yml which uses import_playbook


In [ ]:
!ansible-playbook web-2.yml

Roles

A role is a parametrized playbook that accomplishes a simple task, like:

- install & setup apache (eg. yum + firewall + selinux)
- run checks and send file to support
- implement a set of security policies
- ...

You can get roles from:

Creating roles

You can create a role using the ansible-galaxy command which creates:

  • create the role layout

Or via the molecule package which:

  • create the role layout
  • provides a test framework

In [ ]:
cd roles

In [ ]:
!ansible-galaxy init web

Role layout

Here's a role layout. Main files are:

  • README.md - the role description. Its format is very precise and you have to stick with it!
  • tasks/main.yml - the actual playbook. Can include other playbooks and reference other roles

Being a parameterized playbook, you need to reference parameters and variable, which are defined here:

  • defaults/main.yml
  • vars/main.yml

In [ ]:
!tree  .

Exercise

Inspect the newly created role tree

Exercise

Let's inspect this mongodb role


In [ ]: