Where can you put variables in your automation and state based trigger templates and template sensors

Automations:

YAML variables can be defined multiple places. Though all variables have script-wide scope, variables that are attached to a trigger that is not the initiating trigger, or those that are part of unused branches of Choose or If/Then actions will not be resolved.

trigger_variables:
  var_1: true #Only Limited Templates and static values allowed
trigger:
  - platform: template
    value_template: "{{ states('binary_sensor.x') | bool == var_1 }}"
    variables:
      var_2: "{{ false }}" #If you have multiple triggers, this value applies only when this specific trigger initiates the automation.
variables:
  var_3: "{{ true }}"
condition:
  - variables:
      var_4: "{{ true }}"
action:
  - variables:
      var_5: "{{ true }}"
  - choose:
      - conditions: 
          - condition: template
            value_template: "{{ var_2 }}" 
        sequence:
          - variables:
              var_6: "{{ false }}" #This value only applies for this Option of the Choose action.

* Variables will be populated with values roughly in the order I have numbered above.

State-Based Template Sensors:

YAML variables aren’t really supported in state-based template sensors. You can use the sensor’s attributes to render and store values that are used in the state template. In most cases it would be better to just set up another template sensor instead of self-referencing attributes.

Trigger-Based Template Sensors:

YAML variables can be defined at the trigger, in a variables block, or in the action block of a trigger-based template sensor. These variables are available for use in the state template as well as any attribute templates. Variables will be populated with values roughly in the order I have numbered below.

trigger:
  - platform: numeric_state
    entity_id: sun.sun
    attribute: elevation
    above: -4.0
    variables:
      var_1: "{{ now().day }}"
  - platform: numeric_state
    entity_id: sun.sun
    attribute: elevation
    below: -4.0
    variables:
      var_1: 1
variables:
  var_2: 2
action:
  - variables:
      var_3: "{{ var_1 is even }}"
binary_sensor:
  - name: Example
    state: "{{ var_2 }}"
    attributes:
      day: |
        {% set prev = var_1 if this is undefined else this.attributes.day %} 
        {{  iif(var_3, var_1, prev) }}

UPDATE:

2024-01-28: It is likely that there will be significant changes to variables for both State and Trigger-based Template sensors and binary sensors (and possibly other template entities) in the coming year as progress is being made toward expanding Template Blueprints.

2 Likes