How do I make a loop or switch statement in an automation?

Iterating an action like setting a light intensity to x times 10 where x is the index of the loop would be great.
Same for switch statements. For example, if I set trigger ids, I would like to be able to choose in a switch what the automation should do.

These already exist, right?

In the automation editor you can add “building blocks” which includes “repeat” and “choose”, these represent the for-loop and switch statements, respectively.

Indeed, I didn’t saw the choose action.
For the repeat, it is nice, but we don’t get the index of the iteration and can’t make any change like put blind or light to x * 10%.

Have a look here: Script Syntax - Home Assistant

You can reference repeat.index to get the number in the loop.

Interesting, I’ll keep that in the bookmarks.
I tried to do that in the automations, and it seems to only work in scripts.
That would be great to use in plain automations.

Ah, I didn’t know that.

Surely the building blocks between scripts and automations should be shared. They’re essentially the same thing minus the triggers.

It works in automations as well

1 Like

I retried a little more and after some failed attempts it indeed works within a template:

alias: Exemple loop
description: ""
triggers:
  - type: changed_states
    device_id: 3bf63e4227cb25e07dea42ce217d235a
    entity_id: d670b6c02a52c7605448123b7959785b
    domain: switch
    trigger: device
conditions: []
actions:
  - repeat:
      count: 10
      sequence:
        - action: light.turn_on
          metadata: {}
          data:
            brightness_step_pct: "{{ (repeat.index * 2) | float }}"
          target:
            entity_id: light.office
mode: single

Automations are just scripts with triggers. The syntax is exactly the same for automation actions and script sequences.

Closed as already implemented.