Odd condition handling

I just discovered something quite strange. I have an automation that turns off my outdoor lights after being on for 15 minutes with a condition the sun is above the horizon. So basically if someone flips on an outdoor light during the daytime it gets turned back off after 15 mins.

But what I have discovered is if I turn these lights on <15 minutes from the sun going below_horizon it turns them off in 15 minutes. In other words the condition seems to be interpreted only at the start of the “for:” in the trigger and not at the end.

The non-functional automation is straightforward as shown below:

- alias: Daytime Outdoor Lights On
  initial_state: True
  hide_entity: False

  trigger:
    - platform: state
      entity_id:
        - group.outdoor_night_lights
        - group.outdoor_lights
        - group.outdoor_dusk_lights
        - group.outdoor_holiday_lights
      to: 'on'
      for:
        minutes: 15

  condition:
    - condition: template
      value_template: "{{ is_state('sun.sun','above_horizon') }}"
          
  action:
    - service: homeassistant.turn_off
      data_template:
        entity_id: "{{ trigger.entity_id }}"

What is interesting is moving the template condition inside the action section fixes it:

- alias: Daytime Outdoor Lights On
  initial_state: True
  hide_entity: False

  trigger:
    - platform: state
      entity_id:
        - group.outdoor_night_lights
        - group.outdoor_lights
        - group.outdoor_dusk_lights
        - group.outdoor_holiday_lights
      to: 'on'
      for:
        minutes: 15
          
  action:
    - condition: template
      value_template: "{{ is_state('sun.sun','above_horizon') }}"

    - service: homeassistant.turn_off
      data_template:
        entity_id: "{{ trigger.entity_id }}"

Is this correct as I would assume the condition section would be evaluated once the trigger was asserted and decide if the automation runs or not. But it does not appear that way…

That is strange…

I would have assumed that the trigger would have been evaluated first and only then evaluate the condition. But it sounds like from your description it’s the other way around.

Which makes sense that putting the condition in the action fixes it because then it forces the condition to be evaluated only after the trigger gets evaluated and the action is called.

Please see explanation here:

https://community.home-assistant.io/t/door-sensor-notification-help/115468/19