Trying to create a script to turn off all lights but one

Trying to make a script that will turn off every light except my night stand (once it works I will also have it set my night stand to a dim warm light), but right now it is turning off every light, could someone let me know what I did wrong? Thank you!

alias: Good Night
sequence:
  - service: light.turn_off
    target:
      entity_id: "{{ lights }}"
variables:
  lights: |
    {{ expand(states.light)
      | rejectattr('entity_id', 'in',  ['light.night_stand'])
      | selectattr('state', '==', 'on') | map(attribute='entity_id') | list }}
mode: single
icon: mdi:bed

Why not just create a Helper Group with the lights you want and turn that off via the group:

  - service: light.turn_off
    target:
      entity_id: light.all_family_room_lights

Did you test the Jinja template in the developer tools to see what it is returning?
I wonder if the variable is for some reason not being created before the sequence leading to an empty list?

I tested in my dev tools and it correctly removes the light I don’t want targeted.
So my suggestion would be to define the variable lights, IN the sequence list immediately before the call to turn the lights off.

If light.night_stand doesn’t have an attribute named entity_id but is a single light entity, it won’t work. This is what I’m using:


       {{- states.light
        |map(attribute='entity_id')
        |select('is_state', 'on')
        |reject('eq', 'light.hue_iris')
        |list -}}

Edit: Didn’t read thoroughly.

The posted template isn’t testing an entity attribute named entity_id.

It’s testing a State Object’s property named entity_id which always exists.

Turn on light.night_stand then copy-paste the following template into the Template Editor.

    {{ states.light
      | rejectattr('entity_id', 'in',  ['light.night_stand'])
      | selectattr('state', '==', 'on')
      | map(attribute='entity_id') | list }}

Does the list of entity_id’s reported by the template include light.night_stand?

1 Like

Ah, it is in a group from Hue for the whole bedroom and that is getting selected too.

If it helps, you can reject light group entities.

1 Like

Just found another post you made talking about that when I searched for it. :slight_smile: Thank you for being awesome!