Interview Prep/Ansible/Roles, Collections and Galaxy

What are the ways to use a role in a play?

IntermediateConceptRoles, Collections and Galaxy
Answer
- hosts: web
  roles:                      # static, runs after pre_tasks
    - common
    - { role: nginx, nginx_port: 8080 }
  tasks:
    - ansible.builtin.import_role: { name: app }    # static, in task order
    - ansible.builtin.include_role:                 # dynamic, can loop and use when
        name: monitoring
      when: monitoring_enabled | bool

roles: is the classic form. import_role and include_role let you place a role in the middle of a task list and run it conditionally. Dynamic include_role is evaluated at run time, so tags and --list-tasks do not see inside it without apply.

All Ansible questions Roadmap: Ansible

More on Roles, Collections and Galaxy