Loop and service (how to ?)

hello to all
i have read many, many threads, but i still dont understand:
how to call service in a loop ?
pseudo code:

- alias:my_scrpit:
  trigger:
    anything
  action:
    array=[item1, item2, item3]
    for item in array
      call service
      data= item
  endfor

looks simple…
possible ?
not possible ?
other ways ?
Many thanks for all answers.

@123
:woozy_face: i have missed this one…
clever (i put 1 :heart: )

but what if adding some test|additions|… on item:
pseudo code (more difficult i think)

- alias:my_scrpit:
  trigger:
    anything
  action:
    array=[item1, item2, item3]
    for item in array
      if item > test_variable 
        call service
        data= item
      endif
  endfor

You can use if - then (within the repeat - for_each) to determine if the service call should be executed or not.

@123
i believe this is how to get dynamic values
obviously there is no need to test or something in static array

action:
  - repeat:
      for_each:
        - e: switchlinc_dimmer_3d_ac_8a
          b: states('input_number.test')
        - e: lamplinc_dimmer_35_54_23
          b: 50

      sequence:
        - service: light.turn_on
          target:
            entity_id: 'light.{{ repeat.item.e }}'
          data:
            brightness_pct: '{{ repeat.item.b }}'

right ?
but where to put if|then|else ?

The following example executes the service call only if the light is currently off.

action:
  - repeat:
      for_each:
        - e: switchlinc_dimmer_3d_ac_8a
          b: "{{ states('input_number.test') }}"
        - e: lamplinc_dimmer_35_54_23
          b: 50
      sequence:
        - variables:
            entity: 'light.{{ repeat.item.e }}'
        - if: "{{ is_state(entity, 'off') }}"
          then:
            - service: light.turn_on
              target:
                entity_id: '{{ entity }}'
              data:
                brightness_pct: '{{ repeat.item.b }}'
1 Like

@123
clean & smart ! :clap:
i think you have read this before, but you are a genius.
i will read & reread & try to integrate in my project
many thanks, you find the solution in minutes, i have search this for # 48 hours !!!

1 Like