Quick guide to variables in automations

From a post by @Didgeridrew

In 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 but, if you have multiple triggers, this value applies only when this specific trigger initiates the automation
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.

Home Assistant Cookbook

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