如何在Ansible中获取嵌套变量的值

时间:2020-08-20 09:19:23

标签: json ansible yaml

我正在尝试从下面的文件中逐个获取警报的值,以执行某些操作。有办法做到这一点吗?

        apiVersion: monitoring.coreos.com/v1
        kind: PrometheusRule
        metadata:
          labels:
            prometheus: k8s
            role: alert-rules
            app: prometheus-operator
            release: prometheus-operator
          annotations:
            exclude.release.openshift.io/internal-openshift-hosted: "true"
          creationTimestamp: "2020-04-22T09:22:14Z"
          generation: 1
          name: free-memory-percentage
          namespace: openshift-monitoring
          selfLink: /apis/monitoring.coreos.com/v1/namespaces/openshift-cloud-credential-operator/prometheusrules/cloud-credential-operator-alerts
        spec:
          groups:
          - name: free-memory
            rules:
            - alert: node_mem_free_Percentage
              annotations:
                description: Node memory is under pressure
              expr: 100 - (100 * node_memory_MemFree_bytes / node_memory_MemTotal_bytes) < 50
              for: 2m
          - name: High-CPU-Usage
            rules:
            - alert: HighCPUUsage4test
              annotations:
                description: CPU usage is above the 0% threshold
              expr: (100 - (avg by (instance) (irate(node_cpu_seconds_total{mode="idle"}[5m])) * 100)) > 0
              for: 2m

1 个答案:

答案 0 :(得分:1)

Q:“从文件中一个接一个地获取警报的值。”

A:使用json_query。给定file.yml和变量,下面的任务

    - include_vars:
        file: file.yml
        name: my_data
    - set_fact:
        my_alerts: "{{ my_data.spec.groups|json_query('[].rules[].alert') }}"
    - debug:
        var: my_alerts

给予

  my_alerts:
  - node_mem_free_Percentage
  - HighCPUUsage4test