Templating trigger conditions

I’m trying to set up a couple of automations that will control numerous lights via separate random timers, and I really don’t want to have a dedicated pair of on/off automations per light. After several lengthy exchanges with my friends Mr Google and Mr ChatGPT I came up with the code below. I basically want the automation to check and control light.porch when timer.porch expires, light.tv_room when timer.tv_room expires, etc but I can’t get around the syntax error that Studio Code Server throws up at the line:

entity_id: >

Any help would be most gratefully received.

- alias: turn_on_random_light
  description: Turn on the light associated with a random lighting timer
  trigger:
  - platform: state
    entity_id:
    - timer.desk
    - timer.porch
    - timer.tv_room
    - timer.utility_room
    to: 'idle'
  condition:
  - condition: template
    value_template: "{{ states(entity_id) == 'off' }}"
    entity_id: >  
      {% set entity_name = trigger.entity_id.split('.')[1] %}
      light.{{ entity_name }}
  - condition: time
    before: '23:00'
  action:
  - service: light.turn_on
    data:
      entity_id: light.{{ entity_name }}
  - service: timer.start
    entity_id: timer.{{ entity_name }}
    data:
      duration: '{{ 60 * range(5, 15) | random }}'
#

entity_id is not a valid configuration variable for a template trigger. When using variables, you need to declare your variable so that its scope covers everywhere you need to use it.

- alias: turn_on_random_light
  description: Turn on the light associated with a random lighting timer
  trigger:
  - platform: state
    entity_id:
      - timer.desk
      - timer.porch
      - timer.tv_room
      - timer.utility_room
    to: 'idle'
    variables:
      light_id: "{{ trigger.entity_id | replace('timer', 'light') }}"
  condition:
  - condition: template
    value_template: "{{ is_state(light_id, 'off') }}"
  - condition: time
    before: '23:00'
  action:
  - service: light.turn_on
    data: []
    target:
      entity_id: "{{ light_id }}"
  - service: timer.start
    target:
      entity_id: "{{ trigger.entity_id }}"
    data:
      duration: "{{ 60 * range(5, 15) | random }}"
mode: parallel
1 Like

Thank you so much @Didgeridrew, I was starting to pull out hair that I could not afford to lose! :wink: As the saying goes “Every day should be a learning day” and today certainly has been! :pray: