0

Im using Ansible 2.9 and i want to order msg devices by number, i have this msg :

msg:  "{{ facts['ansible_facts'] | to_json | from_json | json_query('ansible_net_interfaces[?starts_with(name,`pl2`)].name') | list| sort }}"

And i have this output:

ok: [localhost] => {
    "msg": [
        "pl2",
        "pl2.10",
        "pl2.100",
        "pl2.102",
        "pl2.11",
        "pl2.111" ] ... 

How can i make it show the output like this :

"pl2",
"pl2.10",
"pl2.11",
"pl2.12" ] ... 

And also how to catch the biggest pl2.* ? for example if the biggest number is pl2.250? Thanks!

gsr
  • 169
  • 2
  • 19
  • 1
    Write a filter. See [examples](https://github.com/vbotka/ansible-plugins/blob/master/filter_plugins/version_filters/version_filters.py). – Vladimir Botka Dec 09 '21 at 15:32
  • This seems to be a duplicate of [How to sort version numbers in Ansible](https://stackoverflow.com/questions/54025894/how-to-sort-version-numbers-in-ansible), however the most valuable answer from there, using version sort, is already posted here too. – U880D Dec 10 '21 at 12:55

1 Answers1

1

Write custom filter, e.g.

shell> cat filter_plugins/filter.py 
from distutils.version import LooseVersion

def version_sort(l):
    return sorted(l, key=LooseVersion)

class FilterModule(object):
    ''' Ansible filters for operating on versions '''

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

Given the list

  l:
  - pl2
  - pl2.10
  - pl2.100
  - pl2.102
  - pl2.11
  - pl2.111

the sorting works as expected

  l|version_sort:
  - pl2
  - pl2.10
  - pl2.11
  - pl2.100
  - pl2.102
  - pl2.111
Vladimir Botka
  • 58,131
  • 4
  • 32
  • 63