Use For in automation

Hello everybody
I’m trying to write an automation to switch on the air conditioners dynamically based on presence in the rooms and how much my solar system produces.
the second part works already give time, now I wanted to add the part of the rooms.
I am trying to use a for loop inside an entry but I am constantly getting errors.
the problem appears on the “set”.
you can use a for loop inside an automation.
if you have any advice?

this is the code

  alias: Autoaccensione condizionatori NEW
  description: ''
  trigger:
  - platform: numeric_state
    entity_id: sensor.grind_power_now
    below: '100'
    for: 00:20:00
  - platform: time_pattern
    minutes: /20
  condition:
  - condition: numeric_state
    entity_id: sensor.produzione_istantanea_fotovoltaico
    above: '500'
  - condition: time
    after: '10:30'
  action:
    {% set sorted_list = group.usostanze | expand | sort(attribute='state', reverse=true)%}
    {for state in sorted_list %}
    {% set nome = state.entity_id.split("uso_")[1] %}
    {% set valoremax = "sensor.max_consumoclima"+nome %}
    {% set valoretemp = "sensor."+nome+"_room_temperature" %}
    {% set valoreentity = "climate."+nome %}	
  - condition: template
    value_template: {{((states.sensor.produzione_istantanea_fotovoltaico.state)|float - (states.sensor.assorbimento_istantaneo_casa.state)|float - (states(valoremax))|float) >= (states.input_number.delta_fotovoltaico.state) |float }}
  - condition: state
    entity_id: {{valoreentity}}
    state: 'off'
    for: '00:15:00'
  - condition: template
    value_template: {{((states(valoretemp)) > states.input_number.temperatura_interna_max.state) or ((states(valoretemp)) < states.input_number.temperatura_interna_min.state) }}
  - service: climate.turn_on
    target:
      entity_id: {{valoreentity}}
    data: {}
  - condition: state
    entity_id: automation.spegnimentoautomaticocondizionatori
    state: 'off'
  - service: automation.turn_on
    target:
      entity_id: automation.spegnimentoautomaticocondizionatori
    data: {}
  - service: tts.google_translate_say
    data:
      entity_id: media_player.gruppo_casa
      message: avviato servizio di climatizzazione
{%- endfor -%}
  mode: single

At least two things.
The {% endfor %} at the end … should not be there as part of template writing
The current way of writing for is:

   for:
      hours: 0
      minutes: 20
      seconds: 0

I suggest you use the automations GUI to avoid discrepancies as much as possible

EDIT: adding the actual errors also helps, very difficult in guessing what you see

You will need to redesign your automation because it’s based on a fundamental error. You have put YAML options within a template and that’s invalid. In addition, a Jinja2 variable defined within the template of one YAML option is undefined elsewhere (it cannot be referenced in the template of another YAML option).