Repeat For Each loop

I hate having to admit defeat, but after hours of trying to figure it out, I am defeated.

I want an Automation to run the same script several times, each with a different parameter being passed. I could simply create multiple hard coded actions, but where’s the fun in that. :slightly_smiling_face:

Also, I want a simple way to add or delete items from the list it processes.

First of all, a simple test to just run the script once (of course trigger can be ignored):-

alias: Populate EVehiclists
description: testing Set up lists of EVehicles
triggers:
  - trigger: homeassistant
    event: start
actions:
  - action: script.evehiclist_populate
    data:
      EVSE: cp

That works perfectly and runs the script once with the shown parameter (EVSE) value and the correct input_select is populated by the called script, as required.

Then, the docs show the following example:-

repeat:
  for_each:
    - language: English
      message: Hello World
    - language: Dutch
      message: Hallo Wereld
  sequence:
    - action: notify.phone
      data:
        title: "Message in {{ repeat.item.language }}"
        message: "{{ repeat.item.message }}!"

In my case, each loop just needs a single parameter and there’s 3 of them. So I tried this:-

alias: Populate EVehiclists
description: Set up lists of EVehicles
triggers:
  - trigger: homeassistant
    event: start
actions:
  - repeat:
      for each:
        - gl
        - gr
        - cp
      sequence:
        - action: script.evehiclist_populate
          data:
            EVSE: "{{ repeat.item }}"

which looks to me like it should work, running the script 3 times, passing one of the stated values, one for each iteration. But…

It does not work. I cannot even save the script. Any attempt to do so produces the following error:-

Message malformed: extra keys not allowed @ data['actions'][0]['repeat']['for each']

I cannot fathom what the error means, apart from “something’s wrong”. I’ve tried every which way I can think of to create a simple ‘for each’ loop over the 3 items, but HA just doesn’t want to know, despite it seeming to me to be indistinguishable in principle from the docs’ example in the description of the ‘for each’ loop and on which basis I am assuming it is indeed possible.

However, would be most grateful if someone could please explain how. :confused:

You are missing an underscore character in for each. It should be for_each.

1 Like

Damn you. :grin:

I’ve been staring at that for literally hours and changing everything I could think of, but just did not see that missing underscore. I hate it when I do that. :rage:

Thanks for pointing out ‘the bleeding obvious’. I obviously needed that and will now continue in my quest.

Thank you again.

1 Like

Just to add, it now runs perfectly as it should. So I was right in how I was setting it up, but the eyes let me down. :frowning_face: