@frenck recently released the for_each command in 2022.5 and mentioned that complex templates could be use to return lists of entities. I wanted to provide an example here for others to use.
This example takes a pre-defined group of lights, expands the members, checks if they’re already on, and then adjusts their brightness according to a lux sensor.
Isn’t it the case that if you go with @123’s suggestion, if there are no lights that are on, an error with be thrown for trying a service call on an empty list? I do agree that if you know there will be at least one light on (for example with a condition check) it is more efficient. However, the for each route avoids needing the condition check and would also allow you to do things like check the brightness level for each light as well.
Try running the following service call in Developer Tools > Services. In my case (using version 2022.5.2), the template produces an empty list yet executing the service call doesn’t log any warning or error message. It simply does nothing without complaint.