Automating Tasks with Kubectl Scripts: A Practical Guide (with Examples)

Updated: January 30, 2024 By: Guest Contributor Post a comment

Introduction

For developers and system administrators managing Kubernetes clusters, the Kubernetes command-line tool, kubectl, is a critical component of their toolkit. Kubectl enables you to interact with your Kubernetes cluster and manage its resources efficiently. However, performing repetitive tasks manually using kubectl can become tedious and error-prone. To mitigate this, you can write scripts to automate these tasks.

This practical guide will show you how to write kubectl scripts to automate common Kubernetes tasks. We’ll start with the basics, then move on to more complex examples, providing contexts and expected outputs to illustrate.

Getting Started with kubectl

Before diving into scripting, ensure you have kubectl installed and configured to interact with your Kubernetes cluster. You can check your installation by running kubectl version, which should output the client and server versions.

$ kubectl version
Client Version: ... 
Server Version: ... 

Scripting Basics

The simplicity of bash scripting combined with the power of kubectl commands can help in various scenarios, such as rolling updates, log monitoring, and resource scaling. Let’s start with one of the most fundamental tasks: creating a namespace.

To create a new namespace called ‘test-namespace’ via a script:

#!/bin/bash

kubectl create namespace test-namespace

To run your script, save it as create_namespace.sh and make it executable:

$ chmod +x create_namespace.sh
$ ./create_namespace.sh
namespace/test-namespace created

Querying Resources

Use the kubectl get command since accessing resource details is a frequent necessity. Here’s how you might write a script to list all pods in a specific namespace:

#!/bin/bash
namespace=$1

kubectl get pods -n $namespace

Run the script with the namespace as an argument:

$ ./list_pods.sh my-namespace
NAME                     READY   STATUS    RESTARTS   AGE
frontend-8ddbcbc4b-jz4tt 1/1     Running   0          18m
backend-54d57c7d-cj6wb   1/1     Running   0          22m

Executing Commands in Pods

There will be times when you need to execute a command within the context of a particular pod. Here’s an example script to capture heap dumps from a Java application running in your pod:

#!/bin/bash
pod=$1
container=$2

kubectl exec $pod -c $container -- jmap -dump:format=b,file=/tmp/heapdump.hprof

Assign execute permissions and run the script as follows:

$ chmod +x heapdump.sh
$ ./heapdump.sh my-java-pod my-java-container
Dumping heap to /tmp/heapdump.hprof ...
Heap dump file created

Log Monitoring

When you need to follow logs for a certain container, scripting the functionality with kubectl logs can provide a quick, repeatable approach. This example script follows the logs from a specific container in real-time:

#!/bin/bash
pod=$1
container=$2

kubectl logs $pod -c $container -f

After making it executable and running the script, you’ll see the logs output:

$ chmod +x follow_logs.sh
$ ./follow_logs.sh my-pod my-container
10:02:01.019 INFO - Bootstrap ... (logs continue)

Automating Complex Task Sequences

As your automation needs evolve, you may need to script more complex operations. A script that checks the health status of your resources and performs a rolling restart might look like this:

#!/bin/bash

for deploy in $(kubectl get deployments -n prod -o name); do
  if ./deployment_health_checker.sh $deploy; then
    echo "Restarting ${deploy}..."
    kubectl rollout restart $deploy
  else
    echo "${deploy} is not healthy. Skipping..."
  fi
done

The above script relies on another script named deployment_health_checker.sh, which should return a status indicating whether it’s advisable to restart. When run, a healthy deployment will trigger a rolling restart, otherwise it’ll be skipped.

To regenerate the SSL certificates on all nodes, you might script the following:

#!/bin/bash

nodes=$(kubectl get nodes -o name)

for node in $nodes; do
  echo "Regenerating certificates for $node ..."
  ssh ${node#node/} "sudo kubeadm alpha certs renew all"
done

Note that this script uses SSH to access each node, which requires appropriate access and permission setups beforehand.

Conclusion

Writing kubectl scripts is an efficient way to manage recurring tasks in Kubernetes and minimize the potential for human error. Starting with simple tasks and gradually advancing to complex automations can greatly improve your operational efficiency. Scripting your Kubernetes operations allows you to deliver a more reliable system due to improved consistency and speed in deployment and maintenance tasks.