Can't filter entities by labels using light.turn_off

Hello all,
I’ve been using HA for a while now but just started getting more into YAML and JINJA to design more advanced automations.

My goal is to have a script that will turn off all lights in my house that can be called with different triggers, IE everyone leaves the house or we go to bed at night, etc.

I have a few labels categories for lights that I don’t want to be targeted for this script so I am trying to filter them out. For instance, I don’t want my security camera floodlights to turn off nor do I want my lights around the house that are on timers to turn off so I am filtering by the rejectattr label entities. See below:

action: light.turn_off
metadata: {}
data: {}
target:
  entity_id: |-
    {{ states.light
      | rejectattr("entity_id", "in", label_entities("Don't Turn Off"))
      | rejectattr("entity_id", "in", label_entities("Security and Utility"))
      | rejectattr("entity_id", "in", label_entities("Dummylight"))
      | map(attribute="entity_id")
      | join(", ")
    }}

For whatever reason, when I reference this script, I get the following error message: “not a valid value for dictionary value @ data[0][‘target’][‘entity_id’]”

. I don’t know what I am doing wrong. Thanks in advance for the help.

Brian

Your join is missing a closing parenthesis.

Whoops, missed that. Thanks for catching. I placed the parenthesis back in there but it still isn’t properly filtering. It is turning off every single light in HA

Does the template return the expected values in the Template editor tool?

Yes it does! I don’t understand why it won’t translate to the light.turn_off action.

  1. Are any of the entities unavailable?
  2. Have you tried using…
action: light.turn_off
target:
  entity_id: >
    {{ states.light
      | rejectattr("entity_id", "in", label_entities("Don't Turn Off"))
      | rejectattr("entity_id", "in", label_entities("Security and Utility"))
      | rejectattr("entity_id", "in", label_entities("Dummylight"))
      | map(attribute="entity_id")
      | select('has_value')
      | list
    }}

Thanks for your help, I finally got it!
I had to replace ‘join’ with ‘list’ as your code suggested.

I added the ‘expand(states.light)’ and this allowed me to specifically target the lights that aren’t filtered by rejectattr. If I did not include ‘expand(states.light)’ it would automatically target all nights… I am not sure why.

Final working code:

action: light.turn_off
metadata: {}
data: {}
target:
  entity_id: >-
    {{ expand(states.light)
      | rejectattr("entity_id", "in", label_entities("Don't Turn Off"))
      | rejectattr("entity_id", "in", label_entities("Security and Utility"))
      | rejectattr("entity_id", "in", label_entities("Dummylight"))
      | map(attribute="entity_id")
      | list
    }}
1 Like