Setting variables in an 'if' statement

I’d like to turn on a light, and set its brightness based on the time. It seems like the cleanest way to do this would be with an ‘if’ statement like this:

alias: Second Floor Hallway Lights On
description: ""
trigger:
  - entity_id: binary_sensor.z_wave_pir_motion_sensor_any_2
    from: "off"
    platform: state
    to: "on"
condition: []
action:
  - variables:
      brightness: 77
  - if:
      - condition: time
        after: "22:00:00"
        before: "07:00:00"
    then:
      - variables:
          brightness: 30
    else:
      - variables:
          brightness: 100
  - service: light.turn_on
    data:
      brightness_pct: "{{ brightness }}"
    target:
      entity_id: light.inovelli_vzm31_sn_light

This will always set the brightness to ‘77’ because the variable definitions in the ‘if’ statement are local to that scope. Is there some way around this, resetting those larger-scope variables to a new value?

Get rid of the If/Then action and use an If statement in Jinja:

action:
  - variables:
      brightness: |
        {% if 22 > now().hour >= 7 %} 100
        {% else %} 30
        {% endif %}
  - service: light.turn_on
    data:
      brightness_pct: "{{ brightness }}"
    target:
      entity_id: light.inovelli_vzm31_sn_light
2 Likes

Just my extra 2 cents, but reading your code, and intent, I’m thinking you might have a higher problem than that.
You seem to want to “default” to 77, but your if condition would never allow that, it would always be either 30 or 100.
Which basically, could be written like this, without variables/template at all:

if:
  - condition: time
    after: "22:00:00"
    before: "07:00:00"
then:
  - service: light.turn_on
    target:
      entity_id: light.inovelli_vzm31_sn_light
    data:
      brightness_pct: 30
else:
  - service: light.turn_on
    target:
      entity_id: light.inovelli_vzm31_sn_light
    data:
      brightness_pct: 100

In case you actually had a scenario in mind that was to use the 77 value, you might want to revise your approach.