как получить имя отображаемого свойства json_query в доступной книге воспроизведения

У меня в качестве примера есть этот блок json:

"msg": {
        "10.10.28.10": {
            "core": 23,
            "cpuCoreUsage": 0.0,
            "cputhreshold": 80,
            "status": "healthy",
            "status_code": 0,
            "status_reason": "Checks passed",
            "timestamp": 1614281443,
            "total": 0
        },
        "10.10.28.5": {
            "core": 18,
            "cpuCoreUsage": 2.0,
            "cputhreshold": 80,
            "status": "healthy",
            "status_code": 0,
            "status_reason": "Checks passed",
            "timestamp": 1614281443,
            "total": 0
        },
        "capacity": 1080
}

Я пытаюсь понять, как я могу получить этот вывод с именем свойства и статусом, чтобы он выглядел примерно так.

DESIRED OUTPUT:
IP: 10.10.28.5, status: healthy, status_code: 0
IP: 10.10.28.10, status: healthy, status_code: 0

Я могу распечатать все, кроме IP-части, следующим образом:

  - name: STATUS QUERY
    debug:
      msg: "code: {{ item }}"
    loop: "{{ data.json | json_query(status_code_query) | list }}"
    vars:
            status_code_query: "*.{statuscode: status_code, status: status}"

person confusedjoe    schedule 25.02.2021    source источник


Ответы (1)


Я бы не стал использовать для этого JMESPath, причина в том, что, хотя он неплохо справляется с запросами JSON, он не очень хорош для отображения ключей JSON.

Функция keys() наиболее близка к вам, но она даст вам массив, и поскольку вы не можете вернуться к родительскому узлу, вы не можете сделать что-то вроде:

*.{IP: keys($)[0], statuscode: status_code, status: status}

Хотя это довольно часто запрашиваемая функция: https://github.com/jmespath/jmespath.js/issues/22


Теперь, чтобы решить ваш вариант использования, вы можете использовать keys() функция, но одна из Python.

У вас также есть проблема, заключающаяся в том, что все ваши значения data.json не являются словарями: в "capacity": 1080 значение - это просто int.

Вы можете обойти эту странную структуру данных с помощью теста when и проверить, действительно ли ваше значение _ 8_ (или, другими словами, словарь).

Учитывая пьесу:

- hosts: all
  gather_facts: yes

  tasks:
    - debug: 
        msg: >-
          IP: {{ item }}, 
          status: {{ data.json[item].status }}, 
          status_code: {{ data.json[item].status_code }}
      loop: "{{ data.json.keys() }}"
      when: data.json[item] is mapping
      vars:
        data:
          json:
            10.10.28.10:
              core: 23
              cpuCoreUsage: 0
              cputhreshold: 80
              status: healthy
              status_code: 0
              status_reason: Checks passed
              timestamp: 1614281443
              total: 0
            10.10.28.5:
              core: 18
              cpuCoreUsage: 2
              cputhreshold: 80
              status: healthy-
              status_code: 0-
              status_reason: Checks passed
              timestamp: 1614281443
              total: 0
            capacity: 1080

Это дает резюме:

PLAY [all] **********************************************************************************************************

TASK [Gathering Facts] **********************************************************************************************
ok: [localhost]

TASK [debug] ********************************************************************************************************
ok: [localhost] => (item=10.10.28.10) => {
    "msg": "IP: 10.10.28.10,  status: healthy,  status_code: 0"
}
ok: [localhost] => (item=10.10.28.5) => {
    "msg": "IP: 10.10.28.5,  status: healthy-,  status_code: 0-"
}
skipping: [localhost] => (item=capacity) 

PLAY RECAP **********************************************************************************************************
localhost                  : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   

Тем не менее, это также идеальный вариант использования для dict2items фильтр:

- hosts: all
  gather_facts: yes

  tasks:
    - debug: 
        msg: >-
          IP: {{ item.key }}, 
          status: {{ item.value.status }}, 
          status_code: {{ item.value.status_code }}
      loop: "{{ data.json | dict2items }}"
      when: item.value is mapping
      vars:
        data:
          json:
            10.10.28.10:
              core: 23
              cpuCoreUsage: 0
              cputhreshold: 80
              status: healthy
              status_code: 0
              status_reason: Checks passed
              timestamp: 1614281443
              total: 0
            10.10.28.5:
              core: 18
              cpuCoreUsage: 2
              cputhreshold: 80
              status: healthy-
              status_code: 0-
              status_reason: Checks passed
              timestamp: 1614281443
              total: 0
            capacity: 1080

Получил бы такое же резюме.

person β.εηοιτ.βε    schedule 25.02.2021
comment
Спасибо за помощь! Я получаю эту ошибку: НЕ ПРОШЛО! = ›{Msg: В задаче есть опция с неопределенной переменной. Ошибка была: 'int object' не имеет атрибута 'status_code'. Я использую это вместо ваших vars: - name: GET HEALTH CHECK uri: url: http: // {{ansible_fqdn}}: 8888 / healthcheck method: GET return_content: yes status_code: 200 body_format: json validate_certs: no register: data - debug: msg: ›- IP: {{item}}, status_code: {{data.json [item] .status_code}} цикл: {{data.json. ключи ()}} '' ' - person confusedjoe; 26.02.2021
comment
Означает, что data.json[item] не является словарем, подобным тому, который вы указали в своем вопросе. Отладьте его, чтобы увидеть, что он дает, и отредактируйте его в своем вопросе: -debug: var=data.json - person β.εηοιτ.βε; 26.02.2021
comment
Я добавил свои отладочные данные в качестве ответа. - person confusedjoe; 26.02.2021
comment
Вам следовало бы отредактировать свой вопрос. - person β.εηοιτ.βε; 26.02.2021
comment
При этом я отредактировал ответ, чтобы охватить вашу проблему. - person β.εηοιτ.βε; 26.02.2021
comment
спасибо работает как шарм! Ты спасатель! - person confusedjoe; 26.02.2021
comment
@confusedjoe У меня также есть менее громоздкая идея, если вам когда-нибудь интересно. - person β.εηοιτ.βε; 26.02.2021
comment
да, мне интересно, не могли бы вы поделиться своей идеей? - person confusedjoe; 26.02.2021