Struggeling with variables

I am new here at the HA forum (and HA in general), so forgive me for stating obvious things.

Tried this script:

sequence:
  - variables:
      text_to_speak: Alarm is on
  - if:
      - condition: state
        entity_id: alarm_control_panel.location_hjemme
        state: disarmed
    then:
      - variables:
          text_to_speak: Alarm is of
  - action: tts.speak
    metadata: {}
    data:
      cache: true
      media_player_entity_id: media_player.kitchen
      message: "{{ text_to_speak }}"
    target:
      entity_id: tts.home_assistant_cloud

I know I could get what I want using Jinja2, but I wanted to make a script with just the bare minimum of Jinja2.

I found out that variables are scoped, but shouldn’t there be a YAML statement to update a variable. Because variables are behaving a lot like a constant IMHO.

Can this be done in “pure” YAML, or should I just accept the fact that it only can be done with Jinja2?

sequence:
  - variables:
      text_to_speak: >
        Alarm is {{ iif(is_state('alarm_control_panel.location_hjemme', 'disarmed'), 'off', 'on') }}
  - action: tts.speak
    metadata: {}
    data:
      cache: true
      media_player_entity_id: media_player.kitchen
      message: "{{ text_to_speak }}"
    target:
      entity_id: tts.home_assistant_cloud

A script variable’s scope limits where it is defined (and undefined). If you define a variable inside of an if-then, the variable and its value exist only within the if-then. So although you thought you were changing the value of text_to_speak within the if-then, you were actually defining a new variable that only exists within the if-then.

Reference

Script - Scope of variables

Thanks,

I know and it is similair to the way I have implemented it now, but I wanted to know if I could skip the Jinja2 way and have it in YAML statements. So it is easier to read in the GUI

//Robert

No, scoping rules don’t allow that.

Remember, virtually all computed values in Home Assistant are achieved with Jinja2, not YAML. So if a script variable’s value must be computed, it’s done with Jinja2.