Reusing "Chunk" of YAML

I’m trying to figure out the best way to handle some conditional logic in an automation and having a bit of trouble. I have a chunk of iOS companion app notification data that I’d like to define once and do some if then logic to determine exactly which service to call (i.e., if condition a notify just me, if condition b notify my SO, if condition C notify both). I’m trying to do this in the most efficient way possible but can’t quite get there.

What I tried was defining the reusable bit as a variable

variables:
  notification:
    data:
      title: "Buddy: {{ state_attr('calendar.buddy','message') }}"
      message: |
        It's time for {{ state_attr('calendar.buddy','message') }}

        {{ state_attr('calendar.buddy','description') }}
      data:
        push:
          interruption-level: time-sensitive
        tag: buddy-feeding
        url: /dash-buddy
        actions:
          - action: BUDDY_FED
            title: Mark as Fed

and then calling the notification service

service: notify.mobile_app_p
{{notification}}

however because that’s invalid YAML it fails to save (at least via the UI) and fails to actually work. Is there a way to accomplish this or should I just copy and paste this three times and stop overthinking it?

Maybe make it a script?

Have you tried this?

templates/notification_data.yaml

title: ...
message: ...
data:
  tag: ...
  ...
service: notify.mobile_app_p
data: !include templates/notification_data.yaml

Oh yeah! Good call, totally forgot about that level of abstraction. That did exactly what I wanted.

For anyone that finds this later here’s what I did

Script

alias: Buddy Calendar Notification
fields:
  service:
    name: Service to use
    required: true
sequence:
  - service: |
      {{service}}
    data:
      title: "Buddy: {{ state_attr('calendar.buddy','message') }}"
      message: |
        It's time for {{ state_attr('calendar.buddy','message') }}

        {{ state_attr('calendar.buddy','description') }}
      data:
        push:
          interruption-level: time-sensitive
        tag: buddy-feeding
        url: /dash-buddy
        actions:
          - action: BUDDY_FED
            title: Mark as Fed
mode: single
icon: mdi:account-voice

Call in Automation

service: script.buddy_calendar_notification
data:
  service: notify.mobile_app_p

That’s interesting, the script idea from @stevemann did what I wanted (and I was familiar with it) but I’ll have to play with includes like that.

1 Like