Update Multiple Lines in a YAML file with Kubectl

Update Multiple Lines in a YAML file with Kubectl

27 April 2022
yaml
patch
kubernetes

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.

Lab Setup

You can start the lab setup by clicking on the Lab Setup button on the right side of the screen. Please note that there are app-specific URLs exposed specifically for the hands-on lab purpose.

Our lab has been set up with all necessary tools like base OS (Ubuntu), and developer tools like Git, Vim, wget, and others. 

Lab With Kubectl Patch

As we triggered the lab through the LAB SETUP button, a terminal, and an IDE comes for us which already have a Kubernetes cluster running in them. This can be checked by running the kubectl get nodes command.    

Creating Kubernetes Deployment

  • First, let’s create the nginx-deployment with 2 replicas and with container image as nginx with alpine tag.

Apply the above nginx-deployment.yaml file and then check deployments and pods

kubectl apply -f nginx-deployment.yaml
Figure 1: Using the kubectl apply to create a deployment
Figure 1: Using the kubectl apply to create a deployment
kubectl get deployments
kubectl get pods

Now, let’s update the number of replicas in the spec  and also the nginx container image version. Remember, it's multiline, and using any other option can be a bit clumsy.    

Updating Kubernetes Deployment

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

Then patch the nginx-deployment with the below command

kubectl patch deployment/nginx-deployment --patch "$(cat patch.yaml)"
Figure 2: Using the kubectl patch to update the existing deployment
Figure 2: Using the kubectl patch to update the existing deployment

Once you see this message deployment.apps/nginx-deployment patched. Run the below command to check the deployments

kubectl get deployments
kubectl get pods
kubectl get deployment nginx-deployment -o yaml

and look for to see the previous configuration that is replaced 

What Next?

As we have seen an example about how to patch an existing deployment with a kubectl patch, more information on this can be found out here.

Conclusion

In this hands-on lab, we learned how to update existing Kubernetes resources with the kubectl patch command.

How likely are you going to recommend this lab to your friends or colleagues?

Unlikely
Likely

Leave a comment:

About the Author

Vidyasagar Chandra

Vidyasagar Chandra

Solutions Architect, Product Manager & Developer Advocate, IBM.

Vidyasagar is a polyglot and pragmatic programmer, who loves technologies changing lives. He is an AI Enthusiast mastering Machine learning and Data Science. He has more than 14 years of experience and currently working as Solutions Architect, Product Manager & Developer Advocate at IBM.