Passing Arguments to Scripts

I’ve been digging around the source code and it appears that I can pass variables to scripts when I call them with script.turn_on. I’m just not sure what the proper format is and how to actually use them in the script.

For example, I’m trying to write a generic script for turning something off automatically after some period of time following when it was turned on. (My kids leave lights on all over the house all time time.)

Here’s a snippet of what I’ve been trying to do:

  - alias: "Turn off upstairs sink light after a delay"
      platform: state
      entity_id: switch.upstairs_bathroo_switch_13
      from: "off"
      to: "on"
      service: script.turn_on
      entity_id: script.turn_off_after_delay
        desired_delay: "00:00:30"
        device_entity_id: switch.upstairs_bathroo_switch_13

    alias: "Turn something off after a delay"
      - delay: "{{ variables.desired_delay }}"
      - service: homeassistant.turn_off
        entity_id: "{{ variables.device_entity_id }}"

This gives me errors like:

Invalid config for [script]: Entity ID {{ XXXX }} is an invalid entity id for dictionary value...

I’m trying to avoid writing one of these scripts for each of my lights. Any suggestions?


Have a look at my tested example at the end of this thread:

The name of the variable should be accessible directly in the template. I don’t think that the entity_id key supports templating though. I’d be happy to be corrected.

it seems like it matters where you place the variable.

i think i tried it exactly like you did @martinhjelmare

- alias: 'raamhoek aan'
    platform: state
    entity_id: input_boolean.eetraamhoek
    to: 'on'
    service: script.turn_on
    entity_id: script.test
        message: 'P01t'

    alias: P01 aan
      - alias: schakel P01 aan
        service: switch.mysensors_send_ir_code
        entity_id: switch.afstandbediening_2_5
          V_IR_SEND: "{{ message }}"

but if i look what gets sendet: {{ message }}

edit: @pjones you forgot variables: after data:

Use key data_template to have the template rendered for the script service as data value.

1 Like

That’s the issue. The entity_id field doesn’t support templating.

you were right @martinhjelmare.

that was my failure.

@pjones cant you do it without script?

with automation-template
and with service template

something like:

switch a
switch b
switch c
data_template: {{trigger.entity_id}}

could also be that in youre script it could work like this:

entity_id: {{ device_entity_id }}

1 Like

Yes, it should work to put the entity_id key inside the data_template. If a delay is wanted, then a script is probably the easiest approach.

I just wanted to complete this thread by saying that the data_template technique does work for entity_id. Thanks!

1 Like

if the same question came up right now i would advice to install appdaemon and write a small app :wink:

1 Like