Automation "this" - to get automation entity_id

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) }}
1 Like

Thank you very much, it was no clear to me that ‚this’ in automation represents ‚state’ object.

Is it better to write:

this.attributes.last_triggered is not defined or 
      now() - this.attributes.last_triggered >= timedelta(days=2)

or

now() - state_attr(this.entity_id, '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)
1 Like

Another way to do the same thing:

now() - this.attributes.last_triggered | default(as_datetime(0)) >= 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.

now() - state_attr(this.entity_id, 'last_triggered') >= timedelta(days=2)

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.

1 Like

I really like how clean the default solution looks. Thank you both!

Glad you like it but what was the reason you didn’t assign it the Solution tag? Was the template more difficult to understand?