Quick guide to variables in automations

This topic is part of the community-driven cookbook where you can find other topics you might be interested in or might like to contribute to.

Automations:

YAML variables can be defined multiple places, their scope depends on where they are defined.

trigger_variables:
  var_1: true #script-wide (only Limited Templates and static values allowed)
trigger:
  - platform: template
    value_template: "{{ states('binary_sensor.x') | bool == var_1 }}"
    variables:
      var_2: "{{ false }}" #script-wide (only variables attached to the trigger that initiates the automation will be instantiated)
variables:
  var_3: "{{ true }}" #script-wide
condition:
  - variables:
      var_4: "{{ true }}" #local to condition block
action:
  - variables:
      var_5: "{{ true }}" #local to action block
  - choose:
      - conditions: 
          - condition: template
            value_template: "{{ var_2 }}" 
        sequence:
          - variables:
              var_6: "{{ false }}" #local to this Option of this Choose action    

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


This Cookbook is an excerpt. Please refer to the previous post for information about using Variables more broadly.

Home Assistant Cookbook

1 Like

One further thing to note is that even though var1 is available script-wide, if you change it inside a nested block of yaml (e.g. in the choose sequence) those changes will not be available outside that block.

https://www.home-assistant.io/docs/scripts#scope-of-variables

2 Likes

EDITed as I realised my understanding of YAML variables was still not quite correct. I thought once defined they were immutable (effectively Constants).

From Tom’s comment re Scope, I now suspect that:
A Var can be “changed” (strictly re-defined?) at their creation scope level, but a Var of the same name defined at a deeper scope level is a new Var, and so effectively overrides the first Var’s value at that scope and deeper, but not at shallower scopes where the first Var definition will still apply. They are two separate items, both named Var.

So I think the full implications of “Variables have local scope” need making clearer. I’d mis-understood it, even knowing the local scope rule - I thought.

BTW I’m requesting this, pls vote if interested.