How to trigger.to_state inside a script help

Having the trigger.to_state within the automation works. However, it does not work if inside of a script. This error occurs. How to rewrite the code inside the script?

Door Family Greetings: Error executing script. Error for call_service at pos 1: Error rendering data template: UndefinedError: ‘trigger’ is undefined

This works:

- alias: announce who is arriving
  trigger:
     - platform: state
       entity_id: 
        - input_boolean.duc_home
        - input_boolean.eri_home
       to: 'on'
  action:
    - service: notify.alexa_media
      data_template:
        data:
          type: tts
        target:
         - media_player.ai_1
        message: '{{ trigger.to_state.attributes.friendly_name }}, will be home in about 10 minutes.'

This does not work:

- alias: announce who is arriving
  trigger:
     - platform: state
       entity_id: 
        - input_boolean.duc_home
        - input_boolean.eri_home
       to: 'on'
  action:
    - service: script.turn_on
      data:
        entity_id: script.door_family_greeting

script:

  door_family_greeting:
    alias: Door Family Greetings
    sequence:
      - service: notify.alexa_media
        data_template:
          data:
            type: tts
          target:
          - media_player.ai_1
          message: '{{ trigger.to_state.attributes.friendly_name }}, will be home in about 10 minutes.'

It doesn’t work for the simple reason that the Trigger State Object doesn’t exist outside the automation.

If you want the script to receive the Trigger State Object’s value, you must pass it as a variable to the script.

The procedure is explained here: Passing variables to scripts

Your automation will look something like this (the variable’s name can be whatever you want; I used the word person):

- alias: announce who is arriving
  trigger:
     - platform: state
       entity_id: 
        - input_boolean.duc_home
        - input_boolean.eri_home
       to: 'on'
  action:
    - service: script.door_family_greeting
      data:
        person: "{{ trigger.to_state.attributes.friendly_name }}"

Your script will refer to the variable called person. For example:

  door_family_greeting:
    alias: Door Family Greetings
    sequence:
      - service: notify.alexa_media
        data_template:
          data:
            type: tts
          target:
          - media_player.ai_1
          message: '{{ person }}, will be home in about 10 minutes.'
3 Likes

Perfect explanation. Understood.