Loop through array of entity ID strings for sequential light not working

Hello everyone,

I’m trying to loop through an array of strings of entities to turn the previous light off and the next on to get a running light effect.

My script looks as follows:

running_light:
  alias: Running light
  variables:
    lights: |-
      {{ ['light.du_1', 'light.du_2', 'light.du_3', 'light.du_4', 'light.du_5', 'light.du_6', 'light.du_7', 'light.du_8',
          'light.du_9', 'light.du_10', 'light.du_11', 'light.du_12', 'light.du_13', 'light.du_14', 'light.du_15', 'light.du_16'] }}
  sequence:
    - repeat:
        while:
          - condition: state
            entity_id: input_select.dachunterstand_effect
            state: Running_Light
        sequence:
          - service: light.turn_off
            data_template:
              transition: 1
              entity_id: | 
                {{ lights[(now().second - 1) % 16] }}
          - service: light.turn_on
            data_template:
              transition: 1
              entity_id: | 
                {{ lights[now().second % 16] }}
          # - service: system_log.write
          #   data_template:
          #     message: "Off index {{(now().second - 1) % 16}} on index {{now().second % 16}}"
          #     level: warning
          - delay: 00:00:02

When the effect is set on Running_Light then it should toggle the previous and next light every second. The system_log shows that the right array index is being addressed, but the lights are not running.

Do you see any flaw in my code?

Best Regards

Did you try it without a loop first?
Is there a delay, especially longer than a second or two, between the service call and the light turning on?
Did you check the automation’s run trace to make sure there were no errors?