0

I have a dictionary of dictionaries collecting data from openshift using prometheus. Now I intend to add values in all the dictionaries. But some projects don't have quota and hence some pods don't have request/limit set for cpu and memory. I am trying the following and it fails in case the key:value is not there.

If possible I want to use if else such that, if the variable exists then add the variable else use the value as 0.

- name: Total section for Projects
  set_fact:
    pod_count_total: "{{ (pod_count_total|int) + (item.value.pod_count|int)}}"
    total_cpu_request: "{{ (total_cpu_request|float |round(2,'ceil')) + (item.value.cpu_request|float |round(2,'ceil'))}}"
    total_cpu_limit: "{{ (total_cpu_limit|float |round(2,'ceil')) + (item.value.cpu_limit|float |round(2,'ceil'))}}"
    total_memory_request: "{{ (total_memory_request|float |round(2,'ceil')) + (item.value.memory_request|float |round(2,'ceil'))}}"
    total_memory_limit: "{{ (total_memory_limit|float |round(2,'ceil')) + (item.value.memory_limit|float |round(2,'ceil'))}}"
  with_dict: "{{all_project}}"

Dictionary of dictionaries is like

ok: [127.0.0.1] => {
    "msg": {
        "openshift-web-console": {
            "cpu_usage": 0.015,
            "memory_used": 0.04,
            "cpu_request": 0.301,
            "memory_request": 0.293,
            "pod_count": 3
        },
        "srv-test": {
            "cpu_usage": 0.013,
            "memory_used": 0.02,
            "pod_count": 5
        },
        "test": {
            "cpu_usage": 0.001,
            "memory_used": 0.0,
            "pod_count": 1
        },
        "openshift-monitoring": {
            "cpu_limit": 1.026,
            "cpu_request": 0.556,
            "cpu_usage": 0.786,
            "memory_limit": 1.866,
            "memory_request": 1.641,
            "memory_used": 0.14,
            "pod_count": 98
        }
    }
}
Ayush
  • 1,510
  • 11
  • 27
srv_ER
  • 123
  • 1
  • 11

1 Answers1

1

If possible I want to use if else such that, if the variable exists then add the variable else use the value as 0.

The thing you are looking for is the default filter

    total_memory_request: "{{ (
        total_memory_request | default(0) 
        | float | round(2,'ceil')
        ) + (
        item.value.memory_request | default(0) 
        | float | round(2,'ceil')
        ) }}"

There's a subtlety in that if the variable exists but is the empty string, you'll need to pass in the 2nd parameter to default to have it act in a python "truthiness" way: {{ "" | default(0, true) | float }} -- that might not apply to you, but if it does, you'll be glad to know what that 2nd param does

mdaniel
  • 31,240
  • 5
  • 55
  • 58