Automation if/then: How to use variables from the 'if' statement in the 'then' process?

Hi, I have an automation with an if statement:

{% set thisEntity = trigger.entity_id.split('.')[1].split('_')[0] %}
{% set helperName = "input_text."~thisEntity~"_best" %}
{% set tempSoll = (states(helperName) | float(0)) %}


{{ (tempSoll | float(0)) < 20 }}

This gives me true or false.

In the execution I would like to use the above variables:

service: system_log.write
data:
  level: warning
  message: Heizung einschalten {{trigger.entity_id}}
enabled: true

This is working, but I need something like this to have the teperature in the log for troubleshooting:

service: system_log.write
data:
  level: warning
  message: Heizung einschalten {{thisEntity}} - Soll: {{ (tempSoll | float(0)) }}
enabled: true

Unfortunately, the variables are empty
Any hint where to read this from?

Thanks

(This is only a readable example of the overall automation to come to the point…)

If you include the whole automation, we’d be able to help more.

Because you are including Jinja templating in the message, you should have the entire thing in quotes.

  message: "Heizung einschalten {{thisEntity}} - Soll: {{ (tempSoll | float(0)) }}"

Good practice but not absolutely necessary if the template is not the first thing in the string. I learned about this during this conversation.

Yes, it’s a yaml thing.

When yaml sees {, it attempts to process it as json.

e.g.

something: {"this": "works"}

So this forces us using home assistant to use quotes for templates because they start with a {.

When you start the field with a character that’s not something that can be confused with a json object, it automatically treats it as a string.

e.g.

something: blah{{ ... }}
something: "blah{{ ... }}"

are effectively the same.

This is not

something: {"this": "works"}
something: "{"this": "works"}"

This

something: {"this": "works"}

is actually this (long hand)

something:
  this: works
2 Likes

These are Jinja2 variables and they are accessible only where you define them.

{% set thisEntity = trigger.entity_id.split('.')[1].split('_')[0] %}
{% set helperName = "input_text."~thisEntity~"_best" %}
{% set tempSoll = (states(helperName) | float(0)) %}

You said they were part of an if’s condition so that’s the only place in the entire automation where they are available.

I suggest you define them as script variables at the beginning of your automation’s action.

action:
  - variables:
      thisEntity: "{{ trigger.entity_id.split('.')[1].split('_')[0] }}"
      helperName: input_text.{{ thisEntity }}_best
      tempSoll: "{{ states(helperName) | float(0) }}"
  - if: "{{ tempSoll < 20 }}"
    then:
      - service: system_log.write
        data:
          level: warning
          message: Heizung einschalten {{ thisEntity }} - Soll: {{ tempSoll }}
    else:
       ... etc ...
1 Like

Thanks.
This was exactly I was looking for.

1 Like