How to exit a repeat/until loop after a set time/loops?

I am using the following code to repeatedly set a switch to on (sometimes the device seems to miss it being turned on for some reason) but I also want it to only try for a given amount of time then exit, effectively failing.

I am not sure how I can count loops or give a duration for it to repeat and then stop if the main condition isn't met.

I found some code saying about using a template with a "repeat.index" but I am not sure if that is working as when I test it, HA shows an error (which could also be because it isn't actually running the loop yet?)

my code (the device and entity ID is the same device as the entity in the sequence):

repeat:
  until:
    - condition: device
      type: is_on
      device_id: 2e337b7bb5db48ded190fcf59747bb78
      entity_id: 4e435b5affb1c900493a88f4015f78d2
      domain: switch
  sequence:
    - action: switch.turn_on
      metadata: {}
      target:
        entity_id: switch.openeo_charger_charger_switch
      data: {}
    - delay:
        hours: 0
        minutes: 0
        seconds: 5
        milliseconds: 0

This is the way to do it. The variable repeat only has value when the loop is running, so you cannot test it the way you can other conditions.

repeat:
  until:
    - or:
        - alias: Check if the switch is already on
          condition: state
          state: 'on'
          entity_id: switch.openeo_charger_charger_switch
        - alias: Check if this sequence has already repeated 10 times
          condition: template
          value_template: "{{ repeat.index > 10 }}"
  sequence:
    - action: switch.turn_on
      metadata: {}
      target:
        entity_id: switch.openeo_charger_charger_switch
      data: {}
    - delay: 5

To do a time-based condition, you would need to store the current time in a variable prior to starting the repeat then use a template to compare times during each loop:

- variables:
    timestamp: "{{now()}}"
- repeat:
    until:
      - or:
          - alias: Check if the switch is already on
            condition: state
            state: 'on'
            entity_id: switch.openeo_charger_charger_switch
          - alias: Check if this repeat has been running for 2 minutes
            condition: template
            value_template: "{{ now() >= timestamp|as_datetime + timedelta(minutes=2) }}"
    sequence:
      - action: switch.turn_on
        metadata: {}
        target:
          entity_id: switch.openeo_charger_charger_switch
        data: {}
      - delay: 5

Awesome, thank you!