How to test whether an entity exists?

Hello fellow home automators,

Is there a way to test for the existence of a named entity (in particular a scene)?

The high level use case is I’m trying to use a template to construct a scene entity id using a input_select containing a theme name. If the computed scene exists, I want to activate the scene otherwise i just want to silently ignore.

The reason for doing this is that for each theme only some areas of the house will have a scene that should be activated - I.e. the exterior lights may be activated in some scenes but not others. The lighting in different areas of the house are activated at different times so I can’t just build one scene per theme.

Try it with is defined.


Looks like this only works with the states.entity_id.state notation.

6 Likes

Brilliant. Thanks - works like a charm. I now know what I’ll be doing over the festive holiday.

If you have an entity_id stored in a variable, you can also perform the check by doing the following:

{% set check_entity_id = 'schene.whatever' %}
{{ states[check_entity_id] != None}}
1 Like


seems to work fine now, either notation… The latter is best.

Try an entity that doesn’t exist, that’s what this topic is about.

FWIW, if switch.foo doesn’t exist, both of these templates will report False.

{{ states.switch.foo.state is defined }}

{{ states('switch.foo') != 'unknown' }}

In contrast, the following template will report True even if the entity doesn’t exist (because the states() function returns a value of unknown).

{{ states('switch.foo') is defined }}

Revisting this topic it looks like the HA logic has changed. The marked solution does not work anymore. The only working solution in my tests, which reliable states if an entity (a scene) exists is using the following template:

{{ states.scene.my_dynamically_created_scene != None }}

Another option…

1 Like