Prevent duplicate code in YAML

Hi all,
I have the following code, which I would like to compress to less lines (this only is 1 switch, and I want 30). Part two is what I would like to do. That is valid YAML, but all falls under mqtt. And basic_sensor doesnt pass the Home Assistant validator.
Are there other ways to use this alias concept? Or can i disable the validator for a certain block (like in typescripts. // @ts-ignore)

sensor:
  - unique_id: FB_DO_SW_001
    name: "FB_DI_PB_001"
    state_topic: "WAGO-PFC200/Out/DigitalInputs/Pushbuttons/FB_DI_PB_001"
    expire_after: 3
    qos: 2
    availability_topic: "Devices/WAGO-PFC200/availability"
    payload_available: "online"
    payload_not_available: "offline"
    device: *device

  - unique_id: FB_DI_PB_001_P_LONG
    name: "FB_DI_PB_001_P_LONG"
    state_topic: "WAGO-PFC200/Out/DigitalInputs/Pushbuttons/FB_DI_PB_001/P_LONG"
    qos: 2
    availability_topic: "Devices/WAGO-PFC200/availability"
    payload_available: "online"
    payload_not_available: "offline"
    device: *device
basic_sensor:  &basic_sensor
  qos: 2
  availability_topic: "Devices/WAGO-PFC200/availability"
  payload_available: "online"
  payload_not_available: "offline"
  device: *device

sensor:

  - <<: *basic_sensor
    unique_id: FB_DO_SW_001
    name: "FB_DI_PB_001"
    state_topic: "WAGO-PFC200/Out/DigitalInputs/Pushbuttons/FB_DI_PB_001"
    expire_after: 3

  - <<: *basic_sensor
    unique_id: FB_DI_PB_001_P_LONG
    name: "FB_DI_PB_001_P_LONG"
    state_topic: "WAGO-PFC200/Out/DigitalInputs/Pushbuttons/FB_DI_PB_001/P_LONG"

I vaguely remember there being a way to do this, but I can’t remember the syntax. You can try:

sensor:

  - unique_id: FB_DO_SW_001
    name: "FB_DI_PB_001"
    state_topic: "WAGO-PFC200/Out/DigitalInputs/Pushbuttons/FB_DI_PB_001"
    expire_after: 3
    <<: &basic_sensor
      qos: 2
      availability_topic: "Devices/WAGO-PFC200/availability"
      payload_available: "online"
      payload_not_available: "offline"
      device: *device

  - <<: *basic_sensor
    unique_id: FB_DI_PB_001_P_LONG
    name: "FB_DI_PB_001_P_LONG"
    state_topic: "WAGO-PFC200/Out/DigitalInputs/Pushbuttons/FB_DI_PB_001/P_LONG"
2 Likes

The syntax that @petro is using here is called “YAML Anchors”. Just in case you want to look up more information about it.

1 Like