Hi, I am trying to figure out how to define a structure in one place, and then use it in multiple places.
For example, I have a working script that I use to assign z-wave door codes using the last 6 digits of a person’s phone number.
It just iterates through a data structure and calls another script to do the actual work.
(At the time I wrote it, the “name” was just a comment for me)
alias: Set all door codes
sequence:
- repeat:
for_each:
- phone: 123 123 1234
name: Foo
- phone: 234 234 2345
name: Bar
- phone: 345 345 3456
name: Baz
garage_side: false
sequence:
- service: script.set_slot_for_all_door_locks
data:
slot: "{{ repeat.index }}"
code: "{{ (repeat.item.phone | replace(' ', ''))[-6:]}}"
doors: "{{ repeat.item }}"
mode: single
icon: mdi:chevron-triple-right
Now, I am working on making an automation which will send me a notification when someone uses a door code to unlock a door.
I am able to catch the event to trigger the automation, and identify the slot number that unlocked the door, (e.g. slot 2 would correspond to Bar). But I would like the notification to contain the name of the person, not just the slot number. So I will need the data from the script in some form in the automation as well. I would prefer not to have two copies of the same data.
My first try was to use secrets.yaml with something like:
door_codes:
- phone: 123 123 1234
name: Foo
- phone: 234 234 2345
name: Bar
- phone: 345 345 3456
name: Baz
garage_side: false
And then in the script, use:
for_each: !secret door_codes
But it seems that secrets.yaml can only hold strings? I couldn’t make it work. The script didn’t like the !
, iirc.
Next try was to use custom_templates
with a doorcodes.jinja containing:
{%- macro door_codes() -%}
[{"phone":"123 123 1234","name":"Foo"}, {"phone":"234 234 2345","name":"Bar"}, {"phone":"345 345 345","name":"Baz","garage_side":false}]
{%- endmacro -%}
I can get the content of the macro to show up in the Developer Tools Template thingy using
{% from 'doorcodes.jinja' import door_codes -%} {{ door_codes() }}
So the template itself is being loaded and interpreted correctly.
And then in the script, I use this:
for_each: {% from 'doorcodes.jinja' import door_codes -%} {{ door_codes() }}
But it just gives me this error:
Message malformed: template value is None for dictionary value @ data['sequence'][0]['repeat']['for_each']
Is there a better way to go about this? Someplace I can store some structured data like this and then access it in scripts, automations, etc?