I would like to build a dynamic list of entities for my automation.
Searched all over but I didn’t find a clear way to proceed. So I have some questions:
Should I use a value_template in trigger ?
If so, value_template should return a list of entity_ids or a true/false condition ?
Tested without success the following couple of approches:
trigger:
platform: template
value_template: "{% set list = namespace(id=[]) %}
{% for s in states.sensor %}
{% if s.object_id.startswith('shelly') and s.object_id.endswith('_uptime_attr') %}
{% set list.id = list.id + [ s.entity_id ] %}
{% endif %}
{% endfor %}
{{ list.id }}"
and
{% for state in states %}
{% if state.entity_id | regex_match('.*\.shelly.*_uptime_attr') %}
{{ state. }},
{% endif %}
{% endfor %}
You can’t use a template in the entity_id parameter of a state or numeric_state trigger. So the question, again, is, when do you want the automation or automations to trigger, or maybe more appropriately, run their actions?
Basically you’ll probably need to use an event trigger, and then use the dynamic entity ID template in a condition, and then probably some other condition as well. (You’re effectively doing the low level work of a state or numeric_state trigger.) Something like:
- trigger:
- platform: event
event_type: state_changed
condition:
- condition: template
value_template: >
YOUR list.id STUFF GOES HERE
{{ trigger.event.data.entity_id in list.id }}
- ANOTHER CONDITION GOES HERE TO CHECK trigger.event.data.new_state.state, ETC.
action:
...
Unless I’m mistaken, I believe what you are trying to achieve is a dynamic list of entities that contains all entities whose names start with shelly.
Although it’s possible to create such a dynamic list with a template (your example shows one way to do it), like pnbruckner stated, this “list of entities” template cannot be used for a State Trigger (or Numeric State Trigger).
When Home Assistant starts, it checks an automation’s trigger and, in the case of a State Trigger, identifies the entities whose states it should monitor.
It won’t review this list of entities again until the next time it restarts (or the next time automations are reloaded).
To allow for dynamic entity lists, it would have to review the list more often than just startup or reload (and it currently doesn’t do that).