0

Below is my array:

- 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

I wish to sort this in descending order upon just the first substring separated by _ while ignoring whatever is after the underscore.

Thus, my expected output is:

      - 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

I tried the below but it did not give me the desired output:

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

Can you please suggest?

Ashar
  • 2,942
  • 10
  • 58
  • 122
  • Does [how to sort ... numbers in Ansible](https://stackoverflow.com/questions/54025894/) answer your question? – U880D Jun 22 '21 at 06:50

1 Answers1

2

Create index, e.g.

    - 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)) }}"

gives

  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

The next option might be faster

    - debug:
        msg: "{{ _dict|sort(reverse=true)|map('extract', _dict)|list }}"
      vars:
        _index: "{{ diskout|map('regex_replace', '^(.*)_(.*)$', '\\1')|list }}"
        _dict: "{{ dict(_index|zip(diskout)) }}"
Vladimir Botka
  • 58,131
  • 4
  • 32
  • 63