Using variables in scripts

I’m trying to use a variable in a script, but the field I’m trying to use it for is an int, and that’s throwing an error

sequence:
  - alias: Set to Low - 2700K
    if:
      - condition: or
        conditions:
          - condition: time
            after: "21:00:00"
          - condition: sun
            before: sunrise
        alias: If between 9pm and sunrise
    then:
      - variables:
          color: 2700
  - action: light.turn_on
    metadata: {}
    data:
      brightness_pct: 33
      kelvin: "{{ color }}"
    target:
      entity_id: light.kitchen_overhead
description: ""

The error reads: Failed to perform the action script/kitchen_activate_low_lights_duplicate. expected int for dictionary value @ data[‘kelvin’]

I have tried {{color | int}} which did not work

hi there… you’ve got a couple issues there. the primary issue is that variables only exist in the scope in which it’s defined. so your color: 2700 only exists in the “then” block of your yaml.

second, is a logical issue. if your “if” condition is not met, then what do you want color to be? it’s not set here.

if this is part of an overall script and you’ve also got color set as a field (you cannot change a variable… ironic, eh?) then please post the overall script. you’re likely going to need to change your overall approach.

1 Like

well, that’s the whole script haha. I’m just getting started figuring this all out. So you’re saying that variables need to be declared at the root level and then set later?

no. variables need to be defined and set at the beginning of the scope in which they will be used.

look here for scope info:

for your case, if that’s your whole script, then try something like this:

sequence:
  - alias: Set to Low - 2700K
  - action: light.turn_on
    data:
      brightness_pct: 33
      kelvin: >
        {% if as_datetime(state_attr('sun.sun', 'next_rising')).time() > now().time() or
          now() > today_at('21:00') %} 
          2700
        {% else %}
          3500
        {% endif %}
    target:
      entity_id: light.kitchen_overhead

note that i arbitrarily chose 3500 in the “else” case. you had no value set if it wasn’t between sunrise and 21:00. so replace that with whatever temperature you actually want.