If-then-else in automation action

I’m trying to implement a simple security alarm with multiple control buttons that should a) turn off the alarm if it’s already fired and b) toggle ‘armed’ status of the system if there is no ongoing alarm. Current setup is like following:

input_boolean:
  arm_status:
    name: Arm Status
    initial: off
  alarm_bell:
    name: Alarm Bell
    initial: off

automation:
- alias: Security buttons turn off alarm
  trigger:
    # multiple button triggers, all work fine
  condition:
    condition: state
    entity_id: input_boolean.alarm_bell
    state: 'on'
  action:
    - service: input_boolean.turn_off
      entity_id: input_boolean.alarm_bell

- alias: Security buttons toggle armed status
  trigger:
    # the same long triggers block
  condition:
    condition: state
    entity_id: input_boolean.alarm_bell
    state: 'off'
  action:
    - service: input_boolean.toggle
      entity_id: input_boolean.arm_status

I wonder if I can “merge” these two automations into one. I know from documentation that conditions can be used in action, but as I understood, they can only stop actions at certain point when condition is false, while I need to run different action otherwise. Thanks.

1 Like

Yes, you can add conditional if/then/else logic in the action: section using templating: https://www.home-assistant.io/docs/configuration/templating/

1 Like

Thank you, I figured it out! I was aware of templating and used templates here and there, but didn’t know that I can use them not only to format data, but also to call services. So, posting here my current working configuration:

  action:
    service_template: >
      {% if (is_state("input_boolean.alarm_bell", "on")) -%}
      input_boolean.turn_off
      {%- else -%}
      input_boolean.toggle
      {%- endif %}
    data_template:
      entity_id: >
        {% if (is_state("input_boolean.alarm_bell", "on")) -%}
        input_boolean.alarm_bell
        {%- else -%}
        input_boolean.arm_status
        {%- endif %}
5 Likes