Is it possible to iterate over automations?

Hello everyone

I have many switches which are triggered through a specific MQTT message. I know how to build an automation of the kind “if the MQTT payload is X, then toggle switch Y”.

Since there are many switches, I end up with a lot of blocks which are identical, except for these two information.

Is there a way to define the pairs (payload, corresponding switch) and

  • have one block surrounded by a loop over these values – effectively building n automation blocks
  • or use a dictionary inside a block?

In pseudocode (Python and Jinja like), the first case would be something like

{% switches = [(A, B), (C, D), (E, F)] %}
{% for payload, switch in switches %}
  trigger:
  - platform: mqtt
    topic: rfbridge-1/rfin
  condition:
  - condition: template
    value_template: '{{ %payload% in trigger.payload }}'
  action:
  - data:
      entity_id: switch.%switch%
    service: switch.toggle
{% endfor %}

The second case is just one block, there is no need for iteration:

  {% switches = {A: B, C: D, E: F} %+
  trigger:
  - platform: mqtt
    topic: rfbridge-1/rfin
  action:
  - data:
      entity_id: switch.%switch[trigger.payload]%
    service: switch.toggle

In other words: do I have to list very similar blocks, or is there a way to use a variable to have them “virtually built” by HA?

Well, I don’t use mqtt, so not very familiar with its details, but based on what you wrote, how about something like this:

  trigger:
  - platform: mqtt
    topic: rfbridge-1/rfin
  action:
  - data_template:
      entity_id: >
        {% set p_to_s = {'A': 'B', 'C': 'D', 'E': 'F'} %}
        switch.{{ p_to_s[trigger.payload] }}
    service: switch.toggle
1 Like

This looks extremely promising, thank you. Would you know where the structure ({% set ...) is documented (or which keywords would fit to do a Google search)?

This is the kind of code I was looking for but I have some hard time to find it in HA’s documentation (also the fact that you used > to introduce the set - all this must be documented somewhere I guess).

Thanks again for the great pointer!

EDIT: looks like it could be Jinja2

Yes, this is Jinja templating, and the documentation starts here.

Regarding the use of >, that’s YAML, and you can find some info about it here.

1 Like