How to use a loop inside actions in automation

I tried many different ways but didn’t found a way to do following
loop over sensors:
get sensor.id
mqtt publish
topic: this/is/the/topic/sensor.friendly_name
payload: sensor.payload

this looping seems not to be a valid list item in actions…
action mqtt.publish with single topic and payload works pretty nice

It makes it much easier for us to offer constructive answers if you follow Community Guidelines #9 & 11 by supplying a properly formatted configuration for the automation that you have attempted.

The Repeat for Each action will accept a template that returns a list of simple objects. If that is the method you are using, make sure your list is not returning full state objects as those contain complex objects, like datetime objects, that Repeat for Each cannot handle.

1 Like

Hi, yaeh may useful :wink:

But solved it by myself

alias: mqttall_wechselrichter_sensors
description: ""
triggers:
  - trigger: state
    entity_id:
      - sensor.wechselrichter_port_1_dc_strom
      - sensor.wechselrichter_ac_leistung
      - sensor.wechselrichter_port_1_dc_spannung
conditions: []
actions:
  - alias: Set variables
    variables:
      sensors: >-
        {{ states |map(attribute='entity_id')|list | select('match',
        'sensor\..*wechsel.*') | list }}
      sensor_count: sensors | count
  - alias: Repeat for all sensor in sensors
    repeat:
      for_each: "{{ sensors }}"
      sequence:
        - action: mqtt.publish
          data_template:
            topic: homedata/pv/inverter/micro/1/1/{{ repeat.item }}
            payload: "{{states(repeat.item)}} "

works for me. It sends all sensor.wechselrichter to mqtt if one of the trigger will be triggered

If you’re interested, this version of the template is slightly more efficient because it starts with just sensor entities as opposed to all entities.

  - alias: Set variables
    variables:
      sensors: >-
        {{ states.sensor
          | selectattr('object_id', 'match', 'wechsel')
          | map(attribute='entity_id') | list }}

It also performs a match on the entity’s object_id, not its entire entity_id, thereby allowing for a simpler regex pattern.

  • If you want to find all sensors whose object_id starts with wechsel then the match filter is suitable.

  • If you want to find all sensors whose object_id contains wechsel (in other words, not necessarily starting with it) then the search filter is suitable.

2 Likes