For loop in Blueprint to generate YAML code?

Is there a way to “escape” out of the YAML that a blueprint generates in order to dynamically generate the YAML?

I’d like to have a blueprint for an automation that triggers on 1-n devices. The current snippet looks like this:

trigger:
  - platform: event
    event_type: zha_event
    event_data:
      device_id: 4d8c469aea304ae74ac9e03570ad4bde

Since (as best I can tell) I can’t have mulitple device_ids in the event_data block, I need multiple platform blocks.

If I knew that I would have, e.g., 3 devices configured in the blueprint then I’d have three blocks with device_id: !input device_2, etc. But that isn’t very dynamic.

The only way that I’ve thought to solve for this is something like generating the whole platform block dynamically with a for/each block.

(If this were in the body of the automation then I could use a repeat block, but there is no repeat equivalent for the trigger.)

I think that would look something like this:

trigger:
{% for device_id in device_ids %}
  - platform: event
    event_type: zha_event
    event_data:
      device_id: {{ device_id }}
{% endfor %}

But, best I can tell you can’t use templating outside of YAML values.

Any solutions?

Another example would be for lists, like this:

action: light.turn_on
target:
  device_id:
    - fe59...
    - dce...

That can be solved with a repeat which repeats the entire action block, but it seems much better to be able to dynamically generate a list in the device_id block.

Can you trigger on all zha_events, and have a template condition that the event_data.device_id is in your list of device_ids?

Hi James,

While you cannot template many if any things with device_id’s, entity_id’s are a different story. Can you accomplish what you want with entity_id’s pulled in using multiple: true and do your stuff that way?

Why and how to avoid device_ids in automations and scripts.

If you still need the device_id, you can pull it out of the database using a template and the entity_id.
Templating - Home Assistant.

1 Like