Ansible: How to iterate over a role with an array?

后端 未结 5 2280
遥遥无期
遥遥无期 2020-12-05 04:47

Is it possible to call a role multiple times in a loop like this:

vars:
  my_array:
    - foo
    - bar
    - baz 
roles:
  - role: foobar
    with_items: my         


        
相关标签:
5条回答
  • 2020-12-05 05:09

    Here is a code sample for using include_role looping on my_array:

    - name: Use role in loop
      include_role:
        name: myrole
      loop: "{{ my_array }}"
    
    0 讨论(0)
  • 2020-12-05 05:11

    There's no way to loop over a role currently but as mentioned in that Google Group discussion you can pass a list or dict to the role and then loop through that internally.

    So instead you could do something like:

    # loop_role/tasks/main.yml
    
    - name: debug item
      debug: var="{{ item }}"
      with_items: my_array
    

    And then use it like this:

    - hosts: all
      vars:
        my_array:
          - foo
          - bar
          - baz 
      roles:
        - { role: loop_role, my_array: "{{ my_array }}" }
    
    0 讨论(0)
  • 2020-12-05 05:13

    The include_role module is documented here: https://docs.ansible.com/ansible/include_role_module.html

    According to the docs it was introduced in Ansible 2.2 already

    0 讨论(0)
  • 2020-12-05 05:18

    I used something like below on Ansible version 2.8

    tasks:
      - name: looping role to create multiple filesystem
        include_role:
          name: /opt/ansible/playbook/app_filesystem
        vars:
          vgname: "{{ item.vgname }}"
          lvname: "{{ item.lvname }}"
          lvsize: "{{ item.lvsize }}"
          mountpoint: "{{ item.mountpoint }}"
        loop:
          - { vgname: 'vgapp', lvname: 'lvapp', lvsize: '30g', mountpoint: '/app' }
          - { vgname: 'vgapp', lvname: 'lvappzk', lvsize: '64g', mountpoint: '/app/z' }
          - { vgname: 'vgapp', lvname: 'lvappdatazk', lvsize: '+100%FREE', mountpoint: '/app/data/zookeeper' }
    
    tasks:
      - name: looping role to create multiple filesystem
        include_role:
          name: /opt/ansible/playbook/app_filesystem
        vars:
          vgname: "{{ item.vgname }}"
          lvname: "{{ item.lvname }}"
          lvsize: "{{ item.lvsize }}"
          mountpoint: "{{ item.mountpoint }}"
        loop:
          - { vgname: 'vgapp', lvname: 'lvapp', lvsize: '30g', mountpoint: '/app' }
          - { vgname: 'vgapp', lvname: 'lvappzk', lvsize: '64g', mountpoint: '/app/zookeeper' }
          - { vgname: 'vgapp', lvname: 'lvappdatazk', lvsize: '+100%FREE', mountpoint: '/app/data/zookeeper' }
    
    0 讨论(0)
  • 2020-12-05 05:29

    Now supported as of Ansible 2.3.0:

    - name: myrole
      with_items:
        - "aone"
        - "atwo"
      include_role:
        name: myrole
      vars:
        thing: "{{ item }}"
    
    0 讨论(0)
提交回复
热议问题