Saltar al contenido

Principales 6 comandos de Kubectl y consejos de Kubectl

Los 6 mejores comandos de Kubectl y consejos de Kubectl
Los 6 mejores comandos de Kubectl y consejos de Kubectl

El comando kubectl puede ser el comando más utilizado que puedes escribir al trabajar con el ecosistema de Kubernetes. Como sabes, kubectl es la puerta de entrada a todo el mundo de Kubernetes, ya que prácticamente todas nuestras interacciones pasan por esa parte, a menos que estés utilizando un enfoque de CLI.

Entonces, basándonos en los principios de productividad, si puedes mejorar solo un 1% en la tarea que realizas más, la mejora global será masiva. Así que, veamos cómo podemos hacer eso aquí.

kubectl es un comando con muchas opciones diferentes que podrían ayudar a aumentar tu productividad mucho. Pero al mismo tiempo, como tiene tantas opciones, es bastante complejo conocerlas todas o estar al tanto de que hay una forma más rápida de hacer el trabajo, y por eso me gustaría agregar algunas opciones aquí para intentar ayudarte con este conjunto de consejos de kubectl.

Consejos de Comandos de Kubectl

Comencemos con los primeros comandos de kubectl que ayudan mucho a mejorar tu productividad:

kubectl explain <resource-object>

Este comando mostrará la referencia de la API para cualquier Objeto de Kubernetes, por lo que te ayudará a conocer la ortografía exacta de la opción que siempre escribes mal.

kubectl get <resource-object> —watch-output

La opción —watch-output añadida a cualquier comando de kubectl funcionará de la misma manera que el comando watch en sí, por lo que actualizará el mismo comando cada 2.0 segundos para ver la versión en tiempo real de ese comando y evitar que necesites escribirlo de nuevo o depender de un comando externo como watch

kubectl get events --sort-by=".lastTimestamp"

Este comando te ayudará cuando quieras ver los eventos en tu contexto actual, pero la principal diferencia es que ordenará la salida por la marca de tiempo de más reciente a más antiguo, por lo que evitarás tener que desplazarte para encontrar los últimos eventos.

kubectl logs --previous

Siempre hablamos de una de las necesidades de una Arquitectura de Agregación de Logs porque los logs son desechables, pero ¿qué pasa si quieres obtener los logs en un contenedor eliminado? Puedes usar la bandera --previous para acceder a los logs de un contenedor que se ha terminado recientemente. Esto no eliminará la necesidad de una técnica de agregación de logs, pero ayudará a solucionar problemas cuando Kubernetes comience a eliminar cosas y necesites saber qué sucedió.

kubectl create <object> <options> -o=yaml --dry-run=client

kubectl create nos permite crear un objeto de nuestra preferencia proporcionando los argumentos requeridos de manera imperativa, pero si añadimos la opción -o=yaml --dry-run=client, no obtendremos nuestro objeto creado. En su lugar, tendremos un archivo YAML que define ese objeto. Así que podemos modificarlo fácilmente a nuestras necesidades sin tener que hacerlo desde cero buscando en Google un ejemplo para comenzar.

kubectl top pods --all-namespaces --sort-by='memory'

Este comando alterará el orden estándar de top pods para mostrar los pods y los recursos que están consumiendo, y al mismo tiempo, ordenará esa salida por el uso de memoria. Así que, en entornos con muchos pods, proporcionará justo en la parte superior aquellos en los que deberías centrarte primero para optimizar los recursos de todo tu clúster.

Alias de Kubectl

Un paso más allá es simplificar esos comandos añadiendo un alias a esto. Como puedes ver, la mayoría de estos comandos son bastante largos ya que tienen muchas opciones, por lo que escribir cada una de estas opciones tomará un tiempo.

Entonces, si quieres ir un paso más allá en esta optimización, siempre puedes añadir un alias a ese comando para simplificarlo mucho. Y si quieres aprender más sobre esos alias, recomiendo encarecidamente el repositorio de GitHub de Ahmet Alp Balkan:

Top 6 Kubectl Commands and Kubectl Tips

Top 6 Kubectl Commands and Kubectl Tips
Top 6 Kubectl Commands and Kubectl Tips

Kubectl command can be the most used command you can type when working with the Kubernetes ecosystem. As you know, kubectl is the open the door to all the Kubernetes world as pretty much all of our interactions go through that part, unless you are using a CLI approach.

So, based on the productivity principles, if you can improve just 1% in the task that you perform the most, the global improvement will be massive. So, let’s see how we can do that here.

kubectl is a command with many different options that could help boost your productivity a lot. But at the same time, as it has so many options, it is pretty complex to know all of them or be aware that there is a faster way to do the job, and that’s why I would like to add some options here to try to help you with this set of kubectl tips.

Kubectl Commands Tips

Let’s start with the first kubectl commands that help a lot to improve your productivity:

kubectl explain <resource-object>

This command will show the API reference for any Kubernetes Object, so it would help you know the exact spelling of the option that you always miswrite.

kubectl get <resource-object> —watch-output

The —watch-output option added to any kubectl command will work in the same way as the watch command itself, so it will refresh the same command every 2.0 seconds to see the real-time version of that command and avoid that you need to type it again or rely on an external command such as watch

kubectl get events --sort-by=".lastTimestamp"

This command will help you when you want to see the events in your current context, but the main difference is that it will sort the output by the timestamp from more recent to older, so you will avoid needing to scroll to find the latest events.

kubectl logs --previous

We always talk about one of the needs for a Log Aggregation Architecture because the logs are disposable, but what about if you want to get the logs in a killed container? You can use the --previous flag to access the logs for a recently terminated container. This will not remove the need for a logging aggregation technique, but it will help troubleshoot when Kubernetes start killing things and you need to know what happened.

kubectl create <object> <options> -o=yaml --dry-run=client

kubectl create allows us to create an object of our preference by providing the required arguments imperatively, but if we add the -o=yaml --dry-run=client option, we will not get our object created. Instead, we will have a YAML file defining that object. So we can easily modify it to our needs without needing to make it from scratch by searching Google for a sample to start with.

kubectl top pods --all-namespaces --sort-by='memory'

This command will alter the standard top pods order to show the pods and the resources they are consuming, and at the same time, it will sort that output by the memory usage. So, in environments with many pods, it will provide just at the top the ones you should focus on first to optimize the resources for your whole cluster.

Kubectl Alias

One step beyond that is to simplify those commands by adding an alias to this. As you can see, most of these commands are pretty long as they have many options, so writing each of these options will take a while.

So, if you want to go one step further on this optimization, you can always add an alias to that command to simplify it a lot. And if you want to learn more about those aliases, I strongly recommend the GitHub repo from Ahmet Alp Balkan:

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *