Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort with JMESPath in ansible playbook?

I have an array returned by curl from consul during playing ansible playbook:

[
       { 
        "Node": {
            "Node": "test-eu-west-2-staging-0"
        },  
        "Node": {
            "Node": "test-nyc1-staging-0"
        },
        "Node": {
            "Node": "test-sfo1-staging-0"
        }
       }
]

I want to have it sorted by "Node": {"Node" : "hostname"} in ansible playbook

- name: Set TEST vars, servers info and number
    set_fact:
      TEST_SERVERS="{{ test.json | json_query('SOME SORTING QUERY') }}"
      TEST_SRV_NUM="{{ test.json | length }}"

I have read JMESPath and ansible docs for whole day but still don't know how to implement it (btw it is easy in jq sort_by(.Node.Node) but this trick is not applicable to ansible)

like image 484
Konstantin Shestakov Avatar asked Oct 26 '25 06:10

Konstantin Shestakov


1 Answers

As @techraf noted, your sample JSON is malformed. I can make a guess that you have a list of objects with Node.Node inside, in this case you can use sort Jinja2 filter:

---
- hosts: localhost
  gather_facts: no
  vars:
    myvar: [
       { "Node": { "Node": "test-c" } },
       { "Node": { "Node": "test-b" } },
       { "Node": { "Node": "test-a" } }
      ]
  tasks:
    - debug:
        msg: "{{ myvar | sort(attribute='Node.Node') }}"
like image 171
Konstantin Suvorov Avatar answered Oct 28 '25 20:10

Konstantin Suvorov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!