Issues setting variables in Automation action

I’m trying to write a single automation that will let me know if someone arrives at a location or leaves, excluding if the zone is “Home”.

Its all working up to the action. There’s two people being tracked who are listed under the trigger and the notification should go to the person that didn’t trigger the event.

Here’s the action part of the automation where the issue is. I’ve checked the traces and can see it triggers, passes conditions just fine, but then fails with an error:

UndefinedError: ‘trigger’ is undefined

I’ve read the trigger docs, reviewed many (many) forum posts (which were similar but not quite what I was after) and gone over and over this but being a newbie I know I’m probably missing something simple. Can anyone point out the obvious for me and assist with this final bit of the code please?

  - variables:
      person: '{{ state_attr("trigger.entity_id", "friendly_name") }}'
      notify_device: '{{ "mobile_app_nick_phone" if state_attr("trigger.entity_id",
        "friendly_name")=="Kevin" else "mobile_app_kevin_pixel" }}'
      activity: '{{ "arrived at {{ trigger.to_state }}" if "trigger.from_state"=="not_home"
        else "has left {{ trigger.from_state }}" }}'
  - service: notify.{{ notify_device }}
      message: '{{ person }} {{ activity }}'

The variable templates have a couple issues:

  • Don’t nest templates, just use the variable as it.
  • Use ~ or + to concatenate strings with the string values of rendered variables
  • Make sure you are retrieving the actual property or attribute you want, not the entire state object.
  - variables:
      person: '{{ }}'
      notify_device: |
        {{ "mobile_app_nick_phone" if person == "Kevin" else "mobile_app_kevin_pixel" }}
      activity: |
        {{ "arrived at "~trigger.to_state.state if trigger.from_state.state =="not_home" else "has left "~trigger.from_state.state }}
  - service: notify.{{ notify_device }}
      message: '{{ person }} {{ activity }}'

The error, UndefinedError: ‘trigger’ is undefined, is most often caused by users trying to test their automation using the “Run” option from the menu or the automation.trigger service call. Both of these methods bypass the trigger, so the trigger variable is not created. To test automations that rely on the trigger variable, you can use the States tool, entering the desired state in the “State” field and clicking the “Set State” button.

Thanks Drew.

I was testing using the “States” option in Dev Tools as I knew about that already.

I suspect it was the formatting issues that caused the problems. I’ll re-work my code and see if that fixes things.

Thanks for your help - as mentioned I’m still learning and whilst some of the templating stuff seems straight forward, other bits I still need to learn a lot on!

EDIT: Works like a charm. Thx

1 Like