ESPHome Tips and Tricks: Implementing Anchors and Aliases in ESPHome

by Pete
2 minutes read

In this article, we’ll walk you through a practical example of using YAML anchors and aliases in an ESPHome configuration. Let’s say you have multiple LED strips in different rooms, and you want to apply the same settings to all of them without duplicating the configuration.

Define the Anchor

Define an anchor for the LED strip configuration with the common settings you want to apply to all strips:

# Define an anchor for LED strip configuration
led_strip_common: &led_strip_config
  platform: esp8266_pwm
  pin: D1
  num_leds: 60
  name: "Common LED Strip"

User Aliases

Create aliases for each LED strip, referencing the anchor configuration using <<: *anchor_name:

light:
  - <<: *led_strip_config
    id: living_room_leds
    name: "Living Room LED Strip"
  - <<: *led_strip_config
    id: bedroom_leds
    name: "Bedroom LED Strip"
  - <<: *led_strip_config
    id: kitchen_leds
    name: "Kitchen LED Strip"

By using aliases, you avoid repeating the common configuration settings for each LED strip. Any changes made to the anchor configuration will automatically apply to all aliases, ensuring consistency.

Customize as Needed

While the common settings are shared, you can still customize individual LED strips by adding specific attributes:

light:
  - <<: *led_strip_config
    id: living_room_leds
    name: "Living Room LED Strip"
    effects:
      - addressable_rainbow:
          name: "Rainbow Effect"
  # ... (other LED strips)

Conclusion: Simplify and Streamline

YAML anchors and aliases provide a powerful way to simplify and streamline your ESPHome configurations. By defining anchors with common settings and using aliases to reference them, you reduce redundancy, ensure consistency, and enhance maintenance. In the next section, we’ll explore real-world examples where this technique shines across various components of your smart home setup.