Use sensor state in automation topic?

Can you set the action topic with a sensor state? Like the below “topic: {{states.sensor.missedannouncement.states}}”? I have tried many different ways and my config gives me an error. I am attempting to save tts notifications when we are not home.

  - alias: "JDTest"
    initial_state: True
    trigger:
      platform: state
      entity_id: switch.JDTest
      to: 'on'
    action:
      - service: mqtt.publish
        data:
          topic: {{states.sensor.missedannouncement.states}}
          payload: 'This is a TEST'

and my sensor

- platform: template
  sensors:
    missedannouncement:
      friendly_name: "MissedAnnouncement"
      value_template: >
        {% if is_state("sensor.missedannouncement1", "NULL") -%}
          home/missed/announcement1
        {% elif is_state("sensor.missedannouncement2", "NULL") %}
          home/missed/announcement2
        {% elif is_state("sensor.missedannouncement3", "NULL") %}
          home/missed/announcement3
        {% endif %}  

my error

Error loading /config/configuration.yaml: invalid key: "OrderedDict([('states.sensor.missedannouncement.states', None)])"
  in "/config/automations/automation.yaml", line 255, column 0

Two things:

  1. Whenever using a template like this you must use data_template and/or service_template in your action (based on where the template is being used). See more in the docs.

  2. I don’t think you should have the plural “states” at the end but rather the singular.
    states.sensor.missedannouncement.state

Try these and see if they help!

I changed it to data_template and fixed the state but still get an error

      - service: mqtt.publish
        data_template:
          topic: {{states.sensor.missedannouncement.state}}
          payload: 'This is a TEST'

error

Error loading /config/configuration.yaml: invalid key: "OrderedDict([('states.sensor.missedannouncement.state', None)])"
  in "/config/automations/automation.yaml", line 255, column 0

checking my sensor state in the “Templates” front end I get a value
I enter {{states.sensor.missedannouncement.state}}
and to the right it shows “home/missed/announcement1”.

Now I got it!!!
I just put quotes around the topic (I tied that before but needed the data_template)

      - service: mqtt.publish
        data_template:
          topic: '{{states.sensor.missedannouncement.state}}'
          payload: 'This is a TEST'
2 Likes

Ah, yep sorry I missed that one from your OP. Item #3 in the Important Template Rules :slight_smile:

Glad you got it working!