Templated automation failing checks when automations reloaded

I’m having trouble templating an automation. The working version can be seen commented out at the top of the code. What I’m trying to do is to generalise the specific automation to work with all zwave switches.

#- alias: remote_shed_heater_control
#  trigger:
#    - platform: mqtt
#      topic: "hassio_2/switch/tkb_home_tz68_on_off_switch_socket_switch/command"
#  action:
#    - service_template: "switch.turn_{{trigger.payload | lower}}"
#      entity_id: switch.tkb_home_tz68_on_off_switch_socket_switch

- alias: remote_switch_control
  trigger:
    - platform: mqtt
      topic: hassio_2/switch/+/command
  action:
    service_template: >
      switch.turn_{{ trigger.payload | lower }}
      entity_id: switch.{{ trigger.topic.split('/')[ -2 ] }}

The errors I see are:

Error while executing automation automation.remote_switch_control. Invalid data for call_service at pos 1: Service switch.turn_off entity_id: switch.tkb_home_tz88_smart_energy_plug_in_switch_switch_4 does not match format <domain>.<name>
4:31 PM helpers/script.py (ERROR)
Error while executing automation automation.remote_switch_control. Invalid data for call_service at pos 1: Service switch.turn_off entity_id: switch.tkb_home_tz88_smart_energy_plug_in_switch_switch_3 does not match format <domain>.<name>
4:31 PM helpers/script.py (ERROR)
Error while executing automation automation.remote_switch_control. Invalid data for call_service at pos 1: Service switch.turn_on entity_id: switch.tkb_home_tz68_on_off_switch does not match format <domain>.<name>
4:31 PM helpers/script.py (ERROR)
Error while executing automation automation.remote_switch_control. Invalid data for call_service at pos 1: Service switch.turn_on entity_id: switch.tkb_home_tz68_on_off_switch_socket does not match format <domain>.<name>
4:31 PM helpers/script.py (ERROR)

You need to separate the data for the service call from the service template. Try this:

  action:
    service_template: >
      switch.turn_{{ trigger.payload | lower }}
    data_template:
      entity_id: "switch.{{ trigger.topic.split('/')[ -2 ] }}"
1 Like

Thanks. That did it.