Automation with service entity if/else

I am trying to add an if/else condition to the action block of an automation. The intended function is to perform switch.turn_on service but the target entity_id will change depending on the state of a sensor.

  automations.yaml

- id: '1614154379154'
  alias: 'Switch: Bedroom'
  description: ''
  trigger:
  - device_id: fb42aead6bc46d9a778cfc0079312ada
    domain: hue
    platform: device
    type: remote_button_short_release
    subtype: turn_on
  - device_id: fb42aead6bc46d9a778cfc0079312ada
    domain: hue
    platform: device
    type: remote_button_long_release
    subtype: turn_on
  condition: []
  action:
  - service: switch.turn_on
    target:
      entity_id: >
        {% if is_state('sensor.lighting_mode', 'CT') %} 
          switch.circadian_lighting_bedroom_ct
        {% else %} 
          switch.circadian_lighting_bedroom_xy
        {% endif %}
  mode: single

When using the configuration validator, I get the error

Invalid config for [automation]: not a valid value for dictionary value @ data['action'][0]['target']['entity_id']. Got None.

Does anyone have a clue what I might be doing wrong? My configuration looks like it should be valid based on the “Use Templates to Determine The Attributes” example in the documentation.

Help is appreciated! Thanks!

Try this as your action.

action:
  - service: switch.turn_on
    data:
      entity_id: >-
        {% if is_state('sensor.lighting_mode', 'CT') %}
        switch.circadian_lighting_bedroom_ct {% else %}
        switch.circadian_lighting_bedroom_xy {% endif %}
1 Like

Thank you for the response!

It seems like changing it from

action: 
  - service: switch.turn_on
    target:
      entity_id:

to

action: 
  - service: switch.turn_on
    data:
      entity_id:

fixed the error. Thanks again!

1 Like

FYI template support has been added for target: in v2021.3 (currently in beta testing).

1 Like