Variables scope involving IF statement

Obviously, no. And I can’t imagine finding a workaround that would be clean and efficient, otherwise it would probably already be known and most likely widely used, which is not the case.

I’m no developer so I don’t know if the current situation is dependent on Jinja or only HA, but in either case I’m pretty sure that changing this would require a big HA refactoring.

Moreover, this current “mechanism” is so obviously a “poor” and counter-intuitive design that I can only imagine that there was unfortunately a strong reason for making that choice in the first place. Maybe having done it the “proper” way would have made the whole automation mechanism extremely resource hungry.

So, big code duplication it is for now.

Jinja2 is used extensively in Home Assistant and is most often used to compute a YAML option’s value. The “option” can be an entity_id, value_template, state, a script variable, etc. It’s Home Assistant’s way of setting values.

I can’t comment on whatever code you may have created but for the following example, the second version is concise and contains no duplication.

Example 1

Due to scoping rules, ttsm is undefined outside of the automation’s if-then-else block.

  - if:
      - condition: time
        before: "12:00:00"
    then:
      - variables:
          ttsm: "{{ ttsm1 }}"
    else:
      - variables:
          ttsm: "{{ ttsm2 }}"

Example 2

ttsm is accessible throughout the automation’s actions section (i.e. below wherever ttsm is defined).

  - variables:
      ttsm: "{{ iif(now().hour < 12, ttsm1, ttsm2 }}"

Reference

Templating - Immediate If