I recently saw that the go yaml lib has new version (V3)
with the nodes capabilities (which in my opinion is a killer feature :) ) which can helps a lots with modifying yamls without changing the structure of the file
But since it is fairly new (from last week ) I didn't find some helpful docs and example for the context which I need (add new object/node and to keep the file structure the same without removing the comments etc)
what I need is to manipulate yaml file
for example
lets say I’ve this yaml file
version: 1
type: verbose
kind : bfr
# my list of applications
applications:
- name: app1
kind: nodejs
path: app1
exec:
platforms: k8s
builder: test
Now I got an json object (e.g. with app2
) which I need to insert to the existing file
[
{
"comment: "Second app",
"name": "app2",
"kind": "golang",
"path": "app2",
"exec": {
"platforms": "dockerh",
"builder": "test"
}
}
]
and I need to add it to the yml file after the first application, (applications is array of application)
version: 1
type: verbose
kind : bfr
# my list of applications
applications:
# First app
- name: app1
kind: nodejs
path: app1
exec:
platforms: k8s
builder: test
# Second app
- name: app2
kind: golang
path: app2
exec:
platforms: dockerh
builder: test
is it possible to add from the yaml file the new json object ? also remove existing
I also found this blog https://blog.ubuntu.com/2019/04/05/api-v3-of-the-yaml-package-for-go-is-available
This is the types which represent the object
type VTS struct {
version string `yaml:"version"`
types string `yaml:"type"`
kind string `yaml:"kind,omitempty"`
apps Applications `yaml:"applications,omitempty"`
}
type Applications []struct {
Name string `yaml:"name,omitempty"`
Kind string `yaml:"kind,omitempty"`
Path string `yaml:"path,omitempty"`
Exec struct {
Platforms string `yaml:"platforms,omitempty"`
Builder string `yaml:"builder,omitempty"`
} `yaml:"exec,omitempty"`
}
update
after testing the solution which is provided by wiil7200
I found 2 issues
I use at the end write it to file
err = ioutil.WriteFile("output.yaml", b, 0644)
And the yaml output have 2 issue.
The array of the application is starting from the comments, it should start from the name
After the
name
entry thekind
property and all others after are not aligned to thename
any idea how to solve those issue ? regard the comments
issue, lets say I got it from other property
and not from the json (if it make it more simpler)
version: 1
type: verbose
kind: bfr
# my list of applications
applications:
- # First app
name: app1
kind: nodejs
path: app1
exec:
platforms: k8s
builder: test
- # test 1
name: app2
kind: golang
path: app2
exec:
platform: dockerh
builder: test