Automate light timing on and off

This seems so simple, yet even following many threads still stuck on automation to accomplish:
1, Turn on switch1 at 06:00:00
2. Turn off switch1 at 23:00:00
3. Activate on home assistant restart.

The following not working to accomplish this:

alias: Grow_light_Switch
description: ""
trigger:
  - platform: time
    at: "06:00:00"
    id: morning
  - platform: time
    at: "22:00:00"
    id: evening
  - platform: homeassistant
    event: start
condition: []
action:
  - if:
      - condition: time
        after: "06:00:00"
        weekday:
          - mon
          - tue
          - wed
          - thu
          - fri
          - sat
          - sun
        before: "23:00:00"
    then:
      - service: switch.turn_on
        data: {}
        target:
          entity_id: switch.0x70b3d52b60016c87_l1
      - if:
          - condition: time
            after: "23:00:00"
            before: "06:00:00"
            weekday:
              - sun
              - sat
              - fri
              - thu
              - wed
              - tue
              - mon
        then:
          - service: switch.turn_off
            data: {}
            target:
              entity_id: switch.0x70b3d52b60016c87_l1
mode: single

Thank you.

alias: Grow_light_Switch
description: ""
trigger:
  - platform: time
    at: "06:00:00"
    variables:
      cmd: 'on'
  - platform: time
    at: "22:00:00"
    variables:
      cmd: 'off'
  - platform: homeassistant
    event: start
    variables:
      cmd: "{{ 'on' if 6 <= now().hour < 22 else 'off' }}"
condition: []
action:
  - service: 'switch.turn_{{ cmd }}'
    target:
      entity_id: switch.0x70b3d52b60016c87_l1
mode: single

Thanks, however receiving error:

Stopped because an error was encountered at March 10, 2023 at 13:00:06 (runtime: 0.04 seconds)

Template rendered invalid service: switch.turn_

How did you test the automation?

Ran it from the automation page “run automation”

That’s not a suitable test procedure. All it does is execute the automation’s actions, it doesn’t exercise any of the automation’s three triggers.

The action in this automation references a variable named cmd that is only defined when one of the three triggers is triggered. Therefore cmd is undefined and the template produces an invalid service call.

Reference: Testing your automation

If you want to test this automation right now, restart Home Assistant (because that’s what the automation’s third trigger monitors) then check the automation’s trace.

Ahh got it! Just restarted it and worked fine.

Thanks

You’re welcome!

Please consider marking my post above with the Solution tag. It will automatically place a check-mark next to the topic’s title which signals to other users that this topic has been resolved. This helps users find answers to similar questions.

For more information about the Solution tag, refer to guideline 21 in the FAQ.