[Request] Extend YAML objects with context objects

YAML has an object extension syntax using << as a special key whose value is another object from which to copy key-value pairs into the parent object. For example:

foo: &anchor
  K1: "One"
  K2: "Two"
  <<: *anchor
  K2: "I Changed"
  K3: "Three"

In this YAML, bar has 3 keys, the 2 in its body and K1 copied from foo.

While commonly used with references, it can be used with literal objects too:

  <<: { K1: "One", K2: "Two" }
  K2: "I Changed"
  K3: "Three"

In this YAML, bar has the same value it had in the first example.

I would like to use this functionality to define environment variables from a matrix, like this:

      - id: 1
      - id: 2
          GREETING: hello
  <<: ${{ matrix.example.env }}

I would expect this matrix to generate two runs, one with a default environment, and one with the default environment plus a variable GREETING with the value hello. That is, unlike the recommended pattern for defining environment variables from a matrix, I would like the variable GREETING to be undefined in the case that omits it, not defined but empty. If I try this technique today, however, I get the error “A mapping was not expected”.

1 Like

Note that the merge operator << was removed from the YAML spec in version 1.2. It’s only available in 1.1 AFAIK.

This has been discussed extensively here:

1 Like

IMHO, that’s less “discussion” and more a bunch of people either saying, “I want this, too”, or providing their workarounds. :sweat_smile:

Too bad about the operator being removed in 1.2.

1 Like
  • People providing their opinions, use cases and workarounds is a discussion.
  • There are replies from the GitHub staff.
  • Opening a new thread on exactly the same topic doesn’t help anyone.

There are more threads on this and similar DRY topics if you search the forum a bit (see an incomplete list here).

1 Like

I did search the forum “a bit” and found no related thread, not even the one you linked. Perhaps it is because I searched for “merge” and “extend” instead of “anchors”, because I don’t need anchors. I’m not asking for a Don’t Repeat Yourself feature, either, so why would I search for DRY? Even if I search now for “github actions yaml extend context”, only this thread shows up. Blame Discourse’s bad search.

1 Like

Researching this, it seems it was never actually part of the spec, but just commonly implemented in many YAML parsers.

The YAML spec isn’t quite clear on this, but I also got the notion of this being a common YAML 1.1 extension. It definitely isn’t part of the core spec document.


However, I found the following comment:

In YAML 1.3, loaders will be encouraged not to support merge keys by default. It will become an optional feature.

It sounds like some 1.2 implementations might support the merge operator. Not sure what “optional feature” will mean in practice.