Use variables inside an automation

Hi, I would like to send a message by notification depending on the trigger that started the automation.
Here is my code, but everytime I receve the generic message “Une machine est terminée (mais je ne sais pas laquelle)”

alias: "ALERTE : Machine terminée"
description: ""
trigger:
  - platform: state
    entity_id:
      - sensor.lave_linge_statut
    id: lv_termine
    from: null
    to: complete
  - platform: state
    entity_id:
      - sensor.seche_linge_statut
    to: complete
    from: null
    id: sl_complete
condition: []
action:
  - choose:
      - conditions:
          - condition: trigger
            id:
              - lv_termine
        sequence:
          - variables:
              message_text: Lave Linge terminé
      - conditions:
          - condition: trigger
            id:
              - sl_complete
        sequence:
          - variables:
              message_text: Sèche Linge terminé
  - service: notify.constg
    data:
      message: "INFO : {{ message_text }} "
variables:
  message_text: Une machine est terminée (mais je ne sais pas laquelle)
mode: single

Any idea why the variable is not modified?
Thanks.

Read the section on variable scope.

Alternative solution without variables:

alias: "ALERTE : Machine terminée"
trigger:
  - platform: state
    entity_id:
      - sensor.lave_linge_statut
      - sensor.seche_linge_statut
    from: null
    to: complete
action:
  - service: notify.constg
    data:
      message: >
        {{ "INFO : " ~
           {"sensor.seche_linge_statut": "Sèche",
            "sensor.lave_linge_statut": "Lave"}[trigger.to_state.entity_id] ~ 
            " Linge terminé" }}

Would have been easier without the accent in “Sèche”: could have just used:

message: "{{ trigger.to_state.entity_id.split('.')[1].split('_')[:2]|map('title')|join(' ') }} terminé"
1 Like

Haaaaa ok thank you. I missed that part.
DO you know any way to do what I need to do then? Using an helper maybe?

Thank you, this seems more elegant indeed. Problem is I will next need to notify multiple devices, with the same message. :confused:

I think this should work:

action:
  - variables:
      message_text: >
        {% set messages = {"sensor.seche_linge_statut": "Sèche Linge terminé",
                           "sensor.lave_linge_statut": "Lave Linge terminé"} %}
        {% set inconnu = "Une machine est terminée (mais je ne sais pas laquelle)" %}
        {{ messages.get(trigger.to_state.entity_id, inconnu) }}
  - service: notify.constg
    data:
      message: "INFO : {{ message_text }} "
  - service: notify.another_notifier
    data:
      message: "INFO : {{ message_text }} "

get() is a Python dictionary method documented here.

3 Likes

Yes it’s working! Thank you :slight_smile: