Using templates in automation blueprints to modify whole actions

I have a blueprint for a motion activated light type of automation. Most of the config was taken from the example though I wanted to extend it. For one I wanted it to firstly fade to half brightness and then after a second delay fade to off. That has so far worked very well apart from that brightness_step_pct does not change percentage in relation to current brightness but rather maximum possible brightness. So I used templates, to make an action, that calculates half-brightness based off of the current brightness of the entity:

- service: light.turn_on
  target: {{entity_id}}
  data:
    brightness: '{{state_attr(entity_id, "brightness") / 2 | int}}'
    transition: 1

Though as it turns out, the target selector returns an array of areas, devices and entities. The light service can deal with that though not the templates. To make it myself a little easier I created macros that encapsulate an action for an entity so I can more easily iterate through them. However when I tried to run them Home Assistant always fails with the unhelpful message “Invalid blueprint: required key not provided @ data['blueprint']. Got None”. So I tried to simplify the case and boiled it down to:

action:
  - delay: 1
  {% if true == false %}
  - delay: 10
  {% endif %}

Which still fails to evaluate. Is it even possible to use templates in that way? I know the blueprint gets re-compiled as an automation with the inputs replaced with the values entered from UI. But when and at which place are templates evaluated? Is there a more sane version to setting all lights in a target selector (=entities,devices,areas) to a given percentage of their current brightness? And for further debugging: is there a way to see how Home Assistant compiled a blueprint even if it did not create a valid automation? No matter what issue is at fault I almost always get the error message above which does not help in the slightest.

(I did test the templates in the developer tools which did create a valid automation configurations after compiling)

As it turns out: no, you can not use Jinja to modify the template/blueprint.

Use the script syntax instead: Script Syntax - Home Assistant

I.e. to execute an action for a group of entities use:

action:
  - repeat:
    for_each: "{{ list_of_entities }}"
    sequence:
       [...]

In general, you can’t use Jinja2 templates to generate YAML (which is what the example in your first post attempts to do; it uses a Jinja2 template to determine whether a YAML delay statement is employed or not).

During Home Assistant’s startup/reloading process, it runs the YAML processor first, followed by the Jinja2 interpreter. Therefore you can’t use a Jinja2 template to generate YAML code because that’s not the order in which it will be processed.

1 Like