Can "entitity_id" be a template?

Can “entity_id” be a template?

I want to have an automation for an ikea five button remote that changes the dimmness of the lamp(s) that are on. It could be one or both lamps that are on. And if one lamp is on I dont’ want to turn the other on with the light.turn_on service.

I’d also like to avoid doing a bunch of conditionals because that is difficult to maintain.

Here is the code I think should work.

- service: light.turn_on
  target:
    entity_id: >
      {{ states.light|selectattr("entity_id", "search", "living_room_lamp")|selectattr("state",
      "search", "on")|rejectattr("entity_id", "search", "corner")|map(attribute="entity_id")|list}}
    data:
      brightness_step_pct: -40
      transition: 0.5

So I know that you can do this in lovelace with auto-entities, but I havent seen anything for this in automations… It would be nice to see what you turn up with in the end!

On first sight this should work.

What about it needs redesigned? Any suggestion?

In my setup I have 3 lamps in the living room:

  • light.living_room_lamp_left
  • light.living_room_lamp_right
  • light.living_room_lamp_corner

We only use the ‘corner’ lamp for extra brightness and is usually off. So we want the remote to control the left and right lamp only.

  1. I expect the template to return the which lamp (left and/or right) is currently on. (I edited my original post to correct off to on)
  2. I expect the rejectattr to reject the corner lamp out of the group that starts with light.living_room_lamp

In your first question, you said that the call will fail if the result is an empty list. In all the cases for the remote, this will be used for, if the list is empty then nothing should happen.
For example: if user presses the brightness down button when no lights are on, then the list would be empty. This is an okay scenario.