Using string variables in automation

Hi all,

I’m trying to create an automation that sends a critical notification if water is detected.
I want the notification to contain the location of where water was detected. I figured I could use a variable that contained the location name to do this.

But somehow the variables don’t get put into the message. I found many topics covering variables in notifications, somehow, when I try it, it does not seem to work.

As an easy example I have an automation with a static location:

alias: Watersensor
description: ""
variables:
  location: dishwasher
trigger:
  - type: moist
    platform: device
    device_id: 1bd81de3933ea4956127b92477480372
    entity_id: binary_sensor.lumi_lumi_sensor_wleak_aq1_iaszone
    domain: binary_sensor
    for:
      hours: 0
      minutes: 0
      seconds: 30
condition: []
action:
  - service: notify.notify
    data:
      message: Water detected at {{ location }}
      title: Water detected!
      data:
        push:
          sound:
            critical: 1
            volume: 1
mode: single

I saved the automation with the variable declared like this:

variables:
  location: "dishwasher"

But HASS seems to remove the quotes automatically. Same goes for the message and title box in the notify data section.

With the code above I get a notification with:
Title: “Water detected!”
Message: “Water detected at”

But the notification I would like is:
Title: “Water detected!”
Message: “Water detected at dishwasher”

Thanks in advance!

Move the variable block under actions. had a similar issue, and that fixed it.

Are you testing your automation by triggering it manually using its Run command?

If you test it like that, only the automation’s action is executed therefore the variables section outside of action isn’t evaluated (therefore the location variable will be undefined).

If you move variables inside of action it will ensure location is defined. However, this is only needed if you intend on testing the automation by triggering it manually. It’s unnecessary if you allow the automation to be triggered by it trigger. Read the following to understand why testing an automation by manually triggering it has many limitations that can lead to incorrect test results.

Testing your automation

A better way to test an automation is by actually triggering it. If it’s inconvenient to physically initiate the trigger (like pouring water to activate a leak detector), you can force it by using Developer Tools > States. Select the entity, set its state to the desired value (in this case it’s on) and then click the Set State button.

That was it! Good to learn about this feature.

In my automation I stated that the trigger has to last for at least 30 seconds. Is there a way to set the status to on for x seconds?