Turn on or off all switches that starts/ends with string

How do I achieve this? I’m currently stuck with this but I think it’s a syntax problem, because the template returns the correct entities. What I’m doing wrong?

action: switch.turn_on
metadata: {}
data: {}
target:
  entity_id: >-
    {% for entity in states.switch %} {% if entity.entity_id.endswith('_detect')
    or entity.entity_id.endswith('_recordings') or
    entity.entity_id.endswith('_motion') or
    entity.entity_id.endswith('_snapshots') %} {{ entity.entity_id }}, {% endif
    %} {% endfor %}

I’m guess here, but I think your template needs to return a list rather than a string. To do this you need to use “namespace” to build up a variable. Here’s unrelated code where I do the same sort of thing:

          {% set n = namespace(dict=[]) %}
          {% set not_on = expand('switch.always_on_switches') | rejectattr("state", "eq", 'on') %}
          {% for e in not_on %}
            {% set n.dict = n.dict + [e.entity_id] %}
          {% endfor %}
          {{ n.dict }}

Alternatively it might be easier to just create a group with all the entities you’re interested in.

maybe you could use search and regexp. $ marks the end of a string so something like this perhaps:

{{ states.switch | selectattr('entity_id', 'search', '(_recordings$|_motion$)') | list }}

this would generate a list of all switches that end with _recordings or _motion. you can use ‘.recording’ if you want to find entities that start with the ‘recording’. the | lets you “or” them together.

1 Like

this is working!

target:
  entity_id: "{{ states.switch | selectattr('entity_id', 'search', '(_detect$|_recordings$|_motion$|_snapshots$)') | map(attribute='entity_id') | list }}"

thank you all for the help, really appreciated

1 Like

great. glad it’s working for you!