Ansible 如何根据元素子字符串按降序对数组进行排序

问题描述

下面是我的数组:

- set_fact:
    diskout:
      - 85_20.198.65.132
      - 86_52.140.118.141
      - 84_20.198.75.31
      - 82_20.204.75.114
      - 83_20.204.24.160

我希望仅对由 _ 分隔的第一个子字符串进行降序排序,同时忽略下划线后面的内容

因此,我的预期输出是:

      - 86_52.140.118.141
      - 85_20.198.65.132
      - 84_20.198.75.31
      - 83_20.204.24.160
      - 82_20.204.75.114

我尝试了以下但没有给我想要的输出

- debug:
    msg: "The automation will run on {{ item }}"
  with_items: "{{ diskout | reverse | list }}"

你能推荐一下吗?

解决方法

创建索引,例如

    - debug:
        msg: "{{ _dict|dict2items|
                  sort(attribute='key',reverse=true)|
                  map(attribute='value')|
                  list }}"
      vars:
        _index: "{{ diskout|map('regex_replace','^(.*)_(.*)$','\\1')|list }}"
        _dict: "{{ dict(_index|zip(diskout)) }}"

给予

  msg:
  - 86_52.140.118.141
  - 85_20.198.65.132
  - 84_20.198.75.31
  - 83_20.204.24.160
  - 82_20.204.75.114

下一个选项可能会更快

    - debug:
        msg: "{{ _dict|sort(reverse=true)|map('extract',_dict)|list }}"
      vars:
        _index: "{{ diskout|map('regex_replace','\\1')|list }}"
        _dict: "{{ dict(_index|zip(diskout)) }}"