How to identify sensor name in a template?

Apologies if I have this in the wrong place. Most of my experience so far has been trawling the wealth of information here via Google…

Short version - is there a way to reference “me” with-in a sensor value template without needing to write the sensor name?

I’m trying to put together some re-usable packages related to handling Linux RAID and trying to use anchors to reduce the sheer volume of copy/paste that can come up if you have several RAID devices.

So, at the moment it works as follows:

  • Machine with the RAID array regularly pushes a JSON version of /proc/mdstat via MQTT to a single queue on HA.
  • On HA there is one MQTT sensor that receives all of the information to the json_attributes_topic. This sensor has a certain amount of stuff defined and anchored to allow re-use across other topics.
  • For the purposes of usability in HA, each array is defined as a separate sensor, sharing the original json_attributes topic, but tweaked for that array.
sensor raidCommon: &raidCommon
  platform: mqtt
  state_topic: "/home/server/mdstat_json/sink"
  json_attributes_topic: "/home/server/mdstat_json"
  icon: "mdi:nas"

## MQTT sensors for each of the RAID devices - absorbs the originally received JSON in to the various sensors
sensor md100:
  <<: *raidCommon
  name: "MD100 RAID"
  value_template: >-
    {% set whoami = "sensor.md100_raid" %}
    {% set isActive = state_attr(whoami, "active") %}
    {% set isReadOnly = state_attr(whoami, "read_only") %}
    {% set isDegraded = (state_attr(whoami, "status").non_degraded_disks < state_attr(whoami, "status").raid_disks) %}
    {%- if not isActive -%}Inactive{%- else -%} {%- if not isReadOnly and not isDegraded -%}Active{%- else -%}Impaired{%- endif -%} {%- endif -%}
  json_attributes_template: "{{ value_json.devices.md100 | tojson }}"

You can see the copy/paste issue there if there are more raid devices and problems if the value template is updated or changed later…

Is there a way to reference “self” with-in the template? i.e. Could I get rid of the whoami and just have the remaining items refer to “me” or similar?

Or if someone has an alternative approach entirely that simplifies it please shout :).

Someone is working on it:

Thanks for that - interesting to read.

I note it refers to automations and scripts but not sensors. Is it likely to cover sensors or would that be a whole different can of worms?

I believe the PR’s author is best qualified to answer that.

(My guess is yes.)