The best way to automate multiple, similar - sensor (button) to light toggle actions

I have 30 simple lights buttons at my house connected to Home Assistant. They are represented as sensors which have RELEASED/PRESSED states.

I have my automations currently implemented with AppDaemon where I was able to do some simple mapping to avoid duplications of automations.

I plan to switch to Home Assistant native YAML automations and I am looking for the best way to do that.
I would like it to be concise and avoid creating separate automation for each pair of sensor-light.

I’ve found that one option to do that is to use “chooser” in automation so I came up with something like this (example for 2 lights):

- alias: Toggle lights
  description: 'Toggle lights on button press'
  trigger:
  - platform: state
    entity_id:
    - sensor.button_workshop
    - sensor.button_bathroom
  action:
  - choose:
    - conditions:
      - condition: state
        entity_id: sensor.button_workshop
        state: PRESSED
      sequence:
      - service: light.toggle
        entity_id: light.workshop
    - conditions:
      - condition: state
        entity_id: sensor.button_bathroom
        state: PRESSED
      sequence:
      - service: light.toggle
        entity_id: light.bathroom
    default: []

I am wondering if there is any better/alternative way of specifying such a simple automation for multiple entities.

Create a script with the lights and the sensor as a variable. Then call the same script with the different lights and sensors as an input.

Thanks @Burningstone for putting me on the right track.

I’ve started with script like this:


toggle_light:
  alias: "Toggle light"
  icon: "mdi:lightbulb"
  description: "Toggle light on button pressed"
  fields:
    button_entity:
      description: "Button pressed"
      example: "sensor.bedroom_button"
    light_entity:
      description: "Light to toggle"
      example: "light.bedroom"
  sequence:
    - condition: template
      value_template: "{{ is_state(button_entity, 'PRESSED') }}"
    - service: "light.toggle"
      data:
        entity_id: "{{ light_entity }}"

and then made one more step to have everything in automation:

- alias: "Toggle light on button pressed"
  trigger:
  - platform: state
    entity_id:
    - sensor.button_workshop
    - sensor.button_bathroom
  condition:
    - condition: template
      value_template: "{{ is_state(trigger.entity_id, 'PRESSED') }}"
  action:
    service: light.toggle
    data:
      entity_id: >
        {% 
          set entity_map = {
            "sensor.button_workshop": "light.workshop",
            "sensor.button_bathroom": "light.bathroom"
            }
        %}
        {{ entity_map[trigger.entity_id] }}

I still don’t like that I need to have same sensors mentioned twice (in trigger and in action), but I think it is good enough.

I would be happy to hear, if anyone has a better way to do this.

Thanks for help.