Script data template issue


I have been struggling with trying to figure out why this will not work and would really appreciate some help on this.

I am trying to execute a script within a script if motion has not been detected for > 300 seconds. When I run this in the built-in template tester, it works fine. When it is running within the script, I get an error.

This is the code:

- service: script.turn_on
    entity_id: >
      {% if states.binary_sensor.motion_sensor_158d0001e5ceb5.attributes['No motion since'] > 300 %}
      {% else %}
      {% endif %}

I get the following error when this code runs:
Invalid service data for script.turn_on: Entity ID is an invalid entity id for dictionary value @ data[‘entity_id’]. Got ‘’

Thank you for your help!

Because your if statement is returning nothing if the ‘if test’ fails. You need to create a dummy script to execute if that occurs. Or build a condition before executing the script to test that case:

- condition: template
  value_template: "{{ states.binary_sensor.motion_sensor_158d0001e5ceb5.attributes['No motion since'] > 300 }}"
- service: script.test_voice

script.test_voice will only execute when the condition before hand is met. Otherwise it won’t execute anything.

Thanks Petro!

Just trying to wrap my head around this. So when you say if the if test fails, do you you mean that states.binary_sensor.motion_sensor_158d0001e5ceb5.attributes[‘No motion since’] returns nothing instead of a value? What would I need to add to if statement to cover that scenario?

Also, can I put a ‘condition: template’ inside of scripts.yaml? My understanding is that conditions were only allowed in automations.yaml.


No, when "if states.binary_sensor.motion_sensor_158d0001e5ceb5.attributes['No motion since'] > 300" fails. Meaning if your sesnor is less than 300. You output this:

  {% else %}
  {% endif %}

Which is nothing. You essentially provide the the script.turn_on service a blank entity_id. You will get tis error:

Invalid service data for script.turn_on: Entity ID is an invalid entity id for dictionary value @ data['entity_id']. Got ''

There are two parts of an automation that can contain conditions: 1) The condition section of the automation, and 2) the action section of the automation. In effect, the action part of an automation is a script. Anything you can do in a script you can do in the action part of an automation, and vice versa. See:

And especially see the link in the first paragraph where it says, “The action part follows the script syntax …” If you follow that link you’ll eventually get to this:

Got it working now! Thank you!!