Template to include entity (or not)

This seems so simple to me that I think I may be thinking about it wrong. I have a ‘Christmas Time’ input boolean that we turn on when we get all the Christmas decorations out. I have a ‘lights out’ automation that turns some specific lights off at night. If the boolean is on, I want an entity included in the automation. Otherwise, I want it left out.
The below code will work when the boolean is on BUT not when it’s off. I get that. My question is how do I do what I want in THIS automation?

- alias: Nighttime lights off
  trigger:
    platform: template
    value_template: "{{ states('sensor.time') == (state_attr('input_datetime.outside_lights_off_time', 'timestamp') | int | timestamp_custom('%H:%M', False)) }}"
  action:
    - data_template:
        entity_id:
          - group.front_yard
          - group.back_yard
          - >-
            {% if states('input_boolean.christmas_time') == 'on' %}
            switch.christmas_tree
            {% endif %}
      service: homeassistant.turn_off

Use regular service calls for the entities you always want included and use a condition in the action section that checks that the boolean is on and calls the service for the Christmas entity below that.

So…

action:
- service: homeassistant.turn_off
  entity_id:
  - entity 1
  - entity 2
- condition: state
  entity_id: input_boolean.christmas_time
  state: 'on'
- service: homeassistant.turn_off
  entity_id: switch.christmas_tree
1 Like

The above suggestion is a good solution for this particular case. But to answer your question more directly, and for an example of what you might do in a more complex scenario, you can use something like the following, because the entity_id parameter will also accept a single string of entity_id’s separated by commas:

    - data_template:
        entity_id: >
          group.front_yard, group.back_yard
          {% if is_state('input_boolean.christmas_time', 'on') %}
            ,switch.christmas_tree
          {% endif %}
      service: homeassistant.turn_off
1 Like

That’s creative, I like that.

1 Like

Oh! It didn’t even cross my mind to put all this inline as opposed to a list. Thanks!

I didn’t realize that the placement of the condition statement was important. I thought the condition was applied to the whole action.

Yeah, if the condition evaluates as False any services below the condition won’t be called.

Cool. I’m using your solution instead. @pnbruckner, I couldn’t end up getting yours to work. For some reason, it’s not picking up the entities in the data template. I get an error saying that homeassistant/turn_off cannot be called without an entity_id. Not sure exactly what’s going on there. Ideas?

I’m guessing you didn’t enter it correctly. I’d be happy to point out what you might have done wrong, if you’re interested and you post exactly what you wrote. But, if not, that’s fine, too.