As mentioned, Home Assistant doesn’t currently support the concept of global variables. However, what you want to achieve doesn’t require a global variable in Home Assistant.
For example, you can create a Template Sensor that dynamically reports the names of entities that are on
(i.e. open). Here’s one I use to report open doors. It also has an attribute called qty
that reports the quantity of open doors.
sensors:
- platform: template
sensors:
doors_open:
friendly_name: 'Open Doors'
value_template: >
{{ expand('group.doors_all')
| selectattr('state', 'eq', 'on')
| map(attribute='name')
| list | join(', ') }}
attribute_templates:
qty: >-
{{ expand('group.doors_all')
| selectattr('state', 'eq', 'on')
| list | count }}
It references group.doors_all
which contains other groups (group.doors_interior
, group.doors_exterior
).
The resulting sensor.doors_open
can be used in scripts and automations to report open doors. Here’s a simple automation that periodically reports any doors left open in the evening:
- alias: 'Scheduled Door Monitor'
id: scheduled_door_monitor
description: 'Report open doors in the evening'
variables:
qty: "{{ state_attr('sensor.doors_open', 'qty') }}"
trigger:
- platform: time
at:
- '20:55:00'
- '21:55:00'
- '22:55:00'
condition: "{{ qty > 0 }}"
action:
- service: rest_command.speak
data:
audio_clip: 1
content: >
{% set plural = 's' if qty > 1 else '' %}
{% set prep = 'are' if qty > 1 else 'is' %}
Attention, there {{prep}} {{qty}} door{{plural}} left open,
{{' and '.join(states('sensor.doors_open').rsplit(', ', 1))}} door{{plural}},
{{prep}} open.
content_type: 'text'
volume: 80
The template is designed to produce a grammatically correct phrase because it’s intended for TTS. There’s an added touch that includes the word “and” in the appropriate place when there are two or more entities (for more information, see this post: Apples, oranges, and bananas). The template will produce phrases like this :
Attention, there are 3 doors left open, Front, Rear, and Garage doors are open.
Attention, there is 1 door left open, Rear door is open.