Automations and if/then actions

New user here, slowly figuring this thing out. I have set up a Google calendar that turns holiday lights on and off. I’ve got the automation working, but it required two automations: one to turn on, one to turn off. Which is clunky. Is there any way to do this as one automation?

Here’s what I got, which works:

- alias: "Outdoor Holiday 1 On"
  trigger:
    platform: state
    entity_id: calendar.outdoor_holiday_1
    to: "on"
  action:
    service: switch.turn_on
    entity_id: switch.inovelli_unknown_type6000_id6000_switch
   
- alias: "Outdoor Holiday 1 Off"
  trigger:
    platform: state
    entity_id: calendar.outdoor_holiday_1
    to: "off"
  action:
    service: switch.turn_off
    entity_id: switch.inovelli_unknown_type6000_id6000_switch

I’d like to do something like this:

- alias: "Outdoor Holiday 1"
  trigger:
    platform: state
    entity_id: calendar.outdoor_holiday_1
    
  action:
    {% if is_state('calendar.outdoor_holiday_1', 'on') %}
      service: switch.turn_on
      entity_id: switch.inovelli_unknown_type6000_id6000_switch
    {% else %}
      service: switch.turn_off
      entity_id: switch.inovelli_unknown_type6000_id6000_switch
    {% endif %}

However, even just entering this code throws an error in Configurator:

missed comma between flow collection entries at line 25, column 6:
        {% if is_state('calendar.outdoor_ ... 
         ^

Is this possible? If so, what am I doing wrong?

As a follow up question, I’m planning on several more of these. Is there a way to not rewrite code? I’d like some sort of script to which I feed two pieces of info - the calendar entity_id and the switch/light entity_id, and have it perform this. Any way to do that? I can live with one script for switches and one for lights, but it’d be way more elegant to have it be able to determine the correct service to use.

Thanks!

- alias: "Outdoor Holiday 1"
  trigger:
    platform: state
    entity_id: calendar.outdoor_holiday_1
  action:
    service_template: >
      {% if is_state('calendar.outdoor_holiday_1', 'on') %} switch.turn_on
      {% else %} switch.turn_off {% endif %}
    entity_id: switch.inovelli_unknown_type6000_id6000_switch
1 Like

Aha! Thanks!

1 Like