Dynamic sensor group based on area

I’m trying to figure out how to create a sensor group that automatically includes all sensors in a particular area, so that I can move sensors between rooms without having to rewrite my automations.

I’m trying to do something along these lines in my sensors.yaml, but am not sure I’ve got it right:

  - platform: group
    name: "Bedroom Temperature (Max)"
    type: max
    entities: >
      {{ area_entities('bedroom') | expand   
        | selectattr('attributes.device_class', 'defined')
        | selectattr('attributes.device_class', '==', 'temperature')
        | map(attribute='entity_id')
        | list }}

Any tips?

You cannot populate a sensor group with a template. As shown in the docs, the entities key only accepts strings.

You can use Template sensors that calculate the max.

template:
  - sensor:
      - name: "Bedroom Temperature (Max)"
        state: >
          {{  expand(area_entities('bedroom'))
          | selectattr('attributes.device_class', 'defined')
          | selectattr('attributes.device_class', '==', 'temperature')
          | map(attribute='state') | map('float', 0)
          | max }}

It is also possible to use an automation to populate a legacy style group. These ad hoc groups do not survive restart or reboot, so you need to set up the automation to fire on restart.

Thank you!

Edit: It works! I was getting errors from using expand as a filter and found some guidance here), so I have now updated the code as follows:

template:
  - sensor:
      - name: "Bedroom Temperature (Max)"
        state: >
          {{ expand([area_entities('bedroom')])   
          | selectattr('attributes.device_class', 'defined')
          | selectattr('attributes.device_class', '==', 'temperature')
          | map(attribute='state') | map('float', 0)
          | max }}