Skip to content

Instantly share code, notes, and snippets.

@Integralist
Last active February 15, 2025 06:40
Show Gist options
  • Save Integralist/dcabda9b762ad23781af76fd1971e0f7 to your computer and use it in GitHub Desktop.
Save Integralist/dcabda9b762ad23781af76fd1971e0f7 to your computer and use it in GitHub Desktop.
[YAML anchors] #yaml #anchors

If you've not used YAML before you might be wondering what &<name> means.

What this will do is create an 'anchor'.

Anchors allow you to inject the associated block of data any where else within your YAML configuration file.

This allows you to avoid duplicating those particular settings.

The way to do that injection is to 'dereference' the anchor with an asterisk.

e.g. log_format: *log_format or inject it inside another block using a double chevron (e.g. <<: *upstreams).

I recommend having a read through the YAML documentation to get a better feel for how these YAML features work.

https://onlineyamltools.com/convert-yaml-to-json is a good site to test this out on as it can convert your YAML to JSON and you can see if it works how you expect.

Below demonstrates a problem with this feature, which is it works best with objects, not arrays...

In the below example I want to inject the same args: array into the array entry that follows...

- containers:
    - args: &args
        - -cfg
        - /vault/secrets/datasync.conf
        - -backup
      name: datasync
- containers:
    - args: *args
      name: datasync

This products:

[
  {
    "containers": [
      {
        "args": [
          "-cfg",
          "/vault/secrets/datasync.conf",
          "-backup"
        ],
        "name": "datasync"
      }
    ]
  },
  {
    "containers": [
      {
        "args": [
          "-cfg",
          "/vault/secrets/datasync.conf",
          "-backup"
        ],
        "name": "datasync"
      }
    ]
  }
]

This is fine. But what if I want to extend args in the second case to have an extra argument?

The problem with that is I can't extend the args list. This is the problem with the array data type. When working with an object you can use <<: *whatever and then extend an object's key/value but not with an array :-(

Where as if it was an object instead of an array:

- containers:
    - args: &args
        foo: bar
      name: datasync
- containers:
    - args: 
        <<: *args
        beep: boop
      name: datasync

Then this would work fine...

[
  {
    "containers": [
      {
        "args": {
          "foo": "bar"
        },
        "name": "datasync"
      }
    ]
  },
  {
    "containers": [
      {
        "args": {
          "foo": "bar",
          "beep": "boop"
        },
        "name": "datasync"
      }
    ]
  }
]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment