Changing a variable with an if statement within a Script

Hi all,

I’m trying to use an if statement in a scipt to change the media player based on what is currently palying.

The media player (media_player.sonos_1) is passed on to the script as a variable via an automation that is triggering the script. If the current source of media_player.sonos_1 is “AirPlay” I want to switch to media_player.sonos_2 so that media_player.sonos_1 is not interrupted.

This is my code:

#### Sonos Play File
sonos_play_file:
  alias: "Sonos Play File Script"
  mode: queued
  sequence:
  - if:
      - condition: state
        entity_id: media_player.sonos_1
        attribute: source
        state: "AirPlay"
    then:
      - variables:
          sonos_entity: media_player.sonos_2
...

The if statement works correct based on the source of media_player.sonos_1. However, the variable is not changed.

If I just start with changing the variable without the if startement:

sonos_play_file:
  alias: "Sonos Play File Script"
  mode: queued
  sequence:
  - variables:
      sonos_entity: media_player.sonos_2

the variable ist changed. Is there anything wrong with my code? Do I need to use another syntax to change variables within the if statement?

Thanks in advance!

This is likely a scope issue, but you haven’t shown where you are using the sonos_entity variable, so it’s hard to say for sure.

The way you have shown it, the variable will have the value media_player.sonos_2 only within the then. If you need it to have a wider scope you will need to use templates:

#### Sonos Play File
sonos_play_file:
  alias: "Sonos Play File Script"
  mode: queued
  variables:
    sonos_entity: "{{ 'media_player.sonos_2' if is_state_attr('media_player.sonos_1', 'source', 'AirPlay') else 'media_player.sonos_1' }}"
  sequence:
  
...

EDIT: Added missing attribute reference

1 Like

Perfect. Thanks a lot. I had to change if is_state to if is_state_attr and add the attribute name, but than it solved my problem already.

sonos_play_file:
  alias: "Sonos Play File Script"
  mode: queued
  variables:
    sonos_entity: "{{ 'media_player.sonos_2' is_state_attr('media_player.sonos_1', 'source', 'AirPlay') else 'media_player.sonos_1' }}"
  sequence:
  
...

One more question: sonos_entity might contain a string with more than one sonos entities. Is it possible to leave it as it was if the source of media_player.sonos_1 is not AirPlay?

  variables:
    sonos_entity: |
     {{ 'media_player.sonos_2' if is_state_attr('media_player.sonos_1', 'source', 'AirPlay') 
     else sonos_entity }} 
  sequence:

Though, you may want to add a default or further conditions to the template is there’s a chance that sonos_entity might not be provided and sonos_1’s source isn’t AirPlay…