I’m writing an automation to water the garden. Is there an alternative syntax to obtain the entity_id of a automation, other than just hardcoding it, as I did here:
alias: Water the garden
description: ""
trigger:
- platform: sun
event: sunrise
offset: 0
condition:
- condition: template
value_template: >-
{{ now() - state_attr('automation.water_the_garden','last_triggered') >=
timedelta(days=2) }}
action:
- service: script.water_the_garden
data: {}
mode: single
You can use the this variable. With any automations based on last_triggered, you will need to include a clause to allow the first run where last_triggered isn’t defined.
condition:
- condition: template
value_template: >-
{{ this.attributes.last_triggered is not defined or
now() - this.attributes.last_triggered >= timedelta(days=2) }}
Sorry about the deleted post, I wanted to test both options quickly… It looks like either will work, but AFAIK it is slightly more efficient to use the first option because you don’t have to re-render the value.
FYI, for new automations you would need to include the or clause either way:
this.attributes.last_triggered is not defined or
now() - this.attributes.last_triggered >= timedelta(days=2)
or
this.attributes.last_triggered is not defined or
now() - state_attr(this.entity_id, 'last_triggered') >= timedelta(days=2)
A new automation that has never triggered yet will not have a last_triggered attribute. Therefore the following template will fail for a new, untriggered automation. The state_attr() function will return a null object (none) and the subtraction will produce an error.
That’s why Didgeridrew’s example tests if last_triggered is not defined and my example above provides a default value in case last_triggered is undefined.