118

I want to reuse a hash in YAML:

Defaults: &defaults
  Company: Foo
  Item: 123

Computer: *defaults
  Price: 3000

However, this generates an error.

Is the only way to anchor each field value separately like this?

Defaults:
  Company: &company Foo
  Item: &item 123

Computer:
  Company: *company
  Item: *item
  Price: 3000
Matt Ball
  • 354,903
  • 100
  • 647
  • 710
ajsie
  • 77,632
  • 106
  • 276
  • 381

2 Answers2

353

Try reusing a full group by importing it:

Defaults: &defaults
  Company: foo
  Item: 123

Computer:
  <<: *defaults
  Price: 3000

Documentation: http://yaml.org/type/merge.html

Yves M.
  • 29,855
  • 23
  • 108
  • 144
Gabriel Oliveira
  • 3,541
  • 2
  • 12
  • 3
  • 23
    I always forget this syntax, it's kind of complicated. – sites Mar 03 '14 at 23:56
  • Is there documentation you can link to for this? I'd like to see if there is a similar feature for lists. – waterproof Dec 19 '15 at 00:36
  • 18
    For a DSL that is supposedly easy to read and understand, this syntax is notoriously complicated and unreadable. Then you'd think reading the docs/specs would clear it out, but no, you'd end up with a deep hole in your head from all the intense scratching while trying to decipher the specification. – Christian Dec 31 '17 at 22:14
  • I'd go as far as to argue this would be a place were code duplication is better - and I hate duplication in general. – Christian Dec 31 '17 at 22:17
  • 8
    This answer shows exactly how it works. And using two characters is *not* complicated! An `&` with a name to mark a section and a `*` with the same name to recall it. That's very simple. You mark a line with `&name`, and everything nested below that line is then reused with `*name`. Thanks for this post, it's quite helpful, despite these comments saying it's complicated... – daevski Aug 27 '20 at 03:04
41
# sequencer protocols for Laser eye surgery
---
- step:  &id001                  # defines anchor label &id001
    instrument:      Lasik 2000
    pulseEnergy:     5.4
    pulseDuration:   12
    repetition:      1000
    spotSize:        1mm

- step: &id002
    instrument:      Lasik 2000
    pulseEnergy:     5.0
    pulseDuration:   10
    repetition:      500
    spotSize:        2mm

- step: *id001                   # refers to the first step (with anchor &id001)
- step: *id002                   # refers to the second step
- step: *id001
- step: *id002

sample from wikipedia

jcollado
  • 39,419
  • 8
  • 102
  • 133
zed_0xff
  • 32,417
  • 7
  • 53
  • 72
  • 5
    The answer by Gabriel is a better way to solve this problem. You can reuse a whole group, then override the fields (even deep fields) that you want to be different. – Luca Spiller Feb 08 '16 at 10:47