Ansible嵌套循环

时间:2018-11-21 02:35:29

标签: loops ansible

我有一个看起来像这样的变量:

device:
  - sdb: 2
  - sdc: 3
  - sdd: 4

如何通过ansible循环产生结果:

sdb 1
sdb 2
sdc 1
sdc 2
sdc 3
sdd 1
sdd 2
sdd 3
sdd 4

我尝试了with_sequenceloop_control,但是没有用。

3 个答案:

答案 0 :(得分:0)

使用ansible循环和jinja编写调试任务,这将为您提供所需的结果。根据需要进行重构。

- name: Debug device var
  debug:
    msg: "{% for key, value in item.iteritems() %}{% for i in range(value) %} {{ key }} {{ loop.index }} {% endfor %}{% endfor %}"
  loop: "{{ device }}"

答案 1 :(得分:0)

最后,我找到了解决方案,但是更改了变量的格式。变量更改为:

device:
  sdb: 2
  sdc: 3
  sdd: 4

结果是:

ok: [ceph-host-2] => (item=1) => {
    "msg": "sdd 1"
}
ok: [ceph-host-2] => (item=2) => {
    "msg": "sdd 2"
}
ok: [ceph-host-2] => (item=3) => {
    "msg": "sdd 3"
}
ok: [ceph-host-2] => (item=4) => {
    "msg": "sdd 4"
}

TASK [osd : debug] 
ok: [ceph-host-2] => (item=1) => {
    "msg": "sdb 1"
}
ok: [ceph-host-2] => (item=2) => {
    "msg": "sdb 2"
}

TASK [osd : debug] 
ok: [ceph-host-2] => (item=1) => {
    "msg": "sdc 1"
}
ok: [ceph-host-2] => (item=2) => {
    "msg": "sdc 2"
}
ok: [ceph-host-2] => (item=3) => {
    "msg": "sdc 3"
}

main.yml

- include_tasks: inner.yml
  loop: "{{ device.keys() }}"
  loop_control:
    loop_var: outer_item

inner.yml

- debug:
    msg: "{{ outer_item }} {{ item }}"
  with_sequence: count={{ device[outer_item] }}

答案 2 :(得分:0)

变量为:

device:
  - sdb: 2
  - sdc: 3
  - sdd: 4

main.yml

- include_tasks: inner.yml
  loop: "{{ device }}"
  loop_control:
    loop_var: outer_item

inner.yml

- debug:
    msg: "{{ outer_item.keys()[0] }}  {{ item }}"
  with_sequence: count={{ outer_item.values()[0] }}