Create variable names dynamically

Hey there. I want to save the volume states of my Alexa devices before I start the script. The devices always differ and that is why I want to use the list of targets to iterate over and use the target name as a variable name to automatically save the volume value of the device and not manually change it for every automation and every device.

What I tried:

repeat:
  sequence:
    - variables:
        {{target}}: >-
          {{ state_attr('{{target}}', 'volume_level') | default(0.5, true) |
          float }}
  for_each: "{{target}}"

The automation that delivers the values looks like this for example:

service: script.nachricht_uber_alexa
data:
  message: >-
    KĂĽhlschrank und oder SpĂĽlmaschine haben keinen Strom. Bitte prĂĽfe das
    sofort.
  target:
    - media_player.saschas_echo_dot_kuche
    - media_player.saschas_echo_dot_wohnzimmer
    - media_player.saschas_fire

Anyway, the above code will end up in the following and not work:

repeat:
  sequence:
    - variables:
        "[object Object]": >-
          {{ state_attr('{{target}}', 'volume_level') | default(0.5, true) |
          float }}
  for_each: "{{target}}"

How is it possible to save the volume values for all devices in the target list (variable)?

You cannot template YAML keys like those variable ids. Templates are only allowed to provide the values in a key: value pair.

In theory you can use scenes. However with the recent changes to the Alexa API, you may find it unreliable if you are using the Alexa Media Player integration since sensor and attribute value updates are no longer being pushed like they used to be.

Yeah, I see… they actually removed the volume_level. Thats horrible for my automations.

I also cannot do it like this, right?

I don’t know why I cannot use the value of target as for each value…

Where are you defining target as a variable?

They are given as variable from the call of the script. Would it work if I define it again as variable?

Ok, I see… you need quotes around your template

repeat:
  for_each: "{{target}}"
...

And get rid of the media_player. in the entity_id value, you already have that in the values in the target list.

1 Like

Goddamn… sometimes it’s so easy.