I have a k8s yaml file with below block
spec:
replicas: 1
strategy:
type: Recreate
and I want to add below block after "spec:"
selector:
matchLabels:
app: test-app
The file is huge and has many "spec:" fields, so it should be added at the first match.
Final file content should look like this :
spec:
selector:
matchLabels:
app: test-app
replicas: 1
strategy:
type: Recreate
I came up with this working solution using yq with correct indentation but it appends at the end of the file, Its painful to maintain and reading similar 100's of files.
yq -i -y '.spec += {selector:{matchLabels:{app:"test-app"}}}' filename.yaml
Any answers with tools like sed or awk are welcome.
Here you go
$ yq --yaml-output '.spec |= ({selector: {matchLabels: {app: "test-app"}}} + .)' </tmp/your-yaml-file.yaml
spec:
selector:
matchLabels:
app: test-app
replicas: 1
strategy:
type: Recreate
Since you mentioned you have hundreds of files and each has many spec
elements, it's unclear if this will solve your actual problem but hopefully it can be of help. Good luck!