Mastering Kubernetes: How to use Kubectl Part 2

Mastering Kubernetes: How to use Kubectl Part 2

How to configure the Kubetctl tool?

Introduction

Most of the time we don’t need to work with our Kubernetes cluster because it works automatically by orchestrating our workloads.

I said “Most of the time” because we need to make the following actions:

  • Deploy a new workload
  • Update a workload
  • Rollback a workload
  • Troubleshoot a workload

For this we have two choices:

We only use the Kubernetes API for communicating with the Kubernetes cluster through an application for specific needs.

So most of the time when we need to do one of the actions mentioned above, we will use the tool Kubectl!

How to install and use Kubectl?

We have two options:

  • using one global project tool which will create the Kubernetes cluster and install automatically the Kubectl which will point directly to this Kubernetes cluster: Docker Desktop, Minikube etc..
  • downloading and installing the Kubectl directly.

We will see the second option here.

The Kubectl project is available in the following link:

[GitHub - kubernetes/kubectl: Issue tracker and mirror of kubectl code
The k8s.io/kubectl repo is used to track issues for the kubectl cli distributed with k8s.io/kubernetes. It also…github.com](https://github.com/kubernetes/kubectl "github.com/kubernetes/kubectl")

and is written in the Go language.

To install the Kubectl we can use the following tutorial:

[Install Tools
Set up Kubernetes tools on your computer. The Kubernetes command-line tool, kubectl, allows you to run commands against…kubernetes.io](https://kubernetes.io/docs/tasks/tools/ "kubernetes.io/docs/tasks/tools")

Because I work with Windows 11 I will follow the tutorial

[Install and Set Up kubectl on Windows
Before you begin You must use a kubectl version that is within one minor version difference of your cluster. For…kubernetes.io](https://kubernetes.io/docs/tasks/tools/install-kubectl-windows/ "kubernetes.io/docs/tasks/tools/install-kube..")

We just need to download the latest version:

https://dl.k8s.io/release/v1.25.0/bin/windows/amd64/kubectl.exe

Then we can add the kubectl.exe location to our PATH env variable so we can use it on our command line.

Now we are ready to configure our tool Kubectl.

Our tool Kubectl doesn’t know anything about a Kubernetes cluster without any configuration.

It will be the subject of the next section

How to configure Kubectl?

Let’s run the following command:

>kubectl config
Modify kubeconfig files using subcommands like "kubectl config set current-context my-context"

The loading order follows these rules:

1. If the --kubeconfig flag is set, then only that file is loaded. The flag may only be set once and no merging takes
place.

  1. If $KUBECONFIG environment variable is set, then it is used as a list of paths (normal path delimiting rules for
    your system). These paths are merged. When a value is modified, it is modified in the file that defines the stanza. When
    a value is created, it is created in the first file that exists. If no files in the chain exist, then it creates the
    last file in the list.
  2. Otherwise, ${HOME}/.kube/config is used and no merging takes place.

Available Commands:
current-context Display the current-context
delete-cluster Delete the specified cluster from the kubeconfig
delete-context Delete the specified context from the kubeconfig
delete-user Delete the specified user from the kubeconfig
get-clusters Display clusters defined in the kubeconfig
get-contexts Describe one or many contexts
get-users Display users defined in the kubeconfig
rename-context Rename a context from the kubeconfig file
set Set an individual value in a kubeconfig file
set-cluster Set a cluster entry in kubeconfig
set-context Set a context entry in kubeconfig
set-credentials Set a user entry in kubeconfig
unset Unset an individual value in a kubeconfig file
use-context Set the current-context in a kubeconfig file
view Display merged kubeconfig settings or a specified kubeconfig file

Usage:
kubectl config SUBCOMMAND [options]

Use "kubectl --help" for more information about a given command.
Use "kubectl options" for a list of global command-line options (applies to all commands).

It says by default the config file used is: ${HOME}/.kube/config. Well ${HOME} is a Linux env variable, on Windows it is rather %userprofile%

Let’s create this directory .kube and file config:

> cd %userprofile
> mkdir .kube
> cd .kube

We just created the .kube directory in our user profile directory.

Now we will create the config file which is the Kubeconfig file with the YAML format.

It will list the following items:

  • cluster details
  • users
  • contexts

When we use kubectl with the config command we will need only to know about the contexts.

We can see the following depedencies:

Context => Cluster => User

Once we select one context, Kubectl will get the cluster information to reach for the Kubernetes API in the control plane. At last Kubectl will use the user information to get the proper authentication and authorization on the Kubernetes cluster when Kubectl sends the commands.

Let’s create our config yaml file with the very minimum info: a context:

  • name: context name
  • namespace: default namespace in the cluster
  • user: name of the user used for the auth in the Kubernetes API

apiVersion: v1
kind: Config
contexts:
- context:
cluster: minikube
namespace: default
user: minikube
name: minikube

We just add a context named: minikube because I use minikube to work on my dev machine.

Now let’s run the command:

>kubectl config get-contexts
CURRENT NAME CLUSTER AUTHINFO NAMESPACE
minikube

Great we know now:

  • what config file is used by kubectl
  • How to create the yaml config file and add a context

Now we need to know how to connect to our Cluster from the minikube Context.

As a matter of fact, Kubectl can’t connect with this basic config file:

>kubectl get node
Unable to connect to the server: dial tcp [::1]:8080: connectex: No connection could be made because the target machine actively refused it.

We had to wait a while because getting this response, we had a timeout.

Now let’s see how to add the information for connecting to the Minikube cluster:

First, we add the cluster info:

  • server: the URI to find the kubernetes API
  • name : the cluster name
  • certificate-authority : it is the authority which was used to issue the certificate: its data is encrypted in %user%profile\.minikube\ca.crt

It tells use the Kubernetes API will use the certificate to authenticate the requests.

Let’s add the cluster information:

apiVersion: v1
kind: Config
contexts:
- context:
cluster: minikube
namespace: default
user: minikube
name: minikube
clusters:
- cluster:
certificate-authority: C:\Users\nbarlatier\.minikube\ca.crt
server: https://127.0.0.1:52213
name: minikube
preferences: {}

Let’s see what we got:

>kubectl config get-contexts
CURRENT NAME CLUSTER AUTHINFO NAMESPACE
minikube minikube minikube default

We made progress we got:

  • Context Name
  • Cluster NAme
  • AuthInfo : is the user name
  • Namespace: default namespace

Finally let’s use the user information which will be used to authenticate the user:

  • name: name of the user
  • user with client certificate and client key are used to auth the user through the certificate issued by the CA

apiVersion: v1
kind: Config
contexts:
- context:
cluster: minikube
namespace: default
user: minikube
name: minikube
clusters:
- cluster:
certificate-authority: C:\Users\nbarlatier\.minikube\ca.crt
server: https://127.0.0.1:52213
name: minikube
users:
- name: minikube
user:
client-certificate: C:\Users\xxx\.minikube\profiles\minikube\client.crt
client-key: C:\Users\xxx\.minikube\profiles\minikube\client.key

Now we get:

>kubectl config get-contexts
CURRENT NAME CLUSTER AUTHINFO NAMESPACE
minikube minikube minikube default

We just need to tell kubectl what is the default context with the command:

>kubectl config use-context minikube
Switched to context "minikube".

Now we get

>kubectl config get-contexts
CURRENT NAME CLUSTER AUTHINFO NAMESPACE
* minikube minikube minikube default

We noticed the star underneath Current, so now kubectl can call the kubernetes API of the minikube cluster

Let’s try:

>kubectl get nodes
NAME STATUS ROLES AGE VERSION
minikube Ready control-plane,master 17d v1.23.3

Yay, we did it!

Now we understand better how to configure our tool Kubectl and we can easily import other context/cluster/user information and switch our kubectl to the context we need, so we can manage any kubernetes cluster from our dev machine even the remote cluster (if the admin gave you the proper user and opened the network obviously)!

We can add the different parts of the config file manually or with kubectl with for example the command:

>kubectl config set-cluster

to add info to our cluster.

we can use

>kubectl config set-context

to add info to our context

we can use

>kubectl config set-credentials

to add info about the user used to authenticate when the request is sent to the Kubernetes API.

We need to explore the reference to see all the options which are available.

But this article was an introduction. You can find further details in the references in the Conclusion section.

Moreover kubectl can help us when we don’t add parameters for example when we use set-credentials without params:

>kubectl config set-credentials

Sets a user entry in kubeconfig

Specifying a name that already exists will merge new fields on top of existing values.

Client-certificate flags:
--client-certificate=certfile --client-key=keyfile

Bearer token flags:
--token=bearer_token

Basic auth flags:
--username=basic_user --password=basic_password

Bearer token and basic auth are mutually exclusive.

Examples:

Set only the "client-key" field on the "cluster-admin"

entry, without touching other values:

kubectl config set-credentials cluster-admin --client-key=~/.kube/admin.key

# Set basic auth for the "cluster-admin" entry
kubectl config set-credentials cluster-admin --username=admin --password=uXFGweU9l35qcif

# Embed client certificate data in the "cluster-admin" entry
kubectl config set-credentials cluster-admin --client-certificate=~/.kube/admin.crt
--embed-certs=true

# Enable the Google Compute Platform auth provider for the "cluster-admin" entry
kubectl config set-credentials cluster-admin --auth-provider=gcp

# Enable the OpenID Connect auth provider for the "cluster-admin" entry with additional args
kubectl config set-credentials cluster-admin --auth-provider=oidc
--auth-provider-arg=client-id=foo --auth-provider-arg=client-secret=bar

# Remove the "client-secret" config value for the OpenID Connect auth provider for the
"cluster-admin" entry
kubectl config set-credentials cluster-admin --auth-provider=oidc
--auth-provider-arg=client-secret-

# Enable new exec auth plugin for the "cluster-admin" entry
kubectl config set-credentials cluster-admin --exec-command=/path/to/the/executable
--exec-api-version=client.authentication.k8s.io/v1beta1

# Define new exec auth plugin args for the "cluster-admin" entry
kubectl config set-credentials cluster-admin --exec-arg=arg1 --exec-arg=arg2

# Create or update exec auth plugin environment variables for the "cluster-admin" entry
kubectl config set-credentials cluster-admin --exec-env=key1=val1 --exec-env=key2=val2

# Remove exec auth plugin environment variables for the "cluster-admin" entry
kubectl config set-credentials cluster-admin --exec-env=var-to-remove-

Options:
--auth-provider='': Auth provider for the user entry in kubeconfig
--auth-provider-arg=[]: 'key=value' arguments for the auth provider
--embed-certs=false: Embed client cert/key for the user entry in kubeconfig
--exec-api-version='': API version of the exec credential plugin for the user entry in
kubeconfig
--exec-arg=[]: New arguments for the exec credential plugin command for the user entry in
kubeconfig
--exec-command='': Command for the exec credential plugin for the user entry in kubeconfig
--exec-env=[]: 'key=value' environment values for the exec credential plugin

Usage:
kubectl config set-credentials NAME [--client-certificate=path/to/certfile]
[--client-key=path/to/keyfile] [--token=bearer_token] [--username=basic_user]
[--password=basic_password] [--auth-provider=provider_name] [--auth-provider-arg=key=value]
[--exec-command=exec_command] [--exec-api-version=exec_api_version] [--exec-arg=arg]
[--exec-env=key=value] [options]

Use "kubectl options" for a list of global command-line options (applies to all commands).
error: Unexpected args: []

Conclusion

We can find all the reference about kube config:

[Organizing Cluster Access Using kubeconfig Files
Use kubeconfig files to organize information about clusters, users, namespaces, and authentication mechanisms. The…kubernetes.io](https://kubernetes.io/docs/concepts/configuration/organize-cluster-access-kubeconfig/ "kubernetes.io/docs/concepts/configuration/o..")

[Kubectl Reference Docs
This section contains the most basic commands for getting a workload running on your cluster. run will start running 1…kubernetes.io](https://kubernetes.io/docs/reference/generated/kubectl/kubectl-commands#config "kubernetes.io/docs/reference/generated/kube..")

[Configure Access to Multiple Clusters
This page shows how to configure access to multiple clusters by using configuration files. After your clusters, users…kubernetes.io](https://kubernetes.io/docs/tasks/access-application-cluster/configure-access-multiple-clusters/ "kubernetes.io/docs/tasks/access-application..")