Set variables before calling service in script?

I’m trying to swap the state of two lights randomly. When I call the script, nothing happens. Also, where should I be putting code to set variables before I call the services with that variables? this code checks out as valid, but doesn’t appear to do anything.

    - service: light.turn_on
        entity_id: >
            {% set sl_light_1_name =  ( ['kitchen_1','kitchen_2','kitchen_3','kitchen_4','kitchen_5','kitchen_6','livingroom_lamp']|random )  %}
            {% set sl_light_1_rgb = (  states.light[sl_light_1_name].attributes.rgb_color ) %}
            {% set sl_light_1_brightness = (  states.light[sl_light_1_name].attributes.brightness ) %}
            {% set sl_light_2_name =  ( ['kitchen_1','kitchen_2','kitchen_3','kitchen_4','kitchen_5','kitchen_6','livingroom_lamp']|random )  %}
            {% set sl_light_2_rgb = (  states.light[sl_light_2_name].attributes.rgb_color ) %}
            {% set sl_light_2_brightness = (  states.light[sl_light_2_name].attributes.brightness ) %}
        brightness: '{{ sl_light_2_brightness }}'
        rgb_color: '{{ sl_light_2_rgb }}'
        transition: 5
    - service: light.turn_on
        entity_id: >
        brightness: '{{ sl_light_1_brightness }}'
        rgb_color: '{{ sl_light_1_rgb }}'
        transition: 5

you need to understand that all your variables are local not only within one template (so forget about using sl_light_2_brightness in brightness, for example), it’s local within a block i.e directly within a for loop you cannot modify a variable that was defined outside the loop in the same template (but there is namespace workaround. more about it in the docs

the easiest way of debugging things like yours it to test each template separately to see if they work as planned.

as to your goal I personally think a small python_script can do the job if you’re familiar with python :wink:

Totally agree with @AhmadK here. Also, the scope of variables in a template are limited to the template itself. In your script you actually have six separate templates: one for each entity_id, brightness & rgb_color parameter. Also, rgb_color requires a list, and a template can only output a string.

So basically, you could do this in a “regular” script, but it would be really hard. But as @AhmadK suggests, it would be really simple in a python_script. Let us know if you’d like help with that.