YTT overlays: modify arrays using data from that arrays

607 Views Asked by At

This question is about YTT. Is it possible to modify YAML list of items using the data from that items via overlays?

For example we have a template:

---
vlans:
- vlan-id: 10
- vlan-id: 20
- vlan-id: 30
some_other_configuration: #! some other config here

And using overlays we need to transform the template above into this:

---
vlans:
- vlan-id: 10
  vlan-name: vlan10
- vlan-id: 20
  vlan-name: vlan20
- vlan-id: 30
  vlan-name: vlan30
some_other_configuration: #! some other config here
1

There are 1 best solutions below

0
JTigger On

Yes. One can use an overlay within an overlay.

#@ load("@ytt:overlay", "overlay")

#@ def with_name(vlan):
#@overlay/match missing_ok=True
vlan-name: #@ "vlan{}".format(vlan["vlan-id"])
#@ end

#@overlay/match by=overlay.all
---
vlans:
#@overlay/match by=lambda idx, left, right: "vlan-id" in left, expects="1+"
#@overlay/replace via=lambda left, right: overlay.apply(left, with_name(left))
- 

which can be read:

  • for all documents,
  • in the vlans: map item...
    • for every array item it contains that has a map that includes the key "vland-id"...
      • replace the map with one that's been overlay'ed with the vlan name

https://carvel.dev/ytt/#gist:https://gist.github.com/pivotaljohn/33cbc52e808422e68c5ec1dc2ca38354

See also: