Different methods to include roles

There are several ways to include roles from playbooks or roles.

Classic

The classic way:

---
- name: Build a machine
  hosts: all
  
  roles:
    - robertdebock.bootstrap
    - robertdebock.java
    - robertdebock.tomcat

Or a variation that allows per-role variables:

---
- name: Build a machine
  hosts: all
  
  roles:
    - role: robertdebock.bootstrap
    - role: robertdebock.java
      vars: java_version: 9
    - role: robertdebock.tomcat

Include role

The include_role way:

---
- name: Build a machine
  hosts: all
  
  tasks:
    - name: include bootstrap
      include_role:
        name: robertdebock.bootstrap

    - name: include java
      include_role:
        name: robertdebock.java

    - name: include tomcat
      include_role:
        name: robertdebock.tomcat

Or a with_items (since Ansible 2.3) variation:

---
- name: Build a machine
  hosts: all
  
  tasks:
    - name: include role
      include_role:
        name: ""
      with_items:
        - robertdebock.bootstrap
        - robertdebock.java
        - robertdebock.tomcat

Sometimes it can be required to call one role from another role. I’d personally use import_role like this:

---
- name: do something
  debug:
    msg: "Some task"

- name: call another role
  import_role:
    name: role.name

If the role (role.name in this example) requires variables, you can set them in vars/main.yml, like so:

variable_x_for_role_name: foo
variable_y_for_role_name: bar

A real life example is my robertdebock.artifactory role calls robertdebock.service role to add a service. The code for the artifactory role contains:

# snippet
- name: create artifactory service
  import_role:
    name: robertdebock.service
# endsnippet

and the variable are set in [vars/main.yml](https://github.com/robertdebock/ansible-role-artifactory/blob/master/vars/main.yml) contains:

service_list:
  - name: artifactory
    description: Start script for Artifactory
    start_command: "/bin/artifactory.sh start"
    stop_command: "/bin/artifactory.sh stop"
    type: forking
    status_pattern: artifactory