Skip to content

Misc tricks

Thomas Lovén edited this page Apr 14, 2019 · 7 revisions

YAML

I wrote a short description of how YAML works aimed at people who normally don't program. Some texts here will repeat some of the things in that description.

Node anchors

YAML node anchors is a simple way to reuse code in Home Assistant configuration files. Basically, you store the value of a key in an anchor while defining it:

# When you write:
key: &anchor value

# It will be interpreted as:
key: value

And then you can reuse it as many times as you want:

# When you write:
another_key: *anchor
yet_another_key: *anchor

# It will be interpreted as:
another_key: value
yet_another_key: value

anchor should be a single word, but may contain underscores.

value can be any valid YAML structure, strings, numbers, sequences or mappings.

Merge key <<:

The merge key can be used in yaml to merge a mapping into another:

# When you write:
key1: value1
key2: value2
<<:
  key3: value3
  key4: value4

# It will be interpreted as:
key1: value1
key2: value2
key3: value3
key4: value4

This is very useful in combination with node anchors:

# When you write:
- key1: value1
  <<: &common_things
    key2: value2
    key3: value3

- key1: valueA
  <<: *common_things


# It will be interpreted as:
- key1: value1
  key2: value2
  key3: value3
- key1: valueA
  key2: value2
  key3: value3

Node anchors in Home Assistant

Package attribute

Probably the most common usage of node anchors in Home Assistant is in packages. People like to add a configuration section to their packages which contain something like:

homeassistant:
  customize:
    package.node_anchors:
      common: &common
        package: "my package"

    sensor.my_sensor:
      <<: *common

This will add the attribute package with the value "my package" to every entity where it's been specified. The point of this is that if you open up the more-info dialog of the entity, or find it in the dev-states list, you can easily see where it's definition can be found.

Note that the package.node_anchors "entity" is just a dummy to have somewhere to define the node anchor. It could just as well be defined in the first real entity.

Value reuse

Another good use for node anchors is as a variable for any repeated value. In my coffee maker control package, I define a node anchor &cfe_switch which contains the entity id of the coffee maker outlet switch. I then use *cfe_switch in several automations to minimize the risk of me mistyping the entity.

Translations / user customization

If you design a very good package, you may want to distribute it to other users. It might then be a good idea to put a number of definitions near the top of the code, in a customize: section, for example, with values the user may want to customize. This might be things like output messages, time offsets, entity ids etc.