I am trying to pass a list of device ids to a script and have the script use the list in a service call. It seems that I have recreated the list perfectly but it does not work.
test_automation:
- service: script.test_script
data:
monoprice_zones:
- A12345
- B12345
mode: single
test_script:
variables:
target_zones: “[{{ monoprice_zones | join(', ‘)}}]”
sequence:
- service: some service
target:
device_id: "{{ target_zones }}"
When the list:
A12345
B12345
is passed to the script it is arrives like this:
[‘A12345’,’B12345’]
Recreating the original list would be very problematic but another way to do a list (which works) would be like this:
[A12345, B12345]
The target_zones line in the script above recreates the later format. IOW I am able to turn this: [‘A12345’,’B12345’] into this: [A12345, B12345].
The problem is this does not work. If I dump it into the system_log I see the expedted format: [A12345, B12345].
If I hardcode it this like:
- service: some service
target:
device_id: [A12345, B12345]
It works fine! But this:
- service: some service
target:
device_id: "{{ target_zones }}"
generates the following:
Referenced devices [A12345, B12345] are missing or not currently available
Any help would be greatly appreciated. I am about to tear my hair out!
I am responding to my own post in the hope the helps someone else. I figured out a way to use the list of device ids that was passed into a script. Basically, I used a template to take the passed device ids into a new list of entity ids which I can then pass to various services. The template looks like this:
target_zones: "{%- set ns = namespace(entities_list=[]) -%}\
\ {%- for zone in monoprice_zones -%}\n\
\ {%- set ns.entities_list = ns.entities_list + device_entities(zone) -%}\
\ {%- endfor -%}\
\ {{ ns.entities_list }}\n"
Then to use the list I cast it as a sting as follows:
I’m surprised to hear that works because each one of the two items in that list would be interpreted as being the name of a variable, not a device’s identifier. Wrapping each item in quotes makes each item a string value.
The device_id option does support lists. For example, I selected two devices using the Automation Editor in visual mode and here’s the YAML it generated.