与itertools循环的可解性

2024-07-02 11:07:24 发布

您现在位置:Python中文网/ 问答频道 /正文

如何在ansible with loop中获得相同的结果

我想用

   - debug:
       msg: "{{ item.0 }} {{ item.1 }}"
     loop: "{{ gs_hostname | product(wl_hostname) | list }}"

但我得到:

ok: [localhost] => { "msg": { "gs-01": "wl-01", "gs-02": "wl-02", "gs-03": null, "gs-04": null } }

我所期望的是:

from itertools import cycle

gs_hostname = ["gs01", "gs02", "gs03", "gs04"]
wl_hostname = ["wl01", "wl02"]

for a,b in zip(gs_hostname, cycle(wl_hostname)):
    print (a,b)

结果:

gs01 wl01 gs02 wl02 gs03 wl01 gs04 wl02


Tags: loopgswithmsgansiblenullhostnamewl
2条回答

看起来Ansible中并没有任何本机功能可以实现这一点

也就是说,为了实现这一点,您可以使用一点计算和一个modulo与循环^{}耦合

根据剧本:

- hosts: all
  gather_facts: no  
        
  tasks:
    - debug:
        msg: "{{ item }} {{ wl_hostname[idx % wl_hostname | length] }}"
      loop: "{{ gs_hostname }}"
      loop_control:
        index_var: idx
      vars:
        gs_hostname: 
          - gs01
          - gs02
          - gs03
          - gs04
        wl_hostname: 
          - wl01
          - wl02

这将作为输出提供:

PLAY [all] ********************************************************************************************************

TASK [debug] ******************************************************************************************************
ok: [localhost] => (item=gs01) => {
    "msg": "gs01 wl01"
}
ok: [localhost] => (item=gs02) => {
    "msg": "gs02 wl02"
}
ok: [localhost] => (item=gs03) => {
    "msg": "gs03 wl01"
}
ok: [localhost] => (item=gs04) => {
    "msg": "gs04 wl02"
}

PLAY RECAP ********************************************************************************************************
localhost                  : ok=1    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

我找到了另一个解决方案:

- hosts: localhost
  connection: local
  gather_facts: False
  vars:
      gs_hostname: [gs-01, gs-02, gs-03, gs-04, gs-05, gs-06, gs-07]
      wl_hostname: [wl-01, wl-02, wl-03]
  tasks:
    - debug:
         msg: "{% set wl_list = wl_hostname %}
               {% set row_class = cycler(* wl_list) %}
               {% for gs in gs_hostname %}{{ gs }} - {{ row_class.next() }}{% endfor %}"

更多信息here

相关问题 更多 >