Managing Kubernetes without losing your cool Kubernetes Community Days Ukraine March 16th 2023
A presentation at Kubernetes Community Days Ukraine in March 2023 in by Marcus Noble
Managing Kubernetes without losing your cool Kubernetes Community Days Ukraine March 16th 2023
Hi đ, Iâm Marcus Noble, a platform engineer at Iâm found around the web as â¨AverageMarcus⨠in most places and @Marcus@k8s.social on Mastodon đ ~5 years experience running Kubernetes in production environments.
Summary My tips for working with Kubernetes #1 â #5 Anyone can start using these today #6 â #7 Good to know a little old-skool ops first More & Summary Suggestions for more advanced topics but not covered in details
#0 - Pay someone else to deal with it OK, this one is kinda tongue in cheek but worth mentioning. If you have dozens or hundreds of clusters on-top of other development work youâre going to be stretched thin. Getting someone else to manage things while you focus on what makes your business money can often be the right choice.
#1 - Love your terminal
#1 - Love your terminal â Bash? ZSH? Fish? 𤡠- Doesnât matter as long as youâre comfortable with it. â ârcâ files - e.g. .bashrc, .zshrc These set configuration for each terminal session you open. â alias - easily create your own terminal commands â Look for âdotfilesâ on GitHub - e.g. https://github.com/averagemarcus/dotfiles Create your own workflow of tasks you perform often. Avoid typos and âfat fingeringâ by replacing long, complex commands with short aliases (bonus points for adding help text to remind you later)
#2 - Learn to love kubectl
#2 - Learn to love kubectl
â
Tip #1 in action
Add alias k=âkubectlâ to your .bashrc / .zshrc / .whateverrc
KIND: VERSION:
k get pods -A â
The official docs offer a single page view of all built in commands: kubernetes.io/docs/reference/generated/kube ctl/kubectl-commands
â
k explain pods.spec.containers
kubectl explain is your friend! Find out what any property of any Kubernetes resource is for. âĄ
Pod v1
RESOURCE: containers <[]Object> DESCRIPTION: List of containers belonging to the pod. Containers cannot currently be added or removed. There must be at least one container in a Pod. Cannot be updated. A single application container that you want to run within a pod. FIELDS: args <[]string> Arguments to the entrypoint. The docker imageâs CMD is used if this is not provided. Variable references $(VAR_NAME) are expanded using the containerâs environment. If a variable cannot be resolved, the reference in the input string will be unchanged. Double $$ are reduced to a single $, which allows for escaping the $(VAR_NAME) syntax: i.e. â$$(VAR_NAME)â will produce the string literal â$(VAR_NAME)â. Escaped references will never be expanded, regardless of whether the variable exists or not. Cannot be updated. command <[]string> Entrypoint array. Not executed within a shell. The docker imageâs ENTRYPOINT is used if this is not provided. Variable references $(VAR_NAME)
Save time by only typing k
. Kubectl explain for digging into resources and their properties (useful when you canât access the official docs or know exactly what youâre looking for)
#3 - Multiple kubeconfigs
#3 - Multiple kubeconfigs â Quick switch between different Kubernetes contexts (clusters) and between different namespaces. â kubectx and kubens https://github.com/ahmetb/kubectx â kubie https://github.com/sbstp/kubie â kubeswitch https://github.com/danielfoehrKn/kubeswitch kubeswitch my fave as it supports directory of kubeconfigs to make organising easier - you can see it in action here
#4 - Interactive UIs
#4 - k9s github.com/derailed/k9s Interactive terminal. Supports all resource types and actions. Lots of keybinding and similar to quickly work with a cluster. Find, view, edit, port forward, view logs, delete, etc.
#4 - OpenLens github.com/MuhammedKalkan/OpenLens Alternatively, if you prefer a more UI based interface then Lens is a great tool to manage multiple clusters.
#5 - kubectl plugins
#5 - kubectl plugins â
Any command in your $PATH that is prefixed with kubectl- becomes a kubectl plugin
$ cat kubectl-hello #!/bin/bash
â
Krew - package manager for kubectl plugins
echo âHello, Kubeâ
github.com/kubernetes-sigs/krew
â
Install plugins with: kubectl krew install <PLUGIN NAME>
$ kubectl hello Hello, Kube
â
Some of my fave plugins: â stern - Multi-pod/container log tailing â tree - Show hierarchy of resources based on ownerReferences â community-images - Find images still referencing the k8s.gcr.io registry. â gs - Giant Swarmâs plugin for working with our managed clusters
Plugins can be in any language. You can easily add your own by creating Bash scripts with a kubectl-
prefixed name. Note: autocomplete is a bit trickier here. Some plugins support it but generally expect your tabcompletion to only recommend core kubectl features.
Summary My tips for working with Kubernetes â #1 â #5 Anyone can start using these today #6 â #7 Good to know a little old-skool ops first More & Summary Suggestions for more advanced topics but not covered in details Not so scary so far, right? Now on to a little more hands-on techniques.
#6 - Pod Debugging
#6 - Pod Debugging: kshell Launch a temporary pod running a bash shell for cluster debugging Tip #1 in action, again alias kshell=âkubectl run \ -it \ âimage bash \ ârestart Never \ ârm \ shellâ Need more tools? Replace this with alpine or ubuntu Great for more general debugging of a cluster, especially with networking issues or similar.
#6 - Pod Debugging: kshell Launch a temporary pod running a bash shell for cluster debugging
Great for more general debugging of a cluster, especially with networking issues or similar.
#6 - Pod Debugging: kubectl exec Debugging an existing, running pod - kubectl exec
Note: â
â
â
Needs a shell environment within the container Limited to whatâs available in the container (or what you can pull in from the ânet) Container needs to be running
kubectl exec
is great for debugging misconfigured pods that arenât crashing and have enough OS to exec into. But⌠If the pod is CrashLooping youâll get kicked out of the session when it crashes. If the pod doesnât have a shell you can exec into (e.g. a container that only has a Golang binary) youâll not be able to exec kubectl debug
is great for pods that either donât have any OS
#6 - Pod Debugging: kubectl debug Debugging a running pod - kubectl exec
�� error: Internal error occurred: error executing command in container: failed to exec in container: failed to start execâŚâŚ Debugging a running pod - kubectl debug Requires Kubernetes v1.23+
kubectl exec
is great for debugging misconfigured pods that arenât crashing and have enough OS to exec into. But⌠If the pod is CrashLooping youâll get kicked out of the session when it crashes. If the pod doesnât have a shell you can exec into (e.g. a container that only has a Golang binary) youâll not be able to exec kubectl debug
is great for pods that either donât have any OS
��
#6 - Pod Debugging: kubectl debug Example - investigate a CrashLooping pod
READY 0/1
STATUS CrashLoopBackOff
RESTARTS 2 (20s ago)
AGE 44s
This will prevent us from kubectl exec
into the pod
kubectl debug
has a few different modes: - launches an âephemeral containerâ within the pod youâre debugging - kubectl debug
- creates a copy of the pod with some values replaced (e.g. the image used) - kubectl debug âcopy-to
- launch a pod in the nodes host namespace to debug the node - kubectl debug node/my-node
This has some limitations - cannot access all filesystem of failing container, only volumes that are shared
#6 - Pod Debugging When to use what: kshell Multiple workloads experiencing network issues Workload not running as expected but not CrashLooping and isnât a stripped down image (e.g. not Scratch / Distroless) Workload not running as expected but not CrashLooping and has an image based on Scratch / Distroless or similar Workload is CrashLooping kubectl exec kubectl debug â â â â
#7 - Node Debugging
#7 - Node Debugging: kubectl debug (again) â
Requires Kubernetes v1.23 # kubectl debug node/ip-10-0-0-1 -it âimage alpine Creating debugging pod node-debugger-ip-10-0-0-1-9wlqp with container debugger on node ip-10-0-0-1. If you donât see a command prompt, try pressing enter. / # ls -l / total 60 ⌠drwxr-xr-x 2 root root 4096 Aug 9 08:47 home drwxr-xr-x 19 root root 4096 Nov 4 08:48 host The host nodeâs root filesystem drwxr-xr-x 7 root root 4096 Aug 9 08:47 lib drwxr-xr-x 5 root root 4096 Aug 9 08:47 media ⌠/ #
Why not SSH? - I prefer to use ephemeral instances with the minimal needed to run Kubernetes, no sshd, no port 22 open etc. but there are times when you just need to check whatâs actually going on with the underlying host machine.
kubectl debug
launches a pod on the node which allows for direct access to the node host. Processes and filesystem is available to you. Being your own toolkit with you depending on what --image
you specify.
#7 - Node Debugging: nsenter alternative â
For older clusters before Kubernetes v1.23 # kubectl run h0nk ârm -it \ âimage alpine âprivileged \ âoverrides â{âspecâ:{âhostPIDâ: true}}â\ âcommand nsenter â \ âmount=/proc/1/ns/mnt If you donât see a command prompt, try pressing enter. #
â
Alternatives: github.com/AverageMarcus/kube-ssh github.com/giantswarm/kubectl-enter
This wonât work with Talos, for example, whereas kubectl debug
will
â
Note: Underlying host needs a valid shell
Only needed if kubectl debug
not available for your cluster. A one-liner to exec into a privileged pod and switch to the host namespace using nsenter
- small enough to fit in a Tweet or on a sticker! More âpackagedâ alternatives available with kube-ssh or kubectl-enter
Summary My tips for working with Kubernetes â #1 â #5 Anyone can start using these today â #6 â #7 Good to know a little old-skool ops first More & Summary Suggestions for more advanced topics but not covered in details
MoreâŚ
Webhooks â Implement more advanced access control than is possible with RBAC. [Restricting cluster-admin permissions] â Add defaulting logic to Kubernetes resources â Enforce company policies such as not using latest as an image tag or ensuring all workloads have resource requests/limits specified. â âHotfixâ for security issues (e.g. injecting env var to prevent Log4Shell exploit). [Log4Shell Mitigation] â Be careful using webhooks as itâs easy to introduce cluster-breaking configurations! đą [Webhooks Talk] Tools: â Kyverno - Kubernetes native policy management. â OPA Gatekeeper - Policy management built on top of Open Policy Agent Allows for subtractive access control (take away a users ability to perform a certain action against a certain resource) - something not possible with RBAC See blog post about how we avoided a nasty bug in our CLI tool with a ValidatingWebhook. https://www.giantswarm.io/blog/restricting-cluster-admin-permissions
Kubernetes API Resources: - kubernetes/client-go - the official Golang module for interacting with the Kubernetes API - Kubernetes Provider for Terraform (actually uses the above Go module under the hood) - kubernetes-client org on GitHub has many official clients in different languages Where is this useful? â Building our own CLI / desktop tooling (e.g. k9s, Lens). â Cluster automation - resources managed by CI, CronJobs, etc. â Building our own operators to extend Kubernetes. Make use of one of the many client libraries available rather than interacting with the REST endpoint directly. Plenty more official clients available at https://github.com/kubernetes-client
CRDs & Operators Extend Kubernetesâ built-in API and functionality with your own Custom Resource Definitions (CRDs) and business logic (operators). Image credits: Container Solutions https://blog.container-solutions.com/kubernetes-operators-explained Weâve already seen hints of this already in this talk. Kyverno implements CRDs and has an operator that manages them. We mentioned extending the Kubernetes API with custom resources, giving us the programmatic access for our operators.
Recap #1 - Love your terminal #6 - Pod Debugging #2 - Learn to love kubectl #7 - Node Debugging #3 - Multiple kubeconfigs #4 - k9s / OpenLens More - Webhooks, Kubernetes #5 - Kubectl plugins API, CRDs & Controllers
Shell aliases and helpers Alias k, kubectl explain Kubeswitch Interactively work with clusters Krew. Build your own with bash. Kubectl- prefixed name Pod debugging Node debugging Validating and mutating requests to the Kubernetes API Working directly with the API to build our own logic Extending Kubernetes with our own resources and logic
Wrap-up Slides and resources available at: https://go-get.link/kcdukraine Thoughts, comments and feedback: feedback@marcusnoble.co.uk https://k8s.social/@Marcus Thank you