是否可以在循环中多次调用角色,如下所示:
vars:
my_array:
- foo
- bar
- baz
roles:
- role: foobar
with_items: my_array
我们怎么做?
答案 0 :(得分:36)
现在支持Ansible 2.3.0:
- name: myrole
with_items:
- "aone"
- "atwo"
include_role:
name: myrole
vars:
thing: "{{ item }}"
答案 1 :(得分:9)
目前有no way to loop over a role,但正如Google小组讨论中所提到的,您可以将一个列表或字典传递给该角色,然后在内部循环。
所以你可以这样做:
# loop_role/tasks/main.yml
- name: debug item
debug: var="{{ item }}"
with_items: my_array
然后像这样使用它:
- hosts: all
vars:
my_array:
- foo
- bar
- baz
roles:
- { role: loop_role, my_array: "{{ my_array }}" }
答案 2 :(得分:4)
此处记录了include_role
模块:https://docs.ansible.com/ansible/include_role_module.html
根据已在Ansible 2.2中引入的文档
答案 3 :(得分:2)
我在Ansible 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' }
答案 4 :(得分:0)
以下是在my_array上使用include_role循环的代码示例:
- name: Use role in loop
include_role:
name: myrole
loop: "{{ my_array }}"