Home > Software engineering >  Ansible - nested loop over object without knowing object/key name
Ansible - nested loop over object without knowing object/key name

Time:11-09

I'm working on an ansible playbook, I need to get a value from a JSON API result. I want to get the value of the key "1h" without knowing the previous object (sd#eureka...), and i need to loops over all my results, and all my buckets.

{
  "etat_ms_rep": {
    "results": [
      {
          "buckets": {
            "sd#eureka#pixidanalyticsbackend#c3fb422bb36882d9f502092fd75fcb34": {
              "1h": -1,
              "1m": -1
            },
            "sd#eureka#pixidanalyticsbackend#348fdab155904e22ca0c744d0c052cf8": {
              "1h": 100,
              "1m": 100
            }
          }
      },
      {
          "buckets": {
            "sd#eureka#pixidorchestratorbackend#8fa3441c6c5caa2d5f0e3264a00be91b": {
              "1h": 100,
              "1m": 100
            },
            "sd#eureka#pixidorchestratorbackend#6dc48be83cb86ae1a73b344e9421ed8e": {
              "1h": 100,
              "1m": 100
            }
          }
      }
    ]
  }
}

I tried that but without success, it doesnt show the value of "1h" key...

 - name: Display all bucket info
    set_fact:
     test: "{{ etat_ms_rep.results | json_query(jmesquery) }}"
    vars:
      jmesquery: " [*].['1h'] "

CodePudding user response:

For example

    - name: Get the value of the key 1h
      debug:
        msg: "{{ etat_ms_rep.results | json_query(jmesquery) }}"
      vars:
        jmesquery: '[].*.*.["1h"]'

gives

  msg:
  - - - - -1
      - - 100
  - - - - 100
      - - 100

Flatten the list if you want to

    - name: Get the value of the key 1h
      debug:
        msg: "{{ etat_ms_rep.results | json_query(jmesquery) | flatten }}"
      vars:
        jmesquery: '[].*.*.["1h"]'

gives

  msg:
  - -1
  - 100
  - 100
  - 100
  • Related