How to create many devices with the same propieties

Hello everybody!

I want to dynamically store the state of the lights of my living room in a way that keeps between reboots. The scenario is that I have six buttons in my remote, I long press one to store the current state of the lights, and then I short press to recover it.

After some thought I have reached the conclusion that the best way to do that is by creating one virtual device per state and light, using templates or the virtual device. However, that means manually creating 18 elements in my lights.yaml file… And if I add another light to the living room, yet another 6…

Is there a way of creating devices in an iterative way? I would like to find something like this:

%% for i in range(0,15) 
- platform: virtual
  name: 'central-%i' 
  initial_value: 'off'
  support_brightness: true
  support_color: false
%% end for

I tried looking for templates, but I couldn’t find anything that would fit the bill. (I suck at templating, though)

Also, I know that the solution that HA offers for this kind of problem is typically scenes, and you can create dynamic scenes using the ‘scene.create’ service. But I gather from the docs that they are not persistent across reboots.

There is no way to create devices this way. Your best option is to use yaml anchors for common fields.

- name: central-1
  <<: &common_virtual_platform
    platform: virtual
    initial_value: 'off'
    support_brightness: true
    support_color: false

- name: central-2
  <<: *common_virtual_platform

- name: central-3
  <<: *common_virtual_platform

Petro’s answer is the solution I would go with for cases like what you have presented.

There is another option… I usually only bother with this hack if I need to create a set of template sensors that follow a pattern. You can use the template editor tool to iteratively write the yaml configuration for you. For clarity and to echo what Petro said, you cannot just paste this in your configuration.

You can, however, paste the following in the template editor tool, then copy the output, and paste that into your configuration.

{% for i in range(1,16) %}
- platform: virtual
  name: 'central-{{i}}' 
  initial_value: 'off'
  support_brightness: true
  support_color: false
{% endfor %}

I actually tried doing exactly that :sweat_smile:, and as you say, worked in the editor, but not in the YAML files (and the ‘this will prevent you from booting’ alarm went off). Pity, it would have been perfect.

Well, that’s indeed the best solution I’ve seen. I didn’t know yaml anchors where a thing, so I even learned something new. Thank you!