0% found this document useful (0 votes)
23 views17 pages

How To Make Your Own Kubectl Command

The document describes how to create custom commands or plugins for kubectl. It covers writing simple plugins using shell scripts or Golang, as well as using Krew to manage and install plugins. Advanced concepts like interacting with the Kubernetes API from a plugin are also demonstrated.

Uploaded by

nilesh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views17 pages

How To Make Your Own Kubectl Command

The document describes how to create custom commands or plugins for kubectl. It covers writing simple plugins using shell scripts or Golang, as well as using Krew to manage and install plugins. Advanced concepts like interacting with the Kubernetes API from a plugin are also demonstrated.

Uploaded by

nilesh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

How to make your own Kubectl

Command

By

Suraj Narwade

1
How to make your own Kubectl Command

Copyright © 2023 by Suraj Narwade.

Notice of Rights.

All rights reserved. No part of this publication may be reproduced, distributed,

or transmitted in any form or by any means without the author's prior written permission.

2
Table of Content
How to make your own Kubectl Command 1

Table of Content 3

Pre-requisite 4
Installing Kubectl 4
On Linux 4
On Mac 4
On Windows 5
Verify Kubectl Installation 5

Kubectl Plugin - aka Custom commands 6


Naming the plugin file 6
Corner case in naming the plugin 6
Find locally available plugins 7

Writing your first plugin - Hello World (shell script) 8

Write your second plugin - Hello World in Golang 9

Write advanced plugins in Golang 10

Krew - Plugin Manager 12


What is Krew? 12
Installing Krew 12
Mac or Linux 12
Windows 13
Installing a plugin with Krew 13
Publish your plugin on Krew Index 14

Questions 16
What if There are two plugins with the same name? 16
What you can’t do? 16

Request 17

3
Pre-requisite
Feel free to skip this section if you already have kubectl and any kubernetes clusters.

● kubectl
● kubernetes cluster (you can use minikube, kind, microk8s, etc.)

Installing Kubectl
On Linux

● Download the latest kubectl binary

curl -LO "https://dl.k8s.io/release/$(curl -L -s


https://dl.k8s.io/release/stable.txt)/bin/linux/amd64/kubectl"

● make it executable

chmod +x kubectl

● I usually prefer to keep binaries inside ~/.local/bin, but you can keep it in other paths
from PATH variable as well.

mkdir -p ~/.local/bin

mv ./kubectl ~/.local/bin/kubectl

On Mac

● Download the latest kubectl binary

curl -LO "https://dl.k8s.io/release/$(curl -L -s


https://dl.k8s.io/release/stable.txt)/bin/darwin/amd64/kubectl"

● make it executable

sudo chmod +x ./kubectl

● move the binary to PATH

4
sudo mv ./kubectl /usr/local/bin/kubectl

On Windows

● Download the latest kubectl binary

curl.exe -LO
"https://dl.k8s.io/release/<version>/bin/windows/amd64/kubectl.exe"

Verify Kubectl Installation


● Run the following command and it should return kubectl client version

kubectl version --client

5
Kubectl Plugin - aka Custom commands
In the kubernetes eco-system, the mechanism to add your custom command is called plugin.

The plugin is a standalone executable file. This means you could use this file even without
leveraging on kubectl. In this book, we aim to integrate this plugin as a kubectl command.
Let’s see how.

Naming the plugin file


So, if what we said about it’s true and this plugin can be used on its own, how does the
kubectl understand it?

The magic’s all in the naming of the plugin. Every plugin you want to add as a command to
kubectl should prefix kubectl- in its name.

For example, if you add a foo command to kubectl, i.e. kubectl foo, you will need to name
your file kubectl-foo

Note: plugin executables must be present in any location from the PATH variable.

Corner case in naming the plugin


if your plugin/command’s name is more than one word (i.e. hello-world) so you can have a
command like

$ kubectl hello-world

You will soon notice that just naming your command kubectl-hello-world will not do the trick
this time.

In this case, you must add _ (underscore) instead of - (hash) between hello and the world,
whilst the rule of prefixing your command with kubectl- will remain the same.

So, for your custom hello world command to work, your file name must be
kubectl-hello_world. Then you can run the command either with

$ kubectl hello-world

or

$ kubectl hello_world

6
Note: underscore(_) or hash(-) will not make any difference in the working of the command
as it is intended only for naming purposes.

Find locally available plugins


Let’s say that you have now added a bunch of plugins, and you don’t remember all of them
off the top of your head. With the help of the following command. You can list all the
available plugins on your local machine's

$ kubectl plugin list

This command will traverse through all the locations in the PATH and look for executables
files with the kubectl- prefix. This command will warn you if the file is not executable but has
the prefix.

Example output:

$ kubectl plugin list


The following compatible plugins are available:

/Users/surajnarwade/.krew/bin/kubectl-krew
/Users/surajnarwade/.krew/bin/kubectl-test
- warning: /Users/surajnarwade/.krew/bin/kubectl-test identified as a
kubectl plugin, but it is not executable
/Users/surajnarwade/.krew/bin/kubectl-view_secret
/usr/local/bin/kubectl-foreach

7
Writing your first plugin - Hello World (shell
script)
You can write it in any language you want, providing it supports the command line.

For our hello world example, we will be using shell script. Create a kubectl-hello file
that echo “Hello World”

#!/bin/bash
echo "Hello world!!!"

Save your plugin file as kubectl-hello. Then:

● make it executable

$ sudo chmod +x ./kubectl-hello

● move this file to one of the locations from the PATH. you can use the following
command to find all the locations from PATH.

$ echo $PATH

Some of the other examples of locations are, /usr/local/bin,/usr/bin, /bin.

● In this case, I am moving the plugin to /usr/local/bin

$ sudo mv ./kubectl-hello /usr/local/bin

And now, let’s go ahead and try it out:

$ kubectl hello
Hello world!!!

8
Write your second plugin - Hello World in
Golang
● Let’s write a simple hello-world program

package main

import "fmt"

func main() {
fmt.Println("Hello world !!!")
}

● save it as hello_world.go

● Let’s build the binary

go build -o kubectl-hello_world hello_world.go

● Above command will generate a binary named kubectl-hello-world


● Now, let’s move this binary to the PATH variable (any location of your preference)

mv kubectl-hello_world ~/.local/bin/

● Now let’s run our plugin written in Golang

$ kubectl hello-world
Hello world !!!

9
Write advanced plugins in Golang
Now that we have seen a basic hello-world plugin, let’s write a simple plugin in Golang which
will solve a real-life problem so that we can also learn a few more advanced concepts when
building custom plugins.

In the example below, we will make a status command to print a list of all pods. Of course,
this command will not necessarily solve any real-life problem, but it will showcase how you
can interact with the Kubernetes API server when making your commands.

Note: inline comments are added to the code to understand better.

package main

import (
"context"
"fmt"
"log"

"k8s.io/client-go/kubernetes"
"k8s.io/client-go/tools/clientcmd"
)

func main() {
kubeconfig := "/path/to/kubeconfig"
// read kubeconfig file
config, err := clientcmd.BuildConfigFromFlags("", kubeconfig)
if err != nil {
log.Fatal(err)
}
// define client
clientset, err := kubernetes.NewForConfig(config)
if err != nil {
log.Fatal(err)
}
// call API to list all the pods
pods, err := clientset.CoreV1().Pods("").List(context.TODO(),
metav1.ListOptions{})
if err != nil {
log.Fatal(err)
}

fmt.Printf("Number of pods in the cluster: %d\n", len(pods.Items))


}

10
Now that we have defined our program, let’s save it and build the binary

$ go build -o status main.go

then, let’s copy our binary to the location from the PATH

$ cp status ~/.local/bin

And finally, let’s run our brand new subcommand

$ kubectl status
Number of pods in the cluster: 22

11
Krew - Plugin Manager
What is Krew?
Krew is a plugin manager for Kubectl. A bonus fun fact for you: Krew itself is a kubectl
plugin!

Installing Krew
Follow this official Krew Documentation to install the Krew based on your Operating system.

https://krew.sigs.k8s.io/docs/user-guide/setup/install/

Mac or Linux
● Run the following script

(
set -x; cd "$(mktemp -d)" &&
OS="$(uname | tr '[:upper:]' '[:lower:]')" &&
ARCH="$(uname -m | sed -e 's/x86_64/amd64/' -e
's/\(arm\)\(64\)\?.*/\1\2/' -e 's/aarch64$/arm64/')" &&
KREW="krew-${OS}_${ARCH}" &&
curl -fsSLO
"https://github.com/kubernetes-sigs/krew/releases/latest/download/${KREW
}.tar.gz" &&
tar zxvf "${KREW}.tar.gz" &&
./"${KREW}" install krew
)

● Then you will need to add ~/.krew/bin to PATH variable

$ export PATH="${KREW_ROOT:-$HOME/.krew}/bin:$PATH"

And finally, verify the installation

$ kubectl krew

output will look like this:

12
$ kubectl krew
krew is the kubectl plugin manager.
You can invoke krew through kubectl: "kubectl krew [command]..."

Usage:
kubectl krew [command]

Available Commands:
completion generate the autocompletion script for the specified shell
help Help about any command
index Manage custom plugin indexes
info Show information about an available plugin
install Install kubectl plugins
list List installed kubectl plugins
search Discover kubectl plugins
uninstall Uninstall plugins
update Update the local copy of the plugin index
upgrade Upgrade installed plugins to newer versions
version Show krew version and diagnostics

Flags:
-h, --help help for krew
-v, --v Level number for the log level verbosity

Use "kubectl krew [command] --help" for more information about a


command.

Windows

● Download krew.exe from the Releases page.


● Run the following command to install krew:

.\krew install krew

● Add the %USERPROFILE%\.krew\bin directory to your PATH environment variable.

Installing a plugin with Krew


If you need a list of all available plugins published by individuals, you can visit this page:
https://krew.sigs.k8s.io/plugins/

Alternatively, you can also download the list of plugins using the following command

13
$ kubectl krew update

Once the list is downloaded. You can explore it locally

$ kubectl krew search


NAME DESCRIPTION
INSTALLED
access-matrix Show an RBAC access matrix for server
resources no

and after exploring the index and selecting the plugin, you can install it using the following
command:

$ kubectl krew install <NAME_OF_THE_PLUGIN>

My favourite plugin so far is view-secret which allows you to view the Kubernetes secrets
easily.

You will install it as

$ kubectl krew install view-secret

Make sure you keep up-to-date with the latest releases of the plugins. For example,

$ kubectl krew upgrade

Publish your plugin on Krew Index


If you think your plugin will be helpful to others, you can open-source it and publish it on the
Krew Index. The process is very straightforward:

● You will need to write a krew manifest file as mentioned here:


https://krew.sigs.k8s.io/docs/developer-guide/plugin-manifest/

● Raise a pull request to the repository with your krew manifest file:
https://github.com/kubernetes-sigs/krew-index

14
If you need additional guidance and inspiration, you can also check previous examples,
here: https://github.com/kubernetes-sigs/krew-index/pulls

15
Questions
What if There are two plugins with the same name?
Whichever comes first in PATH.

What you can’t do?


You can’t override existing kubectl commands. For example, you can’t override the kubectl
get command by kubectl-get or the kubectl version command by kubectl-version

even if you do so. It won’t have any impact.

16
Request
Hello,
If you are reading this, you have read the complete book. Congratulations!!!
I hope you have enjoyed it and learnt something new.

If you have enjoyed it, I will request you to leave a review and a rating for this book. (Be
honest, it will mean a lot to me.)

You can connect with me:


● Twitter
● Linkedin
● Newsletter
● Youtube

Thank you 🙂
Suraj Narwade

17

You might also like