Automation trigger slows down the entire system

I have several temperature sensors all around and I want an automation to send a notification in case any of these sensors report unusually high temperature. Some of my temperature sensors report the temperature in their state while others in attribute. I came up with a loop to go through all the sensors and check if any of them has ‘temperature’ in name or attribute. If any of them exceeds the threshold the automation is triggered and a notification to be sent.

To check the sensors I iterate through all the sensors with a for loop:

- alias: Unusually High Temperature Warning
  trigger:
    platform: template
    value_template: >-
          {%- set threshold = 40 -%}
          {%- for item in states.sensor %}
            {% if (item.attributes.temperature is defined and item.attributes['temperature']|int > threshold) or ("temperature" in item.entity_id|lower and ((item.state|int > threshold and item.state|int != 0))) or ("temperature" in item.name|lower and ((item.state|int > threshold and item.state|int != 0))) -%}
              {{ true }}
            {% endif %}
          {%- endfor -%}
  action:
  - service: notify.ios_xxx
    data:
        title: "Smart Home"
        message: "A sensor reports high temperature."

After saving and reloading automations CPU usage goes constantly above 30% and the entire Home Assistant system slows down and reacts with like 10-20 seconds delay. It seems the loop is killing the system. As soon as I remove the code and reload automations everything goes back to normal.

My question is why this is not working if a template trigger should only check for trigger condition if a sensor is changing it’s state?

I have another similar automation based on a suggestion from this forum, checking for dead nodes in z-wave network and this one works perfectly without any problem:

- alias: Z wave dead node detection and notification
  trigger:
    platform: template
    value_template: >
      {%- for state in states.zwave -%}
        {%- if state.state == "dead" or (state.attributes.is_failed is defined and state.attributes['is_failed'] == true) -%}
          {{ true }}
        {%- endif -%}
      {%- endfor -%}
  action:
    - service: notify.ios_xxx
      data_template:
        title: Smart Home
        message: "Dead nodes found"
        data:
          subtitle: "Z-wave Malfunction"

I created my temperature check automation based on this, but it doesn’t work properly as I mentioned before. Thanks for help!

You told it to loop over states.sensor. So if ANY sensor on your entire system changes, this automation is going to fire. It doesn’t know to only look at temperature sensors by this point.

Conversly, you might not have a ton of zwave sensors, and they probably aren’t changing that often.

Makes sense thank you. In this case I have to specify the entity_ids one by one.