'How can i optimize ansible's playbook

At this time my playbook looks like this:

    - role: co_java
      vars:
        co_java_version: jdk1.6.0_45
    - role: co_java
      vars:
        co_java_version: jdk1.8.0_161

Can I iterate with item? Desiderata:

    - role: co_java
      vars:
        co_java_version: {{ item }}
      with_items: 
         - jdk1.6.0_45
         - jdk1.8.0_161

Thanks



Solution 1:[1]

Ref: Roles doc page

You cannot do it with the classic way of calling role (like in you above example). But this would be possible with import_role and include_role available since ansible 2.4.

- name: playbook to install java
  hosts: my_hosts

  tasks:
    - name: Include role to install java versions
      include_role:
        name: co_java
      vars:
        co_java_version: "{{ item }}"
      loop:
        - jdk1.6.0_45
        - jdk1.8.0_161

Meanwhile, it might be easier and even more effective to modify your role to directly accept a list of jdks to install so the loop takes place directly in the relevant tasks. You could then call it with something like:

- name: playbook to install java
  hosts: my_hosts

  roles:
    - role: co_java
      vars:
        co_java_version:
          - jdk1.6.0_45
          - jdk1.8.0_161

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1