Scripts: how to templating both data and service?

Hi everybody.
Concerning Scripts:
In a Action is there a way to generate the service to be called using a template, and test the service generated in the data template in order to apply logic the the entity_id tp be gnerated?
i.e.:

an Action like this:

alias: 'Lights: Simulation Script'
  - service: >
      {% set operation = ['homeassistant.turn_on', 'homeassistant.turn_off' ] | random %}   
      {{ operation }}
    data:
      entity_id: >
        {% if operation == 'homeassistant.turn_on'  %}
          {{ expand('group.lights_simulation') | selectattr('state', 'eq', 'off') | map(attribute='entity_id') | list | random }}
        {% elif operation == 'homeassistant.turn_off'  %}
          {{ expand('group.lights_simulation') | selectattr('state', 'eq', 'on') | map(attribute='entity_id') | list | random }}
        {% else %}
          should never use this...
        {% endif %}

it seems that in data template the variable ‘operation’ in not accesible, making the script choose the final else clause.

thank you!
Daniele

Correct; a Jinja2 variable defined within one option (like service) is defined exclusively within that option. It’s undefined anywhere else.

Define operation as a script variable and then it can be referenced in the service and entity_id options.

alias: 'Lights: Simulation Script'
  - variables:
      operation: "{{ ['homeassistant.turn_on', 'homeassistant.turn_off' ] | random }}"
  - service: '{{ operation }}'
    target:
      entity_id: >
        {% if operation == 'homeassistant.turn_on'  %}
          {{ expand('group.lights_simulation') | selectattr('state', 'eq', 'off') | map(attribute='entity_id') | list | random }}
        {% elif operation == 'homeassistant.turn_off'  %}
          {{ expand('group.lights_simulation') | selectattr('state', 'eq', 'on') | map(attribute='entity_id') | list | random }}
        {% else %}
          should never use this...
        {% endif %}

Here’s another way to do the same thing:

alias: 'Lights: Simulation Script'
  - variables:
      operation: "{{ ['on', 'off' ] | random }}"
  - service: 'homeassistant.turn_{{ operation }}'
    target:
      entity_id: >
        {{ expand('group.lights_simulation') | selectattr('state', 'eq', iif(operation == 'on', 'off', 'on')) | map(attribute='entity_id') | list | random }}

Really thank you, really kind @123
Just another issue… in case the script should be a repeat sequence unitl …, how to make the ‘operation’ variable be regenerated using the random choose?
Is it possible in any way ?

You can define a script variable inside the repeat. If you do that then the variable will only be defined inside the repeat and not outside of it. For more information, refer to: Scope of variables

Really Thank you !!!

1 Like