Access variable by string

Is it possible to access/use a variable in an automation by using data from mqtt payload?

This is an example:

alias: someName
description: ''
trigger:
  - platform: mqtt
    topic: sometopic/topic
condition: []
action:
  - service: homeassistant.toggle
    data_template:
      entity_id: '{{ trigger.payload_json.id }}'
mode: single
variables:
  B1: switch.big_light

Here the value of trigger.payload_json.id would be 'B1', is it possible to use it to somehow call defined variable B1 so it can act as an appropriate entity_id ?

The way we can do that in some programming langs, like python for example:

someVar = 'myVariable'

myVariable = 'Hello'

print(eval(someVar))  # Example 1, prints "Hello"

print(globals()[someVar])  # Example 2, prints "Hello"

#getattr in objects .....

How many different id’s do you have to be converted to entity_ids?

Can you list the id’s and their corresponding entity_ids?

If it’s only a couple of ids then an if/else would be appropriate, if more then mapping would be more appropriate.

Hi,

It’s not too many, more than 20, i wouldn’t like to make spaghetti with if/else, maintenance would be bad. I already made it work by sending the actual entity_id instead of an ID, however i would like to explore option using variables in this way, it would make cleaner code than if/else, and the other reason is to keep information logic on the HA side, instead of sending entity_id from external source, so i was just wondering if it is possible

Yeah don’t use if/else for that. Use mapping. See this example: