Templating entity_id in an automation service

Hi all,

Been at this a few hours now and I can’t figure out what the issue is. I’d like to use a template to define an entity_id in my service, but no matter what I do I get the error:

Invalid config for [automation]: not a valid value for dictionary value @ data[‘action’][1][‘entity_id’].

Even the simplest templating test does not work:

- alias: '[lights] motion: on'
  trigger: 
    platform: state
    entity_id: 
      - binary_sensor.mechanical_trisensor_home_security_motion_detection
    to: 'on'
  action: 
    - service: light.turn_on
      entity_id: "{{ 'light.mechanical_light' }}"

Many thanks.

You probably need to provide a little more background on what are you trying to actually do. E.g. why are you trying to template a light entity in the above example?

Are you trying to retrieve an entity_id from inside a variable, or stored inside another entity id?

I’d like to create a single trigger that holds a list of motion sensors that each activate a related light. Something like this:

- alias: '[lights] motion: on'
  trigger: 
    platform: state
    entity_id: 
      - binary_sensor.mechanical_trisensor_home_security_motion_detection
    to: 'on'
  action: 
    - service: light.turn_on
      entity_id: "light.{{ trigger.entity_id.split('.')[1].split('_')[0] }}_light"

Where I can continue to add sensors to the trigger entity_id and they will correspond to appropriately named lights.

That said, I would also like to understand why templating isn’t working in this case. I’ve seen examples of templating an entity_id on these forums.

If your motion sensors and lights have the same object_id this becomes trivial.

entity_ids are composed like this: domain.object_id and the object_id of the triggering entity can be obtained in a template.

e.g. using the entities:

binary_sensor.lounge_room
light.lounge_room

binary_sensor.main_hall
light.main_hall
- alias: '[lights] motion: on'
  trigger: 
    platform: state
    entity_id: 
      - binary_sensor.lounge_room
      - binary_sensor.main_hall
    to: 'on'
  action: 
    - service: light.turn_on
      target:
        entity_id: "light.{{ trigger.to_state.object_id }}"

All you have to do is add more binary sensors to the trigger list.

Thanks tom_l. I was missing the target: syntax. That did the trick.

It’s not strictly necessary. For backward compatibility this will also work:

  action: 
    - service: light.turn_on
      data:
        entity_id: "light.{{ trigger.to_state.object_id }}"