Search code examples
ansibleroles

Ansible - How to manage Large list of small tasks


I have written lots of small yaml task files for an ansible project. Only few of these tasks files are being reused (say 30%). I wonder how to manage this big list of tasks, should I convert all of them to roles, and call the playbook with roles: Playbook as below (pls ignore the syntaxe), will be clear, But I do not like to have a role for each simple task.

- name: playbook with roles for each task
  hosts: all
  roles:
    - small_task_1
    - small_task_2
    - small_task_3
    - small_task_4
    ....
    ....
    - small_task_20

I liked the idea of putting them 2-3 roles, and call the task with include_task (or import_task), but the problem is, to each call of a task, I have to add "import_role: , name: , tasks_from" EVEN THOUGH It's from the same role!

$ ansible-galaxy role list $ /home/user1/.ansible/roles

  • roles_a, (unknown version)
  • roles_b, (unknown version)

in roles_a and roles_b, I may have around 10 yaml tasks for each

,,,

  • name: playbook with 2 roles hosts: all

    - name: small task 1
      include_role:
        name: role_a
        tasks_from: small_task_1
    
    - name: small task 2
      include_role:
        name: role_a
        tasks_from: small_task_2
    
    ......
    ......
    
    - name: small task 9
      include_role:
        name: role_a
        tasks_from: small_task_9
    
    - name: small task 10
      include_role:
        name: role_a
        tasks_from: small_task_10
    

,,,

Above thing is not very handy...

I would like to group the tasks in a "role" (or any other ansible thing), and call the tasks from that group... something like :

,,,

  • name: playbook with 2 roles hosts: all

    - name: small tasks
      include_role:
        name: role_a
        tasks_from: small_task_1
        tasks_from: small_task_2
    
    ......
    ......
    
        tasks_from: small_task_9
        tasks_from: small_task_10
    

,,,

I've tried with block , but it does not shorten the playbook.

Can anyone guide me, please?


Solution

  • For your final example, you can just use a loop directive on your include_role task, like this:

    - hosts: localhost
      gather_facts: false
      tasks:
        - include_role:
            name: role_a
            tasks_from: "{{ item }}"
          loop:
            - small_task_1
            - small_task_2
            - small_task_3
            - small_task_4