Reusable automation templates

At the moment, my automations contain a lot of repeated code which could be eliminated. Automation needs a template function.

Example: I am using automation to make the blinds of my windows close when the windows are closed after sunset. Currently it looks like this:

- alias: 'Niklas: Rolladen links schließen wenn Fenster schließen'
  trigger:
    platform: state
    entity_id: binary_sensor.niklas_fenster_links_state
    from: 'on'
    to: 'off'
    for:
      seconds: 5
  condition:
    condition: numeric_state
    entity_id: sun.sun
    value_template: '{{ state.attributes.elevation }}'
    below: -4.75
  action:
    service: cover.close_cover
    data:
      entity_id: cover.niklas_rolladen_links

- alias: 'Niklas: Rolladen links schließen wenn Fenster schließen'
  trigger:
    platform: state
    entity_id: binary_sensor.niklas_fenster_rechts_state
    from: 'on'
    to: 'off'
    for:
      seconds: 5
  condition:
    condition: numeric_state
    entity_id: sun.sun
    value_template: '{{ state.attributes.elevation }}'
    below: -4.75
  action:
    service: cover.close_cover
    data:
      entity_id: cover.niklas_rolladen_rechts

Both automations are almost exactly the same except for the entity ids. This automation could be defined as a template automation, the entity ids would be passed on as parameters.

There are even more complex examples than this one which would make this a very useful feature. Not sure if this is easy to implement, though.

Why not just use both entity ids and then change action entity_id based on which trigger.entity_id fired the automation. Then you’re just writing 1 automation

mta: I think this should be a working example

- alias: 'Your Alias Here'
  trigger:
    platform: state
    entity_id: binary_sensor.niklas_fenster_rechts_state, binary_sensor.niklas_fenster_links_state
    from: 'on'
    to: 'off'
    for:
      seconds: 5
  condition:
    condition: numeric_state
    entity_id: sun.sun
    value_template: '{{ state.attributes.elevation }}'
    below: -4.75
  action:
    service: cover.close_cover
    data_template:
      entity_id: >
        {% if trigger.entity_id == 'binary_sensor.niklas_fenster_rechts_state' %}
          cover.niklas_rolladen_rechts
        {% else %}
          cover.niklas_rolladen_links
        {% endif %}
1 Like