Get a random entity from domain

Hi all,

I was wondering if it was possible to get a random entity from a certain domain.

Basically I have a few entities like so:

  • variable.boardgame_04_14_98_b2_84_2a_81
  • variable.boardgame_04_15_98_b2_84_2a_81
  • variable.boardgame_04_fc_98_b2_84_2a_80
  • variable.boardgame_53_22_20_1c_10_00_01

What I want to do is run a script to get one of these random variables, and then all its attributes. I’ve got no problems doing the script side of things, but can’t get the random bit,

I’ve tried

{{ states.variable | random }}

But that just gives me None, so not helpful. Also toyed with using a random number, since I can get the count of how many of these variable entities there are, and using that to set the range, unfortunately I cannot get the counter to work.

{% set random = range(1, (states.variable | count)) | random %}

{% set count = 1 %}
{%- for state in states.variable -%}
{%- if count == random -%}
  {{"\n"}}- {{state.entity_id}}
{% set count = 1 + count %}
{%- endif -%}
{%- endfor -%}

Hoping someone can set me on the right track to do this.

Thanks!

I’m not sure how to get this into your example, but this might help. Try these lines out in your developer tools → Templates

{% set list = expand(states.sensor) %}
{% set random = range(1, (list | count)) | random %}
{{ list[random].state }}
{{ list[random].name }}
{{ states.variable | map(attribute='entity_id') | list | random }}

Perfect, thanks @123

1 Like