DEV Community

Vidyasagar SC Machupalli
Vidyasagar SC Machupalli

Posted on

Update multiple lines in a YAML file with kubectl

Whenever I need to update a YAML file, the first thing that comes to mind is to either use sed or awk or perl etc., But there's an in-house Kubectl patch option that simplifies the experience.

Photo by Vidyasagar Machupalli

For example, let's update the number of replicas in the spec below and also the Nginx container image version. Remember, it's multiline and using any other option can be bit clumsy.

Source: https://kubernetes.io/docs/tasks/run-application/run-stateless-application-deployment/



apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx-deployment
spec:
  selector:
    matchLabels:
      app: nginx
  replicas: 2 # tells deployment to run 2 pods matching the template
  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
      - name: nginx
        image: nginx:1.14.2
        ports:
        - containerPort: 80


Enter fullscreen mode Exit fullscreen mode

Let's apply the file



kubectl apply -f https://k8s.io/examples/application/deployment.yaml


Enter fullscreen mode Exit fullscreen mode

Locally, let's create a file called patch.yaml with the below content



spec:
  selector:
    matchLabels:
      app: nginx
  replicas: 3 # Update the number replicas from 2 to 3
  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
      - name: nginx
        image: nginx:1.16.1 # Update the version of nginx from 1.14.2 to 1.16.1
        ports:
        - containerPort: 80


Enter fullscreen mode Exit fullscreen mode

and then patch the deployment with the below command



kubectl patch deployment/nginx-deployment --patch "$(cat patch.yaml)"


Enter fullscreen mode Exit fullscreen mode

Once you see this message deployment.apps/nginx-deployment patched. Run the below commands



Kubectl get deployments 
# NAME                  READY   UP-TO-DATE   AVAILABLE   AGE
#nginx-deployment      3/3     3            3           3h

kubectl get deployment nginx-deployment -o yaml


Enter fullscreen mode Exit fullscreen mode

and look for to see the previous configuration that is replaced



kubectl.kubernetes.io/last-applied-configuration: |
      {"apiVersion":"apps/v1","kind":"Deployment","metadata":{"annotations":{},"name":"nginx-deployment","namespace":"default"},"spec":{"replicas":2,"selector":{"matchLabels":{"app":"nginx"}},"template":{"metadata":{"labels":{"app":"nginx"}},"spec":{"containers":[{"image":"nginx:1.14.2","name":"nginx","ports":[{"containerPort":80}]}]}}}}


Enter fullscreen mode Exit fullscreen mode

Top comments (0)