Need help with sunrise sunset automation

I’ve got an automation for to have a switch turn on the sunsets and turn off for sunrise. The only problem is it turns on for sunset but not off for sunrise. I’m sure I’m missing something easy but I can’t figure it out. Any help would be appreciated. Thanks

alias: Light Sunset/Sunrise
description: Turn light on at sunset and off at sunrise
trigger:
  - platform: sun
    at: sunset
action:
  - service: "switch.turn_{{ 'on' if trigger.platform == ‘sun’ else 'off' }}"
    entity_id: switch.frontporch
mode: single

Your automation only has one trigger and that is sunset so the template will only ever be on, therefore no switch off.

Like most things there are multiple ways to do this but if it were me I would use

Trigger 1 - sunset
Trigger 2 - sunrise

Action:
Choose:
Trigger 1 - turn light on
Trigger 2 - turn light off

Thanks for the response. I understand what you’re saying but I’m struggling with the code. Do you know how I can modify my code to make that work?

Try this-

trigger:
  - platform: sun
    event: sunrise
    id: 'off'
  - platform: sun
    event: sunset
    id: 'on'
condition: []
action:
  - service: >-
      switch.turn_{{ trigger.id }}
    target:
      entity_id: switch.frontporch
2 Likes

Sorry for not responding in a while. Thanks to all who responded. I was able to rework the code and come up with a solution. Here’s what worked.

- id: sunrise_sunset
  alias: Lights Sunset/Sunrise
  trigger:
    - platform: state
      entity_id: sun.sun
  action:
    - service: >
        {% if is_state('sun.sun', 'below_horizon') %}
          switch.turn_on
        {% else %}
          switch.turn_off
        {% endif %}
      entity_id: switch.frontporch

If you wish, you can reduce the template by using an inline-if statement.

  action:
    - service: "switch.turn_{{ 'on' if is_state('sun.sun', 'below_horizon') else 'off' }}"
      entity_id: switch.frontporch