Pass trigger's entity_id to Python script

Is there a way to pass the entity_id that fired a trigger to a Python script?

I have a single Automation set up with two triggers, one for each of my garage doors. I’d like to pass the entity_id of the door that fires the Automation to the Python script. I know I could set up two separate Automations and hard code the entity_id, but I’m looking for something more elegant.

Thanks!

2 Likes

You should be able to do:

action:
  service: python_script.your_script_name
  data_template:
    entity: "{{ trigger.entity_id }}"

…and then the entity id that triggered the automation should be available in your script like so:

entity = data.get('entity')
1 Like

That worked! Thanks!

So moving forward, I’ve changed my Automation from triggering on state to triggering on event. This changes the format of where the entity_id is located. Instead of being a direct child of trigger it is now under event_data.

- id: '1531149972632'
  alias: Car Arrives Home
  trigger:
  - event_data:
      entity_id: cover.left_bay
    event_type: state_change
    platform: event
  - event_data:
      entity_id: cover.right_bay
    event_type: state_change
platform: event
  condition: []
  action:
  - data_template:
      entity: '{{ trigger.entity_id }}'
    service: python_script.garage_door

…and of course entity_id is not getting passed to my script now.

I’ve tried setting the data_template to look this:

  - data_template:
      entity: '{{ trigger.event_data.entity_id }}'
    service: python_script.garage_door

…but this doesn’t work either.

Is there a doc that explains how the data binding between an Automation and Python Script works? I’d prefer to be pointed to where I can figure this out myself, but if a doc doesn’t exist I’d appreciate some help.

Thanks!

This should give you what you need: https://www.home-assistant.io/docs/automation/templating/. I haven’t tried it, but I suspect you could use “{{ trigger.event.data.entity_id }}”.