CKA · Módulo 0CKA · Module 0CKA · Modulo 0 K8s v1.34

Setup + el arte del imperativo

Setup + the art of the imperative

Setup + l'arte dell'imperativo

El módulo de calentamiento. Aliases, --dry-run como generador de YAML, y la diferencia imperativo/declarativo que te ahorra el 20% del tiempo en el examen. Sin esto, todo lo demás es lento.

The warm-up module. Aliases, --dry-run as a YAML generator, and the imperative/declarative split that buys back 20% of your exam time. Without this, everything else is slow.

Il modulo di riscaldamento. Alias, --dry-run come generatore di YAML, e la differenza imperativo/dichiarativo che ti restituisce il 20% del tempo d'esame. Senza questo, tutto il resto è lento.

Duración60 min
Duration60 min
Durata60 min
Peso examenBase (transversal)
Exam weightBase (cross-cutting)
Peso d'esameBase (trasversale)
Tipo100% hands-on
Type100% hands-on
Tipo100% hands-on
PrioridadCrítica para velocidad
PriorityCritical for speed
PrioritàCritica per la velocità
El CKA no se gana sabiendo más Kubernetes que el resto: se gana ejecutando más rápido. Son ~17 tareas en 120 minutos — unos 7 min por tarea, y varias son de múltiples pasos. La diferencia entre aprobar y no llegar casi nunca es el conocimiento: es la velocidad para generar manifiestos. Este módulo te da las tres herramientas que hacen esa diferencia: aliases, el patrón --dry-run, y el criterio de cuándo usar imperativo o declarativo.
The CKA is not won by knowing more Kubernetes than everyone else: it is won by executing faster. It is ~17 tasks in 120 minutes — about 7 minutes each, and several are multi-step. The gap between passing and running out of time is almost never knowledge: it is how fast you produce manifests. This module hands you the three tools that make that difference: aliases, the --dry-run pattern, and the judgement of when to go imperative or declarative.
Il CKA non si vince sapendo più Kubernetes degli altri: si vince eseguendo più in fretta. Sono ~17 task in 120 minuti — circa 7 minuti ciascuno, e diversi sono a più passi. La differenza fra passare e non arrivare non è quasi mai la conoscenza: è la velocità nel produrre manifest. Questo modulo ti dà i tre strumenti che fanno la differenza: alias, il pattern --dry-run, e il criterio per scegliere fra imperativo e dichiarativo.
01
Setup · 20 min
Setup · 20 min
Setup · 20 min

Cluster local multi-node

Local multi-node cluster

Cluster locale multi-node

VMs con kubeadm — el entorno de máxima fidelidad con el examen
VMs with kubeadm — the highest-fidelity match to the exam
VM con kubeadm — l'ambiente più fedele all'esame
Práctica · Hands-on
Practice · Hands-on
Pratica · Hands-on

El entorno: VMs con kubeadm (no kind)

The environment: VMs with kubeadm (not kind)

L'ambiente: VM con kubeadm (non kind)

El CKA corre sobre un cluster armado con kubeadm sobre máquinas Linux reales. El mejor entorno de práctica es el que más se parece al examen: VMs Ubuntu con kubeadm. El paso a paso está en la guía de Setup, con la estrategia de snapshots.

The CKA runs on a cluster built with kubeadm on real Linux machines. The best practice environment is the one closest to the exam: Ubuntu VMs with kubeadm. The step-by-step lives in the Setup guide, snapshot strategy included.

Il CKA gira su un cluster costruito con kubeadm su macchine Linux reali. Il miglior ambiente di pratica è quello più simile all'esame: VM Ubuntu con kubeadm. Il passo-passo è nella guida di Setup, strategia di snapshot inclusa.

  • cp1 — control plane (2 vCPU, 2-4 GB)
  • w1 (y opcionalmente w2) — workers (2 vCPU, 2 GB)
  • cp1 — control plane (2 vCPU, 2-4 GB)
  • w1 (and optionally w2) — workers (2 vCPU, 2 GB)
  • cp1 — control plane (2 vCPU, 2-4 GB)
  • w1 (e facoltativamente w2) — worker (2 vCPU, 2 GB)

Por qué NO kind ni minikube

Why not kind or minikube

Perché non kind né minikube

kind corre cada nodo como contenedor Docker, sin systemd real: no podés practicar kubeadm, backup/restore de etcd, ni systemctl restart kubelet — que juntos son más del 40% del examen. minikube es mejor pero tampoco te da kubeadm desde cero ni el control total del control plane.

kind runs each node as a Docker container, with no real systemd: you cannot practise kubeadm, etcd backup/restore, or systemctl restart kubelet — together over 40% of the exam. minikube is better but still gives you neither kubeadm-from-scratch nor full control-plane access.

kind esegue ogni nodo come container Docker, senza un vero systemd: non puoi esercitarti con kubeadm, backup/restore di etcd, né systemctl restart kubelet — insieme oltre il 40% dell'esame. minikube è meglio ma non ti dà comunque kubeadm da zero né il controllo totale del control plane.

⚠
kind NO es la opción recomendada para el CKA. Sirve para desarrollar apps sobre K8s, pero el CKA evalúa administración (kubeadm, etcd, nodos) que kind no reproduce. Usá VMs.
kind is NOT the recommended option for the CKA. It is fine for developing apps on K8s, but the CKA tests administration (kubeadm, etcd, nodes) that kind does not reproduce. Use VMs.
kind NON è l'opzione consigliata per il CKA. Va bene per sviluppare app su K8s, ma il CKA valuta l'amministrazione (kubeadm, etcd, nodi) che kind non riproduce. Usa le VM.
Teoría · Por qué VMs + snapshots
Theory · Why VMs + snapshots
Teoria · Perché VM + snapshot

Por qué nodos reales y varios

Why real nodes, and more than one

Perché nodi reali, e più di uno

  • kubeadm: init, join y upgrade necesitan máquinas con systemd.
  • etcd: backup/restore necesita el filesystem del control plane.
  • Scheduling: taints y affinity solo tienen sentido con varios nodos.
  • Troubleshooting de nodo: kubelet, static pods, systemctl de verdad.
  • kubeadm: init, join and upgrade need machines with systemd.
  • etcd: backup/restore needs the control plane's filesystem.
  • Scheduling: taints and affinity only make sense across several nodes.
  • Node troubleshooting: kubelet, static pods, real systemctl.
  • kubeadm: init, join e upgrade richiedono macchine con systemd.
  • etcd: backup/restore richiede il filesystem del control plane.
  • Scheduling: taint e affinity hanno senso solo con più nodi.
  • Troubleshooting del nodo: kubelet, static pod, systemctl veri.

El superpoder: snapshots

The superpower: snapshots

Il superpotere: gli snapshot

Muchos ejercicios son destructivos (romper el cluster a propósito). Los snapshots te dan repetición infinita: rompés, arreglás, restaurás, repetís.

Many drills are destructive (breaking the cluster on purpose). Snapshots give you infinite repetition: break it, fix it, restore, repeat.

Molti esercizi sono distruttivi (rompere il cluster di proposito). Gli snapshot ti danno ripetizione infinita: rompi, aggiusti, ripristini, ripeti.

★
Mantené 3 snapshots base: base-prep (sistema listo, sin cluster), cluster-ready (nodos funcionando) y pre-upgrade (una minor atrás, para practicar upgrades).
Keep 3 base snapshots: base-prep (system ready, no cluster), cluster-ready (nodes running) and pre-upgrade (one minor behind, to practise upgrades).
Tieni 3 snapshot di base: base-prep (sistema pronto, senza cluster), cluster-ready (nodi funzionanti) e pre-upgrade (una minor indietro, per esercitarti sugli upgrade).
02
Velocidad · 10 min
Speed · 10 min
Velocità · 10 min

Aliases obligatorios

Mandatory aliases

Alias obbligatori

Lo primero que tipeás el día del examen. Practicá con ellos desde HOY.
The first thing you type on exam day. Practise with them from TODAY.
La prima cosa che digiti il giorno dell'esame. Esercitati con questi da OGGI.
Práctica · Copiá esto
Practice · Copy this
Pratica · Copia questo

Los primeros 60 segundos del examen

The first 60 seconds of the exam

I primi 60 secondi dell'esame

# El alias k ya viene seteado, pero por las dudas:# The k alias ships preset, but just in case:# L'alias k è già impostato, ma per sicurezza:
alias k=kubectl

# Generador de YAML — el más importante# YAML generator — the important one# Generatore di YAML — il più importante
export do="--dry-run=client -o yaml"

# Borrado instantáneo (sin grace period)# Instant delete (no grace period)# Cancellazione istantanea (senza grace period)
export now="--force --grace-period=0"

# Autocompletado (suele venir activo, verificalo)# Completion (usually on already, verify it)# Autocompletamento (di solito è attivo, verificalo)
source <(kubectl completion bash)
complete -F __start_kubectl k

Cómo se usan

How to use them

Come si usano

k run nginx --image=nginx $do > pod.yaml
k delete pod nginx $now
⚠
No te vuelvas loco con aliases. Los que sobran te hacen perder tiempo recordándolos. k, $do y $now alcanzan; más que eso es contraproducente bajo presión.
Do not go alias-crazy. Extra ones cost you time trying to remember them. k, $do and $now are enough; anything more backfires under pressure.
Non impazzire con gli alias. Quelli in più ti fanno perdere tempo a ricordarli. k, $do e $now bastano; oltre a questi è controproducente sotto pressione.
Teoría · El porqué
Theory · The why
Teoria · Il perché

La cuenta del tiempo

The time arithmetic

Il conto del tempo

kubectl vs k son 7 caracteres menos por comando, y tipeás más de 100. Pero el ahorro grande es $do: --dry-run=client -o yaml son 27 caracteres que escribís decenas de veces; con el alias son 3.

kubectl vs k is 7 fewer characters per command, and you type over 100 of them. The big win, though, is $do: --dry-run=client -o yaml is 27 characters you type dozens of times; the alias makes it 3.

kubectl contro k sono 7 caratteri in meno per comando, e ne digiti oltre 100. Il risparmio grosso però è $do: --dry-run=client -o yaml sono 27 caratteri che scrivi decine di volte; con l'alias diventano 3.

AliasPara qué
AliasWhat for
AliasA cosa serve
kkubectl (siempre)
kkubectl (always)
kkubectl (sempre)
$dogenerar YAML sin aplicar
$dogenerate YAML without applying
$dogenerare YAML senza applicare
$nowborrar sin esperar
$nowdelete without waiting
$nowcancellare senza attendere
★
Si practicás con k desde el día 1, en el examen ya es automático. Si lo dejás para el final, vas a tipear kubectl por costumbre y perdés el beneficio.
Practise with k from day one and it is automatic by exam day. Leave it for the end and you will type kubectl out of habit and lose the benefit.
Se ti alleni con k dal primo giorno, all'esame è automatico. Se lo rimandi alla fine, digiterai kubectl per abitudine e perdi il vantaggio.
03
Concepto core · 15 min
Core concept · 15 min
Concetto centrale · 15 min

Imperativo vs Declarativo

Imperative vs Declarative

Imperativo vs Dichiarativo

El criterio que decide tu velocidad: cuándo tipear un comando y cuándo escribir YAML.
The judgement call that sets your pace: when to type a command, when to write YAML.
Il criterio che decide il tuo ritmo: quando digitare un comando e quando scrivere YAML.
Práctica · Los dos modos
Practice · The two modes
Pratica · I due modi

Imperativo — decís QUÉ hacer

Imperative — you say WHAT to do

Imperativo — dici COSA fare

k run nginx --image=nginx
k create deployment web --image=nginx --replicas=3
k expose deployment web --port=80 --type=ClusterIP
k create configmap app-cfg --from-literal=KEY=value
k scale deployment web --replicas=5

Declarativo — describís el ESTADO deseado

Declarative — you describe the desired STATE

Dichiarativo — descrivi lo STATO desiderato

k apply -f deployment.yaml
k apply -f ./manifests/
★
La estrategia ganadora: generá el esqueleto con imperativo + $do, y después editás el YAML solo para lo que el comando no soporta. Nunca escribas YAML desde cero.
The winning strategy: generate the skeleton imperatively with $do, then edit the YAML only for what the command cannot express. Never write YAML from scratch.
La strategia vincente: genera lo scheletro in modo imperativo con $do, poi modifica lo YAML solo per ciò che il comando non copre. Non scrivere mai YAML da zero.
Teoría · Cuándo cada uno
Theory · Which one when
Teoria · Quale e quando

Decisión rápida

Quick decision

Decisione rapida

SituaciónModo
SituationMode
SituazioneModo
Objeto simple (pod, deploy)Imperativo
Simple object (pod, deploy)Imperative
Oggetto semplice (pod, deploy)Imperativo
Campos sin flag equivalenteGenerar + editar
Fields with no matching flagGenerate + edit
Campi senza flag corrispondenteGenerare + modificare
Multi-container, volumes, probesDeclarativo
Multi-container, volumes, probesDeclarative
Multi-container, volumi, probeDichiarativo
Borrar / escalar / exponer rápidoImperativo
Delete / scale / expose quicklyImperative
Cancellare / scalare / esporre in frettaImperativo

Lo que el imperativo NO puede

What the imperative CANNOT do

Cosa l'imperativo NON può fare

  • Pods multi-container
  • volumes y volumeMounts
  • initContainers
  • Probes (readiness / liveness / startup)
  • securityContext detallado
  • affinity y topology constraints
  • Multi-container pods
  • volumes and volumeMounts
  • initContainers
  • Probes (readiness / liveness / startup)
  • Detailed securityContext
  • affinity and topology constraints
  • Pod multi-container
  • volumes e volumeMounts
  • initContainers
  • Probe (readiness / liveness / startup)
  • securityContext dettagliato
  • affinity e topology constraint

Para todos esos: generás el esqueleto con $do y agregás a mano solo el bloque que falta.

For all of those: generate the skeleton with $do and hand-add only the missing block.

Per tutti questi: genera lo scheletro con $do e aggiungi a mano solo il blocco mancante.

04
La técnica clave · 15 min
The key technique · 15 min
La tecnica chiave · 15 min

--dry-run como generador de YAML

--dry-run as a YAML generator

--dry-run come generatore di YAML

El patrón que usás 30+ veces en el examen. Internalizalo hasta que sea reflejo.
The pattern you use 30+ times in the exam. Drill it until it is reflex.
Il pattern che usi 30+ volte all'esame. Allenalo finché non diventa un riflesso.
Práctica · El patrón maestro
Practice · The master pattern
Pratica · Il pattern maestro

Generar → editar → aplicar

Generate → edit → apply

Generare → modificare → applicare

# 1 · generar el esqueleto (NO crea nada)# 1 · generate the skeleton (creates nothing)# 1 · generare lo scheletro (non crea nulla)
k run nginx --image=nginx $do > pod.yaml

# 2 · editar lo que falta (resources, volumes, probes…)# 2 · edit what is missing (resources, volumes, probes…)# 2 · modificare ciò che manca (resources, volumi, probe…)
vim pod.yaml

# 3 · aplicar# 3 · apply# 3 · applicare
k apply -f pod.yaml

Recetas imperativas que generan YAML

Imperative recipes that generate YAML

Ricette imperative che generano YAML

k run nginx --image=nginx $do                          #  Pod
k create deploy web --image=nginx --replicas=3 $do     #  Deployment
k expose deploy web --port=80 $do                      #  Service
k create job pi --image=perl -- perl -Mbignum=bpi -wle 'print bpi(20)' $do
k create cronjob backup --image=busybox --schedule="*/5 * * * *" $do
k create cm app --from-literal=K=V $do
k create secret generic db --from-literal=pass=1234 $do
k create service clusterip hl --clusterip=None $do     #  headless

# pod que ejecuta un comando# pod running a command# pod che esegue un comando
k run test --image=busybox $do -- /bin/sh -c "sleep 3600" > pod.yaml
★
Cuando no hay generador (DaemonSet, StatefulSet) el truco es el mismo: generás un Deployment y cambiás el kind. Y si no te acordás un campo, k explain --recursive <recurso>.spec te da el árbol entero sin salir de la terminal.
When no generator exists (DaemonSet, StatefulSet) the trick is the same: generate a Deployment and change the kind. And if you cannot recall a field, k explain --recursive <resource>.spec prints the whole tree without leaving the terminal.
Quando non esiste un generatore (DaemonSet, StatefulSet) il trucco è lo stesso: generi un Deployment e cambi il kind. E se non ricordi un campo, k explain --recursive <risorsa>.spec stampa tutto l'albero senza uscire dal terminale.
Teoría · Por qué funciona
Theory · Why it works
Teoria · Perché funziona

Las 3 piezas

The 3 pieces

I 3 pezzi

FlagQué hace
FlagWhat it does
FlagCosa fa
--dry-run=clientsimula, no envía al API server
--dry-run=clientsimulates, never hits the API server
--dry-run=clientsimula, non contatta l'API server
-o yamlsalida en formato YAML
-o yamloutput in YAML
-o yamloutput in YAML
> archivoguarda en archivo en vez de stdout
> filewrites to a file instead of stdout
> filescrive su file invece che su stdout

client vs server

client: valida localmente y muestra el YAML, no toca el cluster. Es el que usás para generar. server: lo manda al API server, que valida pero no persiste — útil para comprobar que algo es válido sin crearlo.

client: validates locally and prints the YAML, never touching the cluster. That is the one you generate with. server: sends it to the API server, which validates but does not persist — handy to check something is valid without creating it.

client: valida in locale e stampa lo YAML, senza toccare il cluster. È quello con cui generi. server: lo manda all'API server, che valida ma non persiste — utile per verificare che qualcosa sia valido senza crearlo.

El error de indentación que no querés

The indentation error you do not want

L'errore di indentazione che non vuoi

Escribir YAML a mano en vim bajo presión = errores de indentación que te comen minutos. Generar el esqueleto correcto y solo editar elimina el 90% de eso.

Hand-writing YAML in vim under pressure = indentation errors that eat minutes. Generating a correct skeleton and only editing removes 90% of them.

Scrivere YAML a mano in vim sotto pressione = errori di indentazione che ti mangiano minuti. Generare uno scheletro corretto e limitarsi a modificare ne elimina il 90%.

★
Config de vim para YAML (en ~/.vimrc al practicar): set et ts=2 sw=2 — expande tabs a 2 espacios, esencial para que el YAML no se rompa.
Vim config for YAML (in ~/.vimrc while practising): set et ts=2 sw=2 — expands tabs to 2 spaces, essential to keep YAML from breaking.
Configurazione di vim per lo YAML (in ~/.vimrc mentre ti alleni): set et ts=2 sw=2 — espande i tab a 2 spazi, essenziale perché lo YAML non si rompa.
★
Cierre del módulo
Module wrap-up
Chiusura del modulo

Lo que te llevás del Módulo 0

What you take from Module 0

Cosa porti via dal Modulo 0

Resumen · Kit de arranque
Summary · Starter kit
Riassunto · Kit di partenza
# los 3 aliases (primeros 30 segundos)# the 3 aliases (first 30 seconds)# i 3 alias (primi 30 secondi)
alias k=kubectl
export do="--dry-run=client -o yaml"
export now="--force --grace-period=0"

# ~/.vimrc: set et ts=2 sw=2

# el patrón maestro# the master pattern# il pattern maestro
k <crear-algo> $do > obj.yaml
vim obj.yaml
k apply -f obj.yaml
Teoría · Mentalidad CKA
Theory · CKA mindset
Teoria · Mentalità CKA

Los 3 principios de velocidad

The 3 speed principles

I 3 principi di velocità

  • Nunca escribas YAML desde cero. Generá con $do.
  • Imperativo para lo simple, declarativo solo cuando hace falta.
  • kubernetes.io/docs es tu amigo. Tenés una pestaña permitida: aprendé a navegarla rápido.
  • Never write YAML from scratch. Generate it with $do.
  • Imperative for the simple stuff, declarative only when needed.
  • kubernetes.io/docs is your friend. You get one allowed tab: learn to navigate it fast.
  • Non scrivere mai YAML da zero. Generalo con $do.
  • Imperativo per le cose semplici, dichiarativo solo quando serve.
  • kubernetes.io/docs è tuo amico. Hai una scheda consentita: impara a navigarla in fretta.
★
Este cheat sheet anotalo a mano (los 3 aliases + el patrón maestro). Escribirlo lo fija mejor que releerlo diez veces.
Write this cheat sheet out by hand (the 3 aliases + the master pattern). Writing it fixes it better than re-reading it ten times.
Trascrivi a mano questo bigliettino (i 3 alias + il pattern maestro). Scriverlo lo fissa meglio che rileggerlo dieci volte.
Checkpoint Módulo 0: cluster armado, aliases automáticos y patrón dry-run internalizado. Siguiente: Módulo 1 — Cluster Architecture con kubeadm.
Module 0 checkpoint: cluster built, aliases automatic and the dry-run pattern internalised. Next: Module 1 — Cluster Architecture with kubeadm.
Checkpoint Modulo 0: cluster costruito, alias automatici e pattern dry-run interiorizzato. Prossimo: Modulo 1 — Cluster Architecture con kubeadm.
★
Fase 2 · drills de velocidad
Phase 2 · speed drills
Fase 2 · drill di velocità

Práctica — 5 drills cronometrados

Practice — 5 timed drills

Pratica — 5 drill a tempo

Acá no se aprende teoría: se construye músculo. Cronometrate.
No theory here: this builds muscle. Put a clock on it.
Qui non si impara teoria: si costruisce muscolo. Cronometrati.
0 / 5
⏱
Cómo hacerlos. Namespace m0. Cronómetro en la mano y el tiempo objetivo de cada tarjeta como techo. Si te pasás, repetilo al día siguiente: la meta no es resolverlo, es resolverlo rápido y sin pensar.
How to run them. Namespace m0. Stopwatch in hand, each card's target time as the ceiling. If you go over, repeat it the next day: the goal is not solving it, it is solving it fast and without thinking.
Come farli. Namespace m0. Cronometro alla mano e il tempo obiettivo di ogni scheda come tetto. Se sfori, ripetilo il giorno dopo: l'obiettivo non è risolverlo, è risolverlo in fretta e senza pensare.
E1

Los primeros 60 segundos

The first 60 seconds

I primi 60 secondi

~1 min

Con la terminal recién abierta: dejá listos k, $do, $now, el autocompletado sobre k, y vim configurado para YAML. Después probá que k run x --image=nginx $do imprime YAML y no crea nada.

On a freshly opened terminal: get k, $do, $now, completion on k, and vim configured for YAML. Then prove that k run x --image=nginx $do prints YAML and creates nothing.

Su un terminale appena aperto: prepara k, $do, $now, l'autocompletamento su k e vim configurato per lo YAML. Poi dimostra che k run x --image=nginx $do stampa YAML e non crea nulla.

Ver soluciónShow solutionMostra soluzione
alias k=kubectl
export do="--dry-run=client -o yaml"
export now="--force --grace-period=0"
source <(kubectl completion bash); complete -F __start_kubectl k
echo 'set et ts=2 sw=2' >> ~/.vimrc

k run x --image=nginx $do
k get pod x        # NotFound → confirmado: no creó nada# NotFound → confirmed: it created nothing# NotFound → confermato: non ha creato nulla
Claves
Key points
Punti chiave
  • El complete -F __start_kubectl k es el que hace que el autocompletado funcione con el alias, no solo con kubectl.
  • Los export viven en la sesión: si abrís otra terminal, los volvés a poner.
  • complete -F __start_kubectl k is what makes completion work on the alias, not just on kubectl.
  • The exports live in the session: open another terminal and you set them again.
  • complete -F __start_kubectl k è ciò che fa funzionare l'autocompletamento sull'alias, non solo su kubectl.
  • Gli export vivono nella sessione: se apri un altro terminale, li rimetti.
E2

Ocho objetos en tres minutos

Eight objects in three minutes

Otto oggetti in tre minuti

~3 min

Sin abrir la documentación, creá en m0: un Pod p1 (nginx), un Deployment d1 (nginx, 3 réplicas), un Service que exponga d1 en el 80, un ConfigMap c1 con A=1, un Secret s1 con pw=x, un Job j1 que haga echo hola, un CronJob cj1 cada 5 minutos, y un Service headless hl.

Without opening the docs, create in m0: a Pod p1 (nginx), a Deployment d1 (nginx, 3 replicas), a Service exposing d1 on 80, a ConfigMap c1 with A=1, a Secret s1 with pw=x, a Job j1 doing echo hola, a CronJob cj1 every 5 minutes, and a headless Service hl.

Senza aprire la documentazione, crea in m0: un Pod p1 (nginx), un Deployment d1 (nginx, 3 repliche), un Service che esponga d1 sulla 80, un ConfigMap c1 con A=1, un Secret s1 con pw=x, un Job j1 che faccia echo hola, un CronJob cj1 ogni 5 minuti e un Service headless hl.

Ver soluciónShow solutionMostra soluzione
k create ns m0
k run p1 --image=nginx -n m0
k create deploy d1 --image=nginx --replicas=3 -n m0
k expose deploy d1 --port=80 -n m0
k create cm c1 --from-literal=A=1 -n m0
k create secret generic s1 --from-literal=pw=x -n m0
k create job j1 --image=busybox -n m0 -- echo hola
k create cronjob cj1 --image=busybox --schedule="*/5 * * * *" -n m0 -- echo hola
k create service clusterip hl --clusterip=None -n m0
Claves
Key points
Punti chiave
  • El -- separa los flags de kubectl del comando del container. Todo lo que va después es del container.
  • expose toma el selector del deployment solo: por eso no hay que escribirlo.
  • El -n m0 en cada comando. Este drill existe justamente para grabarlo.
  • -- separates kubectl's flags from the container's command. Everything after it belongs to the container.
  • expose takes the selector from the deployment itself: that is why you never write it.
  • -n m0 on every command. This drill exists precisely to burn that in.
  • -- separa i flag di kubectl dal comando del container. Tutto ciò che segue appartiene al container.
  • expose prende il selector dal deployment stesso: per questo non lo scrivi mai.
  • -n m0 su ogni comando. Questo drill esiste proprio per fissarlo.
E3

Generar y editar: lo que el flag no puede

Generate and edit: what the flag cannot do

Generare e modificare: ciò che il flag non può

~5 min

Creá un Pod web con dos containers (nginx y un busybox que haga sleep 1d), un emptyDir montado en ambos, y una readinessProbe HTTP en el nginx. Partí de un dry-run, no de una hoja en blanco.

Create a Pod web with two containers (nginx and a busybox running sleep 1d), an emptyDir mounted in both, and an HTTP readinessProbe on nginx. Start from a dry-run, not a blank page.

Crea un Pod web con due container (nginx e un busybox che faccia sleep 1d), un emptyDir montato in entrambi e una readinessProbe HTTP sull'nginx. Parti da un dry-run, non da un foglio bianco.

Ver soluciónShow solutionMostra soluzione
k run web --image=nginx -n m0 $do > web.yaml
vim web.yaml
apiVersion: v1
kind: Pod
metadata:
  name: web
  namespace: m0
spec:
  containers:
  - name: web
    image: nginx
    readinessProbe:            # nivel CONTAINER# CONTAINER level# livello CONTAINER
      httpGet: { path: /, port: 80 }
      initialDelaySeconds: 3
    volumeMounts:
    - name: shared
      mountPath: /data
  - name: side               # el segundo container# the second container# il secondo container
    image: busybox
    command: ["sleep", "1d"]
    volumeMounts:
    - name: shared
      mountPath: /data
  volumes:                     # nivel POD# POD level# livello POD
  - name: shared
    emptyDir: {}
Claves
Key points
Punti chiave
  • Ninguna de las tres cosas (2º container, volumen, probe) tiene flag: el dry-run te da igual la mitad del trabajo (apiVersion, metadata, indentación base).
  • volumeMounts se repite en cada container; volumes se declara una vez a nivel pod. El name los enlaza.
  • Si dudás de un campo: k explain pod.spec.containers.readinessProbe --recursive.
  • None of the three things (2nd container, volume, probe) has a flag: the dry-run still hands you half the work (apiVersion, metadata, base indentation).
  • volumeMounts repeats in every container; volumes is declared once at pod level. The name links them.
  • Unsure about a field? k explain pod.spec.containers.readinessProbe --recursive.
  • Nessuna delle tre cose (2° container, volume, probe) ha un flag: il dry-run ti dà comunque metà del lavoro (apiVersion, metadata, indentazione di base).
  • volumeMounts si ripete in ogni container; volumes si dichiara una volta a livello pod. Il name li collega.
  • Dubbi su un campo? k explain pod.spec.containers.readinessProbe --recursive.
E4

Leer el cluster rápido

Reading the cluster fast

Leggere il cluster in fretta

~3 min

Sin editores ni grep a ciegas, contestá con un comando cada una: ¿en qué nodo corre p1? ¿Qué imagen usa d1? ¿Cuántos pods hay en todo el cluster? ¿Qué recursos existen en el ns m0? ¿Cuál es el nombre corto de configmaps?

No editors, no blind grep: answer each with one command. Which node runs p1? Which image does d1 use? How many pods exist cluster-wide? What resources live in ns m0? What is the short name for configmaps?

Niente editor né grep alla cieca: rispondi a ciascuna con un comando. Su quale nodo gira p1? Quale immagine usa d1? Quanti pod ci sono in tutto il cluster? Quali risorse ci sono nel ns m0? Qual è il nome breve di configmaps?

Ver soluciónShow solutionMostra soluzione
k get pod p1 -n m0 -o wide            # columna NODE# NODE column# colonna NODE
k get deploy d1 -n m0 -o wide         # columna IMAGES# IMAGES column# colonna IMAGES
k get pods -A --no-headers | wc -l
k get all -n m0                       # ojo: "all" NO incluye cm/secret/pvc/ingress# careful: "all" does NOT include cm/secret/pvc/ingress# attenzione: "all" NON include cm/secret/pvc/ingress
k api-resources | grep configmap       # cm# cm# cm
Claves
Key points
Punti chiave
  • -o wide resuelve la mitad de las preguntas de "¿dónde/qué?" sin abrir el YAML.
  • k api-resources es el diccionario: nombres cortos, si es namespaced y el apiVersion. Vale oro cuando no te acordás si algo lleva -n.
  • k get all engaña: no lista ConfigMaps, Secrets, PVCs ni Ingress.
  • -o wide answers half the "where/what" questions without opening the YAML.
  • k api-resources is the dictionary: short names, namespaced or not, apiVersion. Gold when you cannot recall whether something takes -n.
  • k get all is misleading: it lists no ConfigMaps, Secrets, PVCs or Ingresses.
  • -o wide risponde a metà delle domande "dove/cosa" senza aprire lo YAML.
  • k api-resources è il dizionario: nomi brevi, se è namespaced e l'apiVersion. Vale oro quando non ricordi se qualcosa vuole -n.
  • k get all inganna: non elenca ConfigMap, Secret, PVC né Ingress.
E5

Limpiar en un comando

Clean up in one command

Pulire con un comando

~1 min

Borrá el pod p1 al instante (sin esperar el grace period) y después el namespace entero. Fijate cuánto tarda cada uno y por qué.

Delete pod p1 instantly (no grace period) and then the whole namespace. Notice how long each takes, and why.

Cancella il pod p1 all'istante (senza grace period) e poi l'intero namespace. Nota quanto ci mette ciascuno, e perché.

Ver soluciónShow solutionMostra soluzione
k delete pod p1 -n m0 $now
k delete ns m0
Claves
Key points
Punti chiave
  • Por defecto un pod tiene 30 s de terminationGracePeriodSeconds: $now los saltea. En el examen, cuando borrás para rehacer, eso son segundos que sumás.
  • Borrar el namespace borra todo lo namespaced que hay adentro; lo de nivel cluster (nodos, labels de nodo, taints, ClusterRoles, PVs) sobrevive.
  • A pod has 30 s of terminationGracePeriodSeconds by default: $now skips them. In the exam, when you delete to redo, those seconds add up.
  • Deleting the namespace removes everything namespaced inside; cluster-scoped things (nodes, node labels, taints, ClusterRoles, PVs) survive.
  • Un pod ha 30 s di terminationGracePeriodSeconds di default: $now li salta. All'esame, quando cancelli per rifare, quei secondi si sommano.
  • Cancellare il namespace elimina tutto ciò che è namespaced al suo interno; le cose a livello cluster (nodi, label dei nodi, taint, ClusterRole, PV) sopravvivono.

Autoevaluación — antes de pasar al Módulo 1

Self-check — before moving on to Module 1

Autovalutazione — prima di passare al Modulo 1

  • Dejar la terminal lista (aliases + completion + vim) en menos de un minuto.
  • Crear pod, deploy, service, cm, secret, job, cronjob y headless sin mirar apuntes.
  • Generar con $do, editar y aplicar sin romper la indentación.
  • Saber de memoria qué NO tiene flag imperativo.
  • Usar -o wide, api-resources y explain --recursive como reflejo.
  • Get the terminal ready (aliases + completion + vim) in under a minute.
  • Create pod, deploy, service, cm, secret, job, cronjob and headless without notes.
  • Generate with $do, edit and apply without breaking indentation.
  • Know by heart what has no imperative flag.
  • Reach for -o wide, api-resources and explain --recursive by reflex.
  • Preparare il terminale (alias + completion + vim) in meno di un minuto.
  • Creare pod, deploy, service, cm, secret, job, cronjob e headless senza appunti.
  • Generare con $do, modificare e applicare senza rompere l'indentazione.
  • Sapere a memoria cosa non ha un flag imperativo.
  • Usare -o wide, api-resources ed explain --recursive per riflesso.
Módulo 0 completado · La base de velocidad está puesta · Siguiente: kubeadm y el control plane
Module 0 complete · The speed foundation is in place · Next: kubeadm and the control plane
Modulo 0 completato · La base di velocità è posata · Prossimo: kubeadm e il control plane