diff --git a/homeassistant/helpers/config_validation.py b/homeassistant/helpers/config_validation.py index 7f2f1550cfe..9b56bb06865 100644 --- a/homeassistant/helpers/config_validation.py +++ b/homeassistant/helpers/config_validation.py @@ -916,7 +916,7 @@ SERVICE_SCHEMA = vol.All( vol.Optional("data"): vol.All(dict, template_complex), vol.Optional("data_template"): vol.All(dict, template_complex), vol.Optional(CONF_ENTITY_ID): comp_entity_ids, - vol.Optional(CONF_TARGET): ENTITY_SERVICE_FIELDS, + vol.Optional(CONF_TARGET): vol.Any(ENTITY_SERVICE_FIELDS, dynamic_template), } ), has_at_least_one_key(CONF_SERVICE, CONF_SERVICE_TEMPLATE), diff --git a/homeassistant/helpers/service.py b/homeassistant/helpers/service.py index 01992d43221..4e484c6aaab 100644 --- a/homeassistant/helpers/service.py +++ b/homeassistant/helpers/service.py @@ -204,10 +204,15 @@ def async_prepare_call_from_config( target = {} if CONF_TARGET in config: - conf = config.get(CONF_TARGET) + conf = config[CONF_TARGET] try: - template.attach(hass, conf) - target.update(template.render_complex(conf, variables)) + if isinstance(conf, template.Template): + conf.hass = hass + target.update(conf.async_render(variables)) + else: + template.attach(hass, conf) + target.update(template.render_complex(conf, variables)) + if CONF_ENTITY_ID in target: target[CONF_ENTITY_ID] = cv.comp_entity_ids(target[CONF_ENTITY_ID]) except TemplateError as ex: diff --git a/tests/helpers/test_service.py b/tests/helpers/test_service.py index d168c8b9cfc..7538c0f6f2c 100644 --- a/tests/helpers/test_service.py +++ b/tests/helpers/test_service.py @@ -213,6 +213,30 @@ class TestServiceHelpers(unittest.TestCase): "entity_id": ["light.static", "light.dynamic"], } + config = { + "service": "{{ 'test_domain.test_service' }}", + "target": "{{ var_target }}", + } + + service.call_from_config( + self.hass, + config, + variables={ + "var_target": { + "entity_id": "light.static", + "area_id": ["area-42", "area-51"], + }, + }, + ) + + service.call_from_config(self.hass, config) + self.hass.block_till_done() + + assert dict(self.calls[2].data) == { + "area_id": ["area-42", "area-51"], + "entity_id": ["light.static"], + } + def test_service_template_service_call(self): """Test legacy service_template call with templating.""" config = {