FWIW, here’s one of the more complicated automations I’ve created recently. It’s part of a system to restoring active timers that were interrupted by a restart. Before the advent of variables, it would not be possible to write this as a YAML automation (the original version was a python_script). It serves as an example of how variables can be used.
-
The
modesvariable, whose scope is the entire action, is defined once, outside therepeat. It could be defined outside theactionbut it’s not used anywhere other than within theactionso that’s where I chose to define it. -
The
modeandtimers_textvariables are defined within therepeatand are redefined every repetition (just twice in all becausecountis2). -
The
timersvariable is defined withinchooseand is based on thetimers_textvariable. -
The remaining three variables,
t,id, andd, are defined within a nestedrepeatand their values are based on other variables.
- alias: 'Timers Restore'
mode: single
trigger:
platform: homeassistant
event: start
action:
- variables:
modes:
- active
- paused
- repeat:
count: 2
sequence:
- variables:
mode: '{{ modes[repeat.index-1] }}'
timers_text: "{{ states('input_text.timers_' ~ mode) }}"
- choose:
- conditions: '{{ timers_text | length > 0 }}'
sequence:
- variables:
timers: "{{ timers_text.split(',') }}"
- repeat:
count: '{{ timers | count }}'
sequence:
- variables:
t: '{{ timers[repeat.index-1].split() }}'
id: 'timer.{{t[0]}}'
d: "{{ t[1]|int - (now().timestamp()|int if mode == 'active' else 0) }}"
- condition: template
value_template: '{{ d > 0 }}'
- service: timer.start
data:
entity_id: '{{ id }}'
duration: '{{ d }}'
- condition: template
value_template: "{{ mode == 'paused' }}"
- service: timer.pause
data:
entity_id: '{{ id }}'