Loop in script with variables

Hi,

i try to pass an variable as array in a script and loop all items of the array as mqtt topic. But the mqtt command has Not the correct variable in the topic path. I hope someone can help me on this. Here is the automation and the called script.

AUTOMATION:

id: '1623079881540'
alias: Tablets bei Bewegung an
description: ''
trigger:
  - platform: state
    entity_id: binary_sensor.flursensor_occupancy
    from: 'off'
    to: 'on'
condition: []
action:
  - service: script.tablets_bei_bewegung_an
    data:
      rooms:
        - wohnzimmer
        - ankleide
        - schlafzimmer
        - bad
        - kueche
mode: single

SCRIPT:

sequence:
  - service: mqtt.publish
    data:
      topic: >-
        {% for room in "{{ rooms }}" %} 
        "wallpanel/{{ room }}/command"
       {% endfor %}
      payload: '{"wake": true, "wakeTime": 3600}'
mode: single
alias: Tablets bei Bewegung an

You can’t nest one template inside of another one.

Try this version:

EDIT

Suggestion withdrawn.

I changed the loop as you suggested but now it seems the script does not enter the loop. There is no mqtt message in my mqtt output

I removed my initial suggestion because the whole approach you’re using won’t work. You can’t loop through several topics that way and expect one service call to publish to multiple topics.

You need to use repeat to execute the service call multiple times (once for each topic). I recently provided a similar example here:

Let me know if you need help to adapt the example for your application.

2 Likes

This works perfect. Thank you. Here is my working automation

alias: Tablets bei Bewegung an
description: ''
trigger:
  - platform: state
    entity_id: binary_sensor.flursensor_occupancy
    from: 'off'
    to: 'on'
condition: []
action:
  - variables:
      rooms:
        - wohnzimmer
        - schlafzimmer
        - bad
        - kueche
  - repeat:
      count: '{{ rooms | count }}'
      sequence:
        - variables:
            room: '{{ rooms[repeat.index - 1] }}'
        - service: mqtt.publish
          data:
            payload: '{"wake": true, "wakeTime": 3600}'
            topic: |
              wallpanel/{{ room }}/command
mode: single
5 Likes