Setting variables in 'choose'-blocks of automations

Tags: #<Tag:0x00007fc4044a0590> #<Tag:0x00007fc4044a03d8> #<Tag:0x00007fc4044a0270>

Hi,
I am cleaning up my code and try to combine multiple similar automations into one. For that, I want to use the new ‘Variables’ feature (v0.115).
The following…

automation:
  - id: test1
    trigger:
      #... some trigger
    variables: 
      messagetext: '--'
    action:
      - variables:
          messagetext: 'start'
      - service: notify.max
        data:
          title: 'Automation Test1'
          message: "{{ messagetext }}"

…works, I get a notification with text ‘start’.
But, if I put the setting of the variable inside a chooser block and use that variable later on:

automation:
  - id: test2
    trigger:
      #... some trigger
    variables: 
      messagetext: '--'
    action:
      - choose:
        - conditions:
          #do something Mondays
          - condition: time
            weekday:
              - mon
          sequence:
            - variables:
                messagetext: 'a Monday'
        default:
          #do something else 
          - variables:
              messagetext: 'another day'        
      - service: notify.max
        data:
          title: 'Automation Test2'
          message: "{{ messagetext }}"

…I get the notification message ‘–’.
In Jinja templates variables are always local or a namespace has to be set.
But how is that done here in automation actions?
In my understanding the defined variable should be accessible throughout the whole automation.

Thanks in advance for your input.
Max

1 Like

Did you ever get this working? I have the same issue

In brief, you can’t redefine the value of a variable like in the posted example.

The variable’s scope is constrained by where it’s defined in the automation. The assumption maxl67 made is that no matter where the variable is defined, it’s scope is always global (available everywhere within the ,action. However, that’s not how it works.

In the example, the variable messagetext is defined not just once but three times. The first time is outside of action and represents the one whose scope is global for the entire automation.

The second and third definitions are made within the conditions of a choose so their scope is constrained to the conditions.

Outside of conditions, like in the service call, the value of messagetext is determined by its first (global) definition.

1 Like

@Rob: no, I haven’t.
@Taras: Thanks for the good explanation.