How To Make Your Own Kubectl Command
How To Make Your Own Kubectl Command
Command
By
Suraj Narwade
1
How to make your own Kubectl Command
Notice of Rights.
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
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
● 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
● make it executable
4
sudo mv ./kubectl /usr/local/bin/kubectl
On Windows
curl.exe -LO
"https://dl.k8s.io/release/<version>/bin/windows/amd64/kubectl.exe"
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.
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.
$ 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.
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:
/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!!!"
● make it executable
● 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
$ 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
mv kubectl-hello_world ~/.local/bin/
$ 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.
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)
}
10
Now that we have defined our program, let’s save it and build the binary
then, let’s copy our binary to the location from the PATH
$ cp status ~/.local/bin
$ 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
)
$ export PATH="${KREW_ROOT:-$HOME/.krew}/bin:$PATH"
$ kubectl krew
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
Windows
Alternatively, you can also download the list of plugins using the following command
13
$ kubectl krew update
and after exploring the index and selecting the plugin, you can install it using the following
command:
My favourite plugin so far is view-secret which allows you to view the Kubernetes secrets
easily.
Make sure you keep up-to-date with the latest releases of the plugins. For example,
● 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.
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.)
Thank you 🙂
Suraj Narwade
17