Use variable for entity_id in a numeric_state trigger based automation

Hello there,

Is it possible to use a variable for entity_id in the following script?

alias: Garder Tradfri connecté
fields:
  entite:
    name: Entité
    description: Sélectionner la lumière a garder connectée.
    required: true
    example: light.chambre_enfants
#    selector:
#      entity:
#        device_class: light # doesn't exists
sequence:
  - service: scene.create
    data:
      scene_id: before
      snapshot_entities: "{{ entite }}"
  - if:
      - condition: numeric_state
        entity_id: "{{ entite }}"
        attribute: brightness
        above: 1
    then:
      - service: light.turn_on
        data:
          brightness: |
            {{ (state_attr(entite,'brightness') | int) - 1 }}
        target:
          entity_id: |
            {{ entite }}
    else:
      - service: light.turn_on
        data:
          brightness: |
            {{ (state_attr(entite,'brightness') | int) + 1 }}
        target:
          entity_id: "{{ entite }}"
  - delay:
      hours: 0
      minutes: 0
      seconds: 0
      milliseconds: 100
  - service: scene.turn_on
    data:
      entity_id: scene.before
mode: parallel
max: 10

The failed validation part is

  - if:
      - condition: numeric_state
        entity_id: "{{ entite }}"
        attribute: brightness
        above: 1

as, according to HA, "{{ entite }}" is neither a valid entity ID nor a valid UUID

Everywhere else, the “{{ entite }}” is accepted but not there, why?

EDIT: As the script will be used by an automation for all my lights, I’d really like to pass the light entity as a parameter to the script like this:

service: script.turn_on
target:
  entity_id: script.garder_tradfri_connecte
data:
  variables:
    entite: light.chambre_enfants

You cannot use templates in most conditions… that is why there is a standalone Template condition.

  - if:
      - condition: template
        value_template: >
          {{ state_attr(entite, 'brightness') > 1 }}

God, I’m using template conditions all the time but I did not even think one second about using it this time. Thank you!

1 Like

If you are interested, you can reduce the script to this:

alias: Garder Tradfri connecté
fields:
  entite:
    name: Entité
    description: Sélectionner la lumière a garder connectée.
    required: true
    example: light.chambre_enfants
#    selector:
#      entity:
#        device_class: light # doesn't exists
sequence:
  - service: scene.create
    data:
      scene_id: before
      snapshot_entities: "{{ entite }}"
  - service: light.turn_on
    data:
      brightness: |
        {% set b = state_attr(entite, 'brightness') | int(0) %}
        {{ iif(b > 1, b - 1, b + 1) }}
    target:
      entity_id: "{{ entite }}"
  - delay:
      milliseconds: 100
  - service: scene.turn_on
    data:
      entity_id: scene.before
mode: parallel
max: 10
1 Like