There are no global variables in Home Assistant that allow you to store and update data as a list.
Define a local variable in the automation,script in home assistant
Define a global variable in the configuration.yaml in home assistant
Using a global variable in the data/json in home assistant
Where You Can Use Variables
| Feature/Section | Can Use Variables | Notes | | sensor | read | write |
|---|
| Automations | ✓ | 1.Great for triggers, conditions, and actions 2.When the automation ends, the variable disappears (not persisted). | | | | |
| Scripts | ✓ | Especially with variables: block | | | | |
| Templates | ✓ | Via Jinja2 templating engine | 1.use a Trigger-based Template Sensor detail1 2.config/custom_templates.detail | | | |
| UI (Lovelace) | ✘ | Variables don’t persist in UI unless part of a custom card | | | | |
| Scenes | ✘ | Static by design | | | | |
| input_text | | input_text can handle max 255 characters | | | | |
| Using a Static JSON File in Home Assistant | | | detail | | | |
source:https://blog.usro.net/2025/05/mastering-home-assistant-variables-for-smarter-automations/
Note
1.Variables are local to the automation or script
Variables in a script do not persist across automation calls. They’re session-local.
2.Can’t define inside condition,Pre-calculate in variables:
Define a global variable in the configuration.yaml in home assistant
| Limitation | Workaround | | read | write | |
| globally accessible | Use input_* helpers | input_text can handle max 255 characters limit.so anything more than shows an error in the logs. | | | detail |
| | Use dict() | | | | |
| Complex types can be tricky | Use json | json file | | | 1.use templating json |
| Using the “Variable” custom integration(rogro82) | | | | use custom integration https://github.com/rogro82/hass-variables action:
- service: variable.set_variable
data:
variable: last_motion
value: "livingroom"
attributes_template: >
{
"history_1": "{{ variable.state }}",
"history_2": "{{ variable.attributes.history_1 }}",
"history_3": "{{ variable.attributes.history_2 }}"
} | |
| | use state object | | | | 1.detail |
| | use template sensor | - sensor:
- name: "storen_data"
state: "active"
attributes:
data: |
{{ {"gaestebad": {
"entity_id": "cover.storen_1_cec9_storen_1_gaestebad",
"azimuth_min": 135,
"azimuth_max": 225,
"position_default": 100,
"tilt_default": 100,
"position_vor_abends": 0,
"tilt_vor_abends": 30,
"position_abends": 0,
"tilt_abends": 0,
"position_nacht": 0,
"tilt_nacht": 0,
"position_sonnenschutz": 0,
"tilt_sonnenschutz": 40,
"window_sensor": "sensor.custom_fenster_status_gaestebad",
"automation_active_sensor": "input_boolean.storen_automatic_gaestebad_fenster"} } }} | {{state_attr('sensor.storen_data', 'data').gaestebad.azimuth_min}} | | 1.detail detail |
| | use Trigger template sensor | Trigger based template sensor to store global variables | | Handle custom events # this configuration can be placed in configuration.yaml
- trigger:
- platform: event
event_type: set_variable
- platform: event
event_type: remove_variable
- platform: event
event_type: clear_variables
condition:
- condition: template
value_template: >
{{
(
trigger.event.event_type == 'set_variable'
and trigger.event.data is defined
and trigger.event.data.key is defined
and trigger.event.data.value is defined
)
or
(
trigger.event.event_type == 'remove_variable'
and trigger.event.data is defined
and trigger.event.data.key is defined
)
or
trigger.event.event_type == 'clear_variables'
}}
action:
- if: "{{ trigger.event.data.get('log', state_attr('sensor.variables', 'log_events')) }}"
then:
- service: logbook.log
data:
name: "{{ trigger.event.event_type }}:"
message: >
{{ trigger.event.data.key | default('All variables removed') }}
{%- if trigger.event.event_type == 'set_variable' -%}
: {{ trigger.event.data.value }}.
{%- endif -%}
sensor:
- unique_id: 4a4c8e53-9e68-4198-9cc5-b336e228ea4d
name: Variables
state: Variables
attributes:
default_timestamp: false
log_events: false
variables: >
{% set others = dict(this.attributes.get('variables', {}).items() | rejectattr('0', 'eq', trigger.event.data.key)) %}
{% if trigger.event.event_type == 'set_variable'
and trigger.event.data.get('set_timestamp', this.attributes.get('default_timestamp', false))
%}
{% set value = trigger.event.data.value %}
{% set value = value.isoformat() if value is datetime else value %}
{% set new = {trigger.event.data.key: {'value': value, 'timestamp': now().isoformat()}} %}
{{ dict(others, **new) }}
{% elif trigger.event.event_type == 'set_variable' %}
{% set new = {trigger.event.data.key: trigger.event.data.value} %}
{{ dict(others, **new) }}
{% elif trigger.event.event_type == 'remove_variable' %}
{{ others }}
{% elif trigger.event.event_type == 'clear_variables' %}
{}
{% endif %} | 1.detail |
| | Mqtt sensor | | | | |
| | RESTful Sensor and RESTful Binary Sensor | | | post http://homeassistant.local:8123/api/states/:entity_id {
"state": "below_horizon",
"attributes": {
"next_rising":"2016-05-31T03:39:14+00:00",
"next_setting":"2016-05-31T19:16:42+00:00"
}
} | 1.detail |
| | command_line sensor | json | | | 1.detail |
Using a global variable in the data/json in home assistant
json file
| Limitation | Workaround | | read | write | |
| json file | | | Integration | Integration | detail |
| json data via jija templating | /data/homeassistant202405/custom_template/stations.jinja {% macro stations_data() %}
[
{
"name": "Station One",
"url": "https://one.example.com",
"inital_volume": 120
},
{
"name": "Radio two",
"url": "https://two.example.com",
"inital_volume": 100
},
{
"name": "LiveTalk",
"url": "https://three.example.com",
"inital_volume": 110
}
]
{% endmacro %} | json file | | | 1.use templating json |
| local json file | Reading JSON from a file using Python | detail | import json
# Read from file and parse JSON
with open("sample.json", "r") as f:
data = json.load(f)
print(data)
print(type(data)) | import json
data = {
"name": "sathiyajith",
"rollno": 56,
"cgpa": 8.6,
"phone": "9976770500"
}
with open("sample.json", "w") as f:
json.dump(data, f) | |
| | use rest_command integration | This integration can expose regular REST commands as actions. Actions can be called from a script or in automation detail 2.detail | | | 1.detail |
| | use file integration | | | | 1.detail |
| | use python_script integration | | | Handle custom events | 1.detail 2.detail |
| | Mqtt sensor | | | | |
| json file + template sensor in configuration.yaml | | | template:
- binary_sensor:
- name: "Chinese Holiday Today"
state: >
{% set file = '/config/data/holiday-cn-2025.json' %}
{% set data = read_file(file) | from_json %}
{% set today = now().strftime('%Y-%m-%d') %}
{% set holiday = data | selectattr('date', 'equalto', today) | list %}
{{ holiday | count > 0 }}
attributes:
friendly_name: "Is today a Chinese holiday?"
| | |
| json file +restful api template sensor in configuration.yaml https://www.home-assistant.io/integrations/sensor.rest/ | | | | post http://homeassistant.local:8123/api/states/:entity_id {
"state": "below_horizon",
"attributes": {
"next_rising":"2016-05-31T03:39:14+00:00",
"next_setting":"2016-05-31T19:16:42+00:00"
}
} | 1.detail |
| http json+rest_command | https://www.home-assistant.io/integrations/rest_command | | rest_command:
secured_command:
url: "http://example.com/api/secure-endpoint"
method: post
authentication: digest
username: "your_username"
password: "your_password"
payload: '{"data": "example"}'
content_type: "application/json" | | 1.detail 2.detail |
| local json file+command_line | command_line sensor | json | command_line:
- sensor:
name: JSON user
command: python3 -c "import requests; print(requests.get('https://jsonplaceholder.typicode.com/users').text)"
json_attributes_path: "$.[0].address"
json_attributes:
- street
- suite
- city
- zipcode
value_template: "{{ value_json[0].name }}" | | 1.detail |
Conclusion
In Home Assistant, "global variables" are typically implemented using Helper entities, specifically Input Booleans, Input Numbers, or Input Texts. These entities act as containers for values that can be accessed and modified by various automations, scripts, and even displayed in the user interface.
Home Assistant’s REST API documentation shows that you can create an entity and update the state of the entity with just one HTTP POST request to URL POST /api/states/<entity_id>.
useful links
https://blog.usro.net/2025/05/mastering-home-assistant-variables-for-smarter-automations/
http://localhost:4999/boards/topic/37186/global-variables-in-home-assistant-yaml#56820
Comments
Comments are closed