gpt4 book ai didi

ansible - ansible中如何将列表转换为列表列表

转载 作者:行者123 更新时间:2023-12-02 03:00:21 27 4
gpt4 key购买 nike

我有一个列表,并将拆分转换为列表列表,请查找下面的示例,


List: ['sk','bk', 'ab','4',,'5',6','ku','in']
Expected output:
[
[sk','bk', 'ab','4'],
['5',6','ku','in]
]

注意:如果列表包含 12 个元素,则预期输出应有 3 个列表

你能知道如何在ansible中做到这一点

提前致谢,森蒂尔

最佳答案

还有更多选择。

给定列表声明变量step

  l: ['sk', 'bk', 'ab', '4', '5', '6', 'ku', 'in', '12', '34', '56', '78']
step: 4
  1. 使用 Jinja 过滤器 batch
  l_batch: "{{ l|batch(step) }}"

给出

  l_batch:
- [sk, bk, ab, '4']
- ['5', '6', ku, in]
- ['12', '34', '56', '78']

  • 使用Extended loop variables
  •     - debug:
    msg: "{{ _batch|to_yaml }}"
    loop: "{{ range(step, l_lenght|int + step, step)|list }}"
    loop_control:
    label: "{{ item }}"
    extended: true
    vars:
    l_lenght: "{{ l|length }}"
    split0: "{{ ansible_loop.previtem|default(0) }}"
    split1: "{{ ansible_loop.last|ternary(l_lenght, item) }}"
    _batch: "{{ l[split0|int:split1|int] }}"

    给出了删节

      msg: [sk, bk, ab, '4']
    msg: ['5', '6', ku, in]
    msg: ['12', '34', '56', '78']

  • 创建自定义过滤器插件
  • shell> cat plugins/filter/list_methods.py
    def list_split_period(l, p):
    split_list = []
    for i in range(p, len(l) + p, p):
    if i == p:
    split_list.append(l[0:p])
    j = i
    elif i > len(l):
    split_list.append(l[j:])
    else:
    split_list.append(l[j:i])
    j = i
    return split_list


    class FilterModule(object):

    def filters(self):
    return {
    'list_split_period': list_split_period,
    }

    然后,声明变量

      l_split: "{{ l|list_split_period(step) }}"

    给出

      l_split:
    - [sk, bk, ab, '4']
    - ['5', '6', ku, in]
    - ['12', '34', '56', '78']

    注释:

    • 用于测试的完整剧本示例
    - hosts: localhost

    vars:

    l: ['sk', 'bk', 'ab', '4', '5', '6', 'ku', 'in', '12', '34', '56', '78']
    step: 4

    l_batch: "{{ l|batch(step) }}"
    l_split: "{{ l|list_split_period(step) }}"

    tasks:

    - debug:
    var: l_batch|to_yaml

    - debug:
    var: l_split|to_yaml

    - debug:
    msg: "{{ _batch|to_yaml }}"
    loop: "{{ range(step, l_lenght|int + step, step)|list }}"
    loop_control:
    label: "{{ item }}"
    extended: true
    vars:
    l_lenght: "{{ l|length }}"
    split0: "{{ ansible_loop.previtem|default(0) }}"
    split1: "{{ ansible_loop.last|ternary(l_lenght, item) }}"
    _batch: "{{ l[split0|int:split1|int] }}"
    • 设置步骤:5给出
      l_batch:
    - [sk, bk, ab, '4', '5']
    - ['6', ku, in, '12', '34']
    - ['56', '78']

    l_split:
    - [sk, bk, ab, '4', '5']
    - ['6', ku, in, '12', '34']
    - ['56', '78']

    msg: [sk, bk, ab, '4', '5']
    msg: ['6', ku, in, '12', '34']
    msg: ['56', '78']

    关于ansible - ansible中如何将列表转换为列表列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60096256/

    27 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com