Issue with Template Variables in Script

Hello,

I am attempting to create a script that will play a media file in whatever room I happen to be in. However, when I execute the script, I receive an error stating:

Template rendered invalid entity IDs:

When I manually plug in one of the media players, it works fine. Any help would be appreciated. Below is the code:

Script:

service: media_player.play_media
target:
  entity_id: "{{ media_player }}"

Automation calling script

service: script.media_based_on_presence
target:
  entity_id: |
    {% if is_state('binary_sensor.bedroom_aqara_fp2_presence_sensor_1', 'on') %}
      media_player.bedroom_display
    {% elif is_state('sensor.andrews_watch', 'office') %}
      media_player.office
    {% elif is_state('sensor.andrews_watch', 'theater_room') %}
      media_player.theater_room
    {% elif is_state('sensor.andrews_watch', 'living_room') %}
      media_player.living_room
    {% else %}
      none
    {% endif %}
data:
  media_content_id: media-source://media_source/local/Kraken.mp3
  media_content_type: audio/mpeg
metadata:
  title: Kraken.mp3
  thumbnail: null
  media_class: music
  children_media_class: null
  navigateIds:
    - {}
    - media_content_type: app
      media_content_id: media-source://media_source

I’m not sure what the script is supposed to be for. If you replaced service.media_based_on_presence with media_player.play_media in your automation, it seems like this would work.

If you do want to use a script and pass variables to it, though, you would need to use fields in the script.

You’re absolutely right! I swear I tried that, but must have had something else wrong with it elsewhere. Thank you.

If one of the suggestions listed solves your problem, please consider clicking the solution button to close the thread.