Access automation's last_triggered attribute from within the automation itself?

I have an automation where I’d like to change the behavior if the automation itself has triggered recently. You could just create the automation, find the entity name, and then edit the automation to reference the correct entity. But that’s tedious and messy.

As an example, I’d like to be able to include a template condition like this:

{{ (as_timestamp(now()) - as_timestamp(state_attr('', 'last_triggered')))  < 120 }}

inside the automation Foo, but without hardcoding Is there a way to do this?

Some context in case there’s a better way to do this… I have some motion-sensors and some lights that automated to turn on with motion. I have one automation blueprint that triggers to turn them on and the same automation triggers again to turn them off.

I’d also like to have functionality to skip turning on the lights if the room is already sufficiently bright (many have done this already). The catch is that my motion sensors (with integrated illuminance sensor) don’t always update the illuminance value quickly (sometimes 30s or more).

The way this manifests in real life is that if you exit a room and the no-motion condition turns off the light, AND THEN you re-enter the room before the illuminance sensor has updated Home Assistant; the automation is triggered by motion, but it sees the (stale) illuminance value that indicates there’s sufficient light, and then the automation does not turn on the light.

My thoughts on a workaround for this are to set a condition for the automation that says if the automation has triggered in the last 60s (i.e. to turn off the lights), then ignore the illuminance value and turn them on anyway. And knowing when the automation was last triggered would enable that functionality…

I have exactly that same problem! Did you solve it?

I don’t believe it existed a year ago, but you can now refer to the automation using the this variable. For example:

{{ now() - this.attributes.last_triggered < timedelta(seconds=120) }}
1 Like