Friday, 10 September 2021

 

This post is copied form https://www.ibm.com/cloud/blog/8-kubernetes-tips-and-tricks

1. Set default namespaces

You can divide a Kubernetes cluster into multiple environments by using namespaces (e.g., Dev1, Dev2, QA1, QA2, etc.), and each environment can be managed by a different user. One of the inconveniences of writing kubectl commands is that every time you write a command, you need the --namespace option at the end. People often forget this and end up creating objects (pods, services, deployments) in the wrong namespace. 

With this trick, you can set the namespace preference before running kubectl commands. Run the following command before executing the kubectl commands, and it will save the namespace for all subsequent kubectl commands for your current context:

kubectl config set-context $(kubectl config current-context) --namespace=mynamespace

Some of the most common and useful commands with namespace are listed below:

  • kubectl get namespaces
  • kubectl create namespace mynamespace
  • kubectl get pods --all-namespaces (List all pods with status from all namespaces.)
  • kubectl get po -o wide -n <namspace1> -n <namespace2> -n <namespace3> (This command will identify the pods in each namespace)
  • kubectl describe namespace <namespace>
  • kubectl config view --minify | grep namespace (This command will ensure that you set the namespace correctly for your current context.) 

2. Helpful aliases to save time

Kubernetes commands can be quite lengthy, so setting up some aliases for running kubectl is very helpful. You will no longer need to spell out the full command over and over again, making your life a lot easier when you want to execute multiple Kubernetes commands in one session.

We have listed aliases for some frequently used commands below. Run these before executing kubectl commands to save yourself some time. Example: You just need to type k instead of typing kubectl:

  • alias k='kubectl'
  • alias kc='k config view --minify | grep name'
  • alias kdp='kubectl describe pod'
  • alias krh='kubectl run --help | more'
  • alias ugh='kubectl get --help | more'
  • alias c='clear'
  • alias kd='kubectl describe pod'
  • alias ke='kubectl explain'
  • alias kf='kubectl create -f'
  • alias kg='kubectl get pods --show-labels'
  • alias kr='kubectl replace -f'
  • alias kh='kubectl --help | more'
  • alias krh='kubectl run --help | more'
  • alias ks='kubectl get namespaces'
  • alias l='ls -lrt'
  • alias ll='vi ls -rt | tail -1'
  • alias kga='k get pod --all-namespaces'
  • alias kgaa='kubectl get all --show-labels'

3. YAML editing with vi

There are many different editors available to write YAML files, but there are many times where you may need to quickly tweak a generated YAML and while working on a terminal. This is a great place to use our trusty vi, the text editor originally created for the Unix operating system.

The vi editor is well documented and has support from a vibrant open source community. One of the problems with the vi editor while creating YAML files, however, is the space issue. We need a way to indent with tabs and align with spaces. Using tabs vs. spaces for whitespace has always created syntax issues while writing YAML files (e.g., getting the 2-space YAML as the default when hitting carriage return).

The solution? Create a ~/.vimrc file with these lines before creating YAML files with the vi editor to make editing easier:

  • set smarttab
  • set expandtab
  • set shiftwidth=4
  • set tabstop=4
  • set number

4. Create YAML from kubectl commands 

We can create complex YAML files from the command line using kubectl commands.

Most people would agree that working with YAML files is no fun, and Kubernetes YAML files can be very verbose and hard to create from scratch. It is much easier to create the YAML file from kubectl commands instead of from a blank page using an editor.

The following commands will create a YAML file with name yamlfile. Once you create the YAML file from these kubectl commands, you can modify it based on your requirements and use it instead of writing from scratch:

  • kubectl run busybox --image=busybox --dry-run=client -o yaml --restart=Never > yamlfile.yaml
  • kubectl create job my-job --dry-run=client -o yaml --image=busybox -- date  > yamlfile.yaml
  • kubectl get -o yaml deploy/nginx > 1.yaml (Ensure that you have a deployment named as nginx)
  • kubectl run busybox --image=busybox --dry-run=client -o yaml --restart=Never -- /bin/sh -c "while true; do echo hello; echo hello again;done" > yamlfile.yaml
  • kubectl run wordpress --image=wordpress –-expose –-port=8989 --restart=Never -o yaml
  • kubectl run test --image=busybox --restart=Never --dry-run=client -o yaml -- bin/sh -c 'echo test;sleep 100' > yamlfile.yaml  (Notice that --bin comes at the end. This will create yaml file.)

Another good idea for creating the YAML file is obtaining the file directly from the internet using the wget command. 

5. Switching between Kubernetes namespaces

In Tip 1, we learned some useful commands to use Kubernetes namespaces and save them so that you don't have to add to every command. Let's expand the tip to make it easier to switch between namespaces and kubectl contexts.

There are several tools that can help, but we like kubectx and kubens for managing contexts and namespaces, respectively. You can find details of kubectx and kubens here.

Here is how to download the Linux binaries for kubectx and kubens utility:

  • wget https://github.com/ahmetb/kubectx/releases/download/v0.9.0/kubectx_v0.9.0_linux_x86_64.tar.gz
  • wget https://github.com/ahmetb/kubectx/releases/download/v0.9.0/kubens_v0.9.0_linux_x86_64.tar.gz

Then you extract them with the following commands:

  • tar -xvf kubectx_v0.9.0_linux_x86_64.tar.gz
  • tar -xvf kubens_v0.9.0_linux_x86_64.tar.gz

Finally, you move them to your PATH:

  • sudo mv kubectx /usr/local/bin
  • sudo mv kubens /usr/local/bin

Once installed, you can simply use kubens to list the namespaces and switch between them:

Once installed, you can simply use kubens to list the namespaces and switch between them:

When working with multiple clusters, kubectx makes switching between contexts a breeze:

When working with multiple clusters, kubectx makes switching between contexts a breeze:

6. Shell auto-completion

Did you know that kubectl provides auto-completion for BASH and ZSH? This is an optional configuration.

Let’s say you understand the concepts of Kubernetes and have some experience with kubectl, but perhaps you aren’t so good at memorizing commands. First you install bash-completion, and then you enable kubectl autocompletion. You can find all the details in the “Install and Set Up kubectl“ documentation page for your environment.

Below are the config options with the autocompletion feature:

Below are the config options with the autocompletion feature:

Now, just tab away!

7. Viewing resource utilization

The top command is probably one of the most popular tools to monitor processes and system resources. It provides a simple character-based interface and quick access to crucial information.

You can see resource utilization per node:

You can see resource utilization per node:

Resource utilization per pod:

Resource utilization per pod:

And the handy watch command can help you display the command in a desirable interval without having to run it over and over again. The following example makes it run every five seconds (the default is two seconds): 

watch kubectl top node -n 5

Note: The watch command needs to be downloaded for your environment.

Your Kubernetes cluster also needs to be running heapster in order for the top command work, otherwise you'll get the following error: “Error from server (NotFound): the server could not find the requested resource (get services http:heapster:)”

Learn how to enable the heapster add-on.

8. Extend kubectl and create your own commands using raw outputs

The kubectl command provides a summarized view of the resources stored by the apiserver. There are many more fields stored by the apiserver that are not shown. You can use the kubectl get command with the raw resource output to create your own visualization and commands. 

You can print the raw resources in JSON with the following command:

kubectl get deployments -o json

You can also call the resource directly using the api call:

kubectl get --raw=/apis/apps/v1/deployments

You can even combine the output with tools like jq to provide different visualizations, filter the output, or feed the output to other tools for advance automation. 

For example, it can be hard to find issues on clusters with multiple namespaces and deployments, but the example below uses the raw API to scan all deployments in the cluster and filter only the deployments with failing replicas:

kubectl get --raw=/apis/apps/v1/deployments | jq '.items[] | {name: .metadata.name, replicas: .status.replicas, available: (.status.availableReplicas // 0), unavailable: (.status.unavailableReplicas // 0)} | select (.unavailable > 0)'

The following is a quick explanation of the command above:

  • First, we call the Kubernetes API to return all deployments. The default output is in JSON. It is hard to visualize the structure of the JSON document, but you can pipe to jq to get a better idea like in the example below:
    kubectl get --raw=/apis/apps/v1/deployments | jq .
  • Notice that the response document has an array of items for each deployment. We want to inspect the status field of this array all the way in the end. The command below shows how to print just the data you need and a default value of 0 when the field is not available:
    kubectl get --raw=/apis/apps/v1/deployments | jq '.items[] | {name: .metadata.name, replicas: .status.replicas, available: (.status.availableReplicas // 0), unavailable: (.status.unavailableReplicas // 0)}'
  • The final piece of the puzzle is using the select function to only display deployments with unavailable replicas:
    kubectl get --raw=/apis/apps/v1/deployments | jq '.items[] | {name: .metadata.name, replicas: .status.replicas, available: (.status.availableReplicas // 0), unavailable: (.status.unavailableReplicas // 0)} | select (.unavailable > 0)'