Sobes.tech
Junior

How do you invoke roles in an Ansible playbook?

sobes.tech AI

Answer from AI

Roles in Ansible can be invoked in several ways within a playbook.

  1. Using the roles keyword at the playbook level:

    # playbooks/my_playbook.yml
    - name: Applying roles to servers
      hosts: webservers
      become: yes
      roles:
        - role: common  # Calling the 'common' role
        - role: nginx   # Calling the 'nginx' role
          vars:         # Passing variables to the role
            nginx_port: 8080
        - another_role # Shortened form of invocation
    

    This method is used for calling roles that will be executed sequentially for all hosts defined in the hosts section.

  2. Using the include_role module in a task list:

    # playbooks/my_playbook.yml
    - name: Applying roles with conditions
      hosts: appservers
      tasks:
        - name: Include database role (only for dev)
          include_role:
            name: database
          when: env == 'dev' # Calling role with condition
    
        - name: Include application role
          include_role:
            name: app
          vars:
            app_version: 1.2.0 # Passing variables to the role
    

    The include_role module executes the role as if it were a list of tasks included in the current play. It allows using conditions (when) and loops (loop) to control role execution.

  3. Using the import_role module in a task list:

    # playbooks/my_playbook.yml
    - name: Import application role
      hosts: appservers
      tasks:
        - name: Import application role for all hosts
          import_role:
            name: app
          vars:
            app_config_file: /etc/app/config.conf # Passing variables
    

    The import_role module is processed at parse time, before actual execution. This means that directives like when will apply to all tasks within the role, not just the role invocation itself. Variables passed via vars will be available inside the role.

The key difference between include_role and import_role lies in processing time: import_role is processed statically at parse time, while include_role is dynamic during playbook execution. This affects the ability to use conditions and loops:

Functionality include_role import_role
Processing Dynamic Static
Using when to invoke Yes No
Using loop to invoke Yes No
Ability to use variables defined earlier in the play Yes No

The choice between methods depends on the required flexibility and processing time. For simple role inclusion, the roles keyword or import_role is usually sufficient. For more complex scenarios with conditions and loops, include_role is used.