gsr
gsr

Reputation: 189

Ansible sort output by numbers

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!

Upvotes: 0

Views: 324

Answers (1)

Vladimir Botka
Vladimir Botka

Reputation: 68044

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

Upvotes: 1

Related Questions