ansible - Ansible 中按自然字母数字顺序对列表进行排序

标签 ansible jinja2 ansible-template

有没有办法以自然的方式对 Ansible 或 Jinja 中的列表进行排序?

例如,这是列表

test
test123
test12
test5
test1234test
test22te

我需要它来考虑整个数字而不是单个数字,因此 test12 位于 test5 之下,依此类推。

最佳答案

给定列表

  l1:
    - test
    - test123
    - test12
    - test5
    - test1234test
    - test22te

创建一个具有整数类型属性index的列表,例如

    - set_fact:
        l2: "{{ l2|default([]) +
                [{'index': (_index|length > 0)|ternary(_index|int, 0),
                  'name': item}] }}"
      loop: "{{ l1 }}"
      vars:
        _regex: '^test(\d*)\D*$'
        _replace: '\1'
        _index: "{{ item|regex_replace(_regex, _replace) }}"
    - debug:
        msg: "{{ l2|sort(attribute='index')|
                    map(attribute='name')|
                    list }}"

给出

  msg:
  - test
  - test5
  - test12
  - test22te
  - test123
  - test1234test

无需迭代,声明变量

  _regex: '^test(\d*)\D*$'
  _replace: '\1'
  _index: "{{ l1|map('regex_replace', _regex, _replace)|map('int')|list }}"
  l2: "{{ dict(_index|zip(l1))|
                      dict2items|
                      sort(attribute='key')|
                      map(attribute='value')|
                      list }}"

给出相同的结果

  l2:
  - test
  - test5
  - test12
  - test22te
  - test123
  - test1234test

用于测试的完整剧本示例

- hosts: localhost

  vars:

    l1:
      - test
      - test123
      - test12
      - test5
      - test1234test
      - test22te

    _regex: '^test(\d*)\D*$'
    _replace: '\1'
    _index: "{{ l1|map('regex_replace', _regex, _replace)|map('int')|list }}"
    l2: "{{ dict(_index|zip(l1))|
                        dict2items|
                        sort(attribute='key')|
                        map(attribute='value')|
                        list }}"

  tasks:

    - debug:
        var: _index
    - debug:
        var: l2

关于ansible - Ansible 中按自然字母数字顺序对列表进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67601218/

相关文章:

ansible - 如何在 Ansible/Jinja2 中获取变量的插值

Ansible/Jinja2 如何将列表格式化为我的配置文件的字段?

ansible - 如何在 Ansible 中迭代多个列表/名称?

unix - Ansible不使用cp命令复制目录

shell - 如何使用 Ansible 自动化一次性任务?

python - 比较模板中的多个 forloop.counter 值

ansible - 如何根据条件打破 with_items 循环

ansible - 如何在 Ansible 中比较内核(或其他)版本号

python - 隐式访问SQLAlchemy类字段并修复 'object is not subscriptable'错误

python - 在 HTML 中的 url_for 上发送 GET 参数