Perform actions on a set of entities serially - Loops in blueprints?

The generalized version of what I’m trying to do is: Take a set of entities (an array input in a blueprint) and then do a set of actions for each of them. In my case, I need this done in a serial fashion.

More specifically, I’m creating a “winterize” routine for my sprinkler system. I have a rachio smart sprinkler system and each zone shows up as a switch in Home Assistant. In the fall, I’ll be hooking up an air compressor to the water line. I need each zone to get turned on for about 60 seconds, then a delay for a couple minutes so the compressor can catch up. Right now, I just copy/pasted the actions for all the relevant zones. But a blueprint would just be more fun. :slight_smile:

My attempts to do this in a blueprint with some templating have failed. Here’s some non functional code to better illustrate my goal.

blueprint:
  name: Loop Test
  description: Tests looping through entities.
  domain: automation
  source_url: "..."
  input:
    entities:
      name: Entities To Process
      description: The collection of entities to loop through.
      default: []
      selector:
        entity:
          filter:
            domain: switch
          multiple: true

variables:
  entities: !input entities

mode: restart

trigger:
  ...


action:
  {% for entityToProcess in entities %}
  - service: switch.turn_on
    data: {}
    target:
      entity_id: {{ entityToProcess }}

  - delay:
      hours: 0
      minutes: 0
      seconds: 30
      milliseconds: 0

  - service: switch.turn_off
    data: {}
    target:
      entity_id: {{ entityToProcess }}

  - delay:
      hours: 0
      minutes: 5
      seconds: 0
      milliseconds: 0

  {% endfor %}

Eventually, the delay amounts would become inputs too so that I can tweak the process.

I recommend using the documents to find this information out. All action types are shown in them. This example is even provided (missing the template for for_each).

- repeat:
    for_each: "{{ entities }}"
    sequence:
    - service: switch.turn_on
      target:
        entity_id: "{{ repeat.item }}"
    - delay: "00:00:30"
    - service: switch.turn_off
      target:
        entity_id: "{{ repeat.item }}"
    - delay: "00:05:00"

Thanks for the solution. I do poke around the docs or google search for the answer but my search-foo was off today. Thanks again.

FYI, when you want to learn about automation actions, click in the actions in the sidebar which will Lea you to script syntax. Which contains every option you can do in a action.

1 Like