Tuesday, January 4, 2022

[SOLVED] Adding key-values in yaml at specific location using python or sed

Issue

I am trying to add following key values in values.yaml at exactly at particular location, sed doesn't help much, as it breaks indentation of yaml. Is there any other way to get this right.

Ex: sample yaml

enter image description here

desired yaml

enter image description here


Solution

Using sed you can insert a block of text before livenessProbe this way:

sed -e '/livenessProbe/i\
volumes:\n- name: my-agent\n  persistentVolume:\n  claimName: my-agent
' sample.yaml

If sample.yaml is

resources:
  limits:
    cpu: 500m
    memory: 2Gi
  requests:
    cpu: 100m
    memory: 512Mi
livenessProbe:
  httpGetPath: /heartbeat

the result would be:

resources:
  limits:
    cpu: 500m
    memory: 2Gi
  requests:
    cpu: 100m
    memory: 512Mi
volumes:
- name: my-agent
  persistentVolume:
  claimName: my-agent
livenessProbe:
  httpGetPath: /heartbeat

If the code block to add is in a yaml file addons.yaml:

sed -e "/livenessProbe/i\
$(cat addons.yaml | sed ':a;N;$!ba;s/\n/\\n/g')
" sample.yaml


Answered By - Davide Madrisan