【问题标题】:Ansible with itertools cycleAnsible 与 itertools 循环
【发布时间】:2020-08-04 15:43:19
【问题描述】:

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

我想用

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

但我明白了:

好的:[本地主机] => { “味精”:{ “gs-01”:“wl-01”, "gs-02": "wl-02", “gs-03”:空, “gs-04”:空 } }

我的期望:

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

【问题讨论】:

    标签: python loops ansible cycle


    【解决方案1】:

    确实,Ansible 中似乎没有任何原生功能可以实现这一点。

    这就是说,您可以使用一点点计算和modulo 加上循环index_var 来实现这一点。

    鉴于剧本:

    - 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
    

    【讨论】:

    • 非常感谢你!!
    【解决方案2】:

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

    - 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

    【讨论】:

    猜你喜欢
    • 2016-09-18
    • 1970-01-01
    • 1970-01-01
    • 2021-09-14
    • 2017-09-06
    • 1970-01-01
    • 2015-10-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多