CKA · Módulo 2CKA · Module 2CKA · Modulo 2K8s v1.34parte de Cluster Arch 25%part of Cluster Arch 25%parte di Cluster Arch 25%
RBAC y seguridad del cluster
RBAC and cluster security
RBAC e sicurezza del cluster
Quién puede hacer qué, y cómo. El módulo que más confunde por su vocabulario, pero que se vuelve simple con un solo modelo mental: QUIÉN + QUÉ, conectados por un BINDING.
Who can do what, and how. The module whose vocabulary confuses most, yet which becomes simple with a single mental model: WHO + WHAT, connected by a BINDING.
Chi può fare cosa, e come. Il modulo che confonde di più per il suo vocabolario, ma che diventa semplice con un solo modello mentale: CHI + COSA, connessi da un BINDING.
Duración60 min
Duration60 min
Durata60 min
PrerequisitoMódulo 1 (API server)
PrerequisiteModule 1 (API server)
PrerequisitoModulo 1 (API server)
DificultadMedia-alta
DifficultyMedium-high
DifficoltàMedio-alta
Cae en examenSeguido
Exam frequencyOften
Frequenza d'esameSpesso
RBAC (Role-Based Access Control) controla quién puede hacer qué contra el API server. Suena complejo por los cuatro objetos con nombres parecidos (Role, ClusterRole, RoleBinding, ClusterRoleBinding), pero todos encajan en un modelo simple. Lo bueno: ya tenés la base del Módulo 1 — sabés que todo pasa por el API server. RBAC es justamente el portero que decide qué dejás pasar.
RBAC (Role-Based Access Control) governs who can do what against the API server. It sounds complex because of the four similarly named objects (Role, ClusterRole, RoleBinding, ClusterRoleBinding), but they all fit one simple model. The good news: you have the Module 1 foundation — you know everything goes through the API server. RBAC is precisely the doorman deciding what gets through.
RBAC (Role-Based Access Control) governa chi può fare cosa contro l'API server. Sembra complesso per i quattro oggetti dai nomi simili (Role, ClusterRole, RoleBinding, ClusterRoleBinding), ma stanno tutti in un modello semplice. La buona notizia: hai le basi del Modulo 1 — sai che tutto passa dall'API server. RBAC è proprio il portiere che decide cosa lasciar passare.
El modelo mental que resuelve todo RBAC
The mental model that solves all of RBAC
Il modello mentale che risolve tutto RBAC
QUIÉN
WHO
CHI
Subject
User, Group o ServiceAccount. La identidad que quiere hacer algo.
User, Group or ServiceAccount. The identity that wants to do something.
User, Group o ServiceAccount. L'identità che vuole fare qualcosa.
+
QUÉ
WHAT
COSA
Role / ClusterRole
Un conjunto de permisos: qué verbos (get, create...) sobre qué recursos.
A set of permissions: which verbs (get, create...) on which resources.
Un insieme di permessi: quali verbi (get, create...) su quali risorse.
=
CONECTADOS POR
CONNECTED BY
CONNESSI DA
Binding
RoleBinding o ClusterRoleBinding. Le da el QUÉ al QUIÉN.
RoleBinding or ClusterRoleBinding. It gives the WHAT to the WHO.
RoleBinding o ClusterRoleBinding. Dà il COSA al CHI.
Un permiso solo "existe" cuando un Binding conecta un Subject (quién) con un Role (qué). El Role sin Binding no hace nada. El Binding es el pegamento.
A permission only "exists" when a Binding connects a Subject (who) to a Role (what). A Role with no Binding does nothing. The Binding is the glue.
Un permesso "esiste" solo quando un Binding collega un Subject (chi) a un Role (cosa). Un Role senza Binding non fa nulla. Il Binding è la colla.
2.1
Roles & ClusterRoles
El QUÉ: definir permisos. Namespaced vs cluster-wide.
The WHAT: defining permissions. Namespaced vs cluster-wide.
Il COSA: definire permessi. Namespaced contro cluster-wide.
2.2
RoleBindings & ClusterRoleBindings
El pegamento: conectar permisos con identidades. Las combinaciones válidas.
The glue: connecting permissions to identities. The valid combinations.
La colla: collegare permessi a identità. Le combinazioni valide.
2.3
ServiceAccounts
La identidad de los pods. Cómo se vincula al pod.
The identity of pods. How it attaches to a pod.
L'identità dei pod. Come si lega al pod.
2.4
auth can-i
Verificar permisos. Tu herramienta de diagnóstico de RBAC.
Verifying permissions. Your RBAC diagnostic tool.
Verificare i permessi. Il tuo strumento diagnostico RBAC.
Contexts, users, clusters. How kubectl knows who you are.
Context, user, cluster. Come kubectl sa chi sei.
★
Práctica · 9 ejercicios
Practice · 9 exercises
Pratica · 9 esercizi
El trío canónico, las 4 combinaciones, SA en pods, can-i y un Forbidden real.
The canonical trio, the 4 combinations, SAs in pods, can-i and a real Forbidden.
Il trio canonico, le 4 combinazioni, SA nei pod, can-i e un Forbidden vero.
2.1
El QUÉ · 20 min
The WHAT · 20 min
Il COSA · 20 min
Roles & ClusterRoles
Definen permisos. La diferencia es el alcance: un namespace vs todo el cluster.
They define permissions. The difference is scope: one namespace vs the whole cluster.
Definiscono permessi. La differenza è l'ambito: un namespace contro l'intero cluster.
Práctica · Crear permisos
Practice · Creating permissions
Pratica · Creare permessi
Role — permisos en UN namespace
Role — permissions in ONE namespace
Role — permessi in UN namespace
# Imperativo: role que puede ver pods en el ns actual# Imperative: a role that can view pods in the current ns# Imperativo: un role che può vedere i pod nel ns correntek create role pod-reader \
--verb=get,list,watch \
--resource=pods
# Con $do para ver el YAML# With $do to see the YAML# Con $do per vedere lo YAMLk create role pod-reader \
--verb=get,list,watch --resource=pods $do
ClusterRole — permissions across the WHOLE cluster
ClusterRole — permessi su TUTTO il cluster
# Mismo formato, pero sin namespace (es cluster-wide)# Same shape, but no namespace (it is cluster-wide)# Stessa forma, ma senza namespace (è cluster-wide)k create clusterrole node-reader \
--verb=get,list,watch \
--resource=nodes $do
★
El apiGroups: [""] (string vacío) es el "core group" — pods, services, configmaps, etc. Para otros recursos cambia: apps (deployments), rbac.authorization.k8s.io (roles), etc. Si no sabés el group, k api-resources te lo dice.
apiGroups: [""] (empty string) is the "core group" — pods, services, configmaps, etc. Other resources differ: apps (deployments), rbac.authorization.k8s.io (roles), etc. If you do not know the group, k api-resources tells you.
apiGroups: [""] (stringa vuota) è il "core group" — pod, service, configmap, ecc. Per altre risorse cambia: apps (deployment), rbac.authorization.k8s.io (role), ecc. Se non sai il gruppo, k api-resources te lo dice.
Teoría · El alcance
Theory · Scope
Teoria · L'ambito
Role vs ClusterRole
Role vs ClusterRole
Role contro ClusterRole
Role
ClusterRole
Role
ClusterRole
Role
ClusterRole
Alcance
1 namespace
Todo el cluster
Scope
1 namespace
Whole cluster
Ambito
1 namespace
Tutto il cluster
Tiene namespace
Sí
No
Has a namespace
Yes
No
Ha un namespace
Sì
No
Para recursos
Namespaced (pods, etc.)
Namespaced O cluster-scoped (nodes, PVs)
For resources
Namespaced (pods, etc.)
Namespaced OR cluster-scoped (nodes, PVs)
Per risorse
Namespaced (pod, ecc.)
Namespaced O cluster-scoped (node, PV)
Las 3 partes de un rule
The 3 parts of a rule
Le 3 parti di una rule
apiGroups: a qué grupo de API pertenece el recurso
resources: qué recursos (pods, deployments...)
verbs: qué acciones (get, list, create...)
apiGroups: which API group the resource belongs to
resources: which resources (pods, deployments...)
verbs: which actions (get, list, create...)
apiGroups: a quale gruppo API appartiene la risorsa
Un Role/ClusterRole por sí solo no le da permisos a nadie. Es solo una definición de permisos "flotando". Recién sirve cuando un Binding la conecta a un Subject (sección 2.2).
A Role/ClusterRole on its own grants nobody anything. It is just a permission definition floating there. It only counts once a Binding connects it to a Subject (section 2.2).
Un Role/ClusterRole da solo non concede nulla a nessuno. È solo una definizione di permessi che fluttua. Vale solo quando un Binding la collega a un Subject (sezione 2.2).
2.2
El pegamento · 15 min
The glue · 15 min
La colla · 15 min
RoleBindings & ClusterRoleBindings
Conectan el QUIÉN con el QUÉ. Acá vive la lógica que más confunde.
They connect the WHO with the WHAT. This is where the most confusing logic lives.
Collegano il CHI al COSA. Qui vive la logica che confonde di più.
Práctica · Conectar
Practice · Connecting
Pratica · Collegare
RoleBinding — da permisos en UN namespace
RoleBinding — grants in ONE namespace
RoleBinding — concede in UN namespace
# Darle el role 'pod-reader' al usuario 'juan'# Give the 'pod-reader' role to user 'juan'# Dare il role 'pod-reader' all'utente 'juan'k create rolebinding juan-pods \
--role=pod-reader \
--user=juan $do
# A un ServiceAccount en vez de user:# To a ServiceAccount instead of a user:# A un ServiceAccount invece che a un utente:k create rolebinding sa-pods \
--role=pod-reader \
--serviceaccount=default:miapp $do
ClusterRoleBinding — da permisos en TODO el cluster
ClusterRoleBinding — grants across the WHOLE cluster
ClusterRoleBinding — concede su TUTTO il cluster
k create clusterrolebinding juan-nodes \
--clusterrole=node-reader \
--user=juan $do
El patrón útil: ClusterRole + RoleBinding
The useful pattern: ClusterRole + RoleBinding
Il pattern utile: ClusterRole + RoleBinding
# Definís el permiso UNA vez como ClusterRole,# You define the permission ONCE as a ClusterRole,# Definisci il permesso UNA volta come ClusterRole,# y lo aplicás en namespaces específicos con RoleBinding# and apply it in specific namespaces with a RoleBinding# e lo applichi in namespace specifici con un RoleBindingk create rolebinding juan-en-dev \
--clusterrole=pod-reader \
--user=juan \
--namespace=dev $do
★
El patrón ClusterRole + RoleBinding es muy común: definís permisos reutilizables una vez (ClusterRole) y los otorgás namespace por namespace (RoleBinding). Evita duplicar Roles idénticos en cada namespace.
The ClusterRole + RoleBinding pattern is very common: you define reusable permissions once (ClusterRole) and grant them namespace by namespace (RoleBinding). It avoids duplicating identical Roles everywhere.
Il pattern ClusterRole + RoleBinding è molto comune: definisci permessi riutilizzabili una volta (ClusterRole) e li concedi namespace per namespace (RoleBinding). Evita di duplicare Role identici ovunque.
Teoría · Las combinaciones
Theory · The combinations
Teoria · Le combinazioni
La tabla que tenés que saber de memoria
The table you must know by heart
La tabella da sapere a memoria
Binding
Referencia a
¿Válido?
Binding
References
Valid?
Binding
Referenzia
Valido?
RoleBinding
Role
SÍ
RoleBinding
Role
YES
RoleBinding
Role
SÌ
RoleBinding
ClusterRole
SÍ
RoleBinding
ClusterRole
YES
RoleBinding
ClusterRole
SÌ
ClusterRoleBinding
ClusterRole
SÍ
ClusterRoleBinding
ClusterRole
YES
ClusterRoleBinding
ClusterRole
SÌ
ClusterRoleBinding
Role
NO
ClusterRoleBinding
Role
NO
ClusterRoleBinding
Role
NO
La regla en palabras
The rule in words
La regola a parole
Un RoleBinding puede apuntar a un Role O a un ClusterRole (en ambos casos, los permisos aplican solo en SU namespace).
Un ClusterRoleBinding solo puede apuntar a un ClusterRole (nunca a un Role).
A RoleBinding can point at a Role OR a ClusterRole (either way, permissions apply only in ITS namespace).
A ClusterRoleBinding can point only at a ClusterRole (never a Role).
Un RoleBinding può puntare a un Role O a un ClusterRole (in entrambi i casi i permessi valgono solo nel SUO namespace).
Un ClusterRoleBinding può puntare solo a un ClusterRole (mai a un Role).
Por qué ClusterRoleBinding → Role no existe
Why ClusterRoleBinding → Role does not exist
Perché ClusterRoleBinding → Role non esiste
Un Role está atado a un namespace. Un ClusterRoleBinding es cluster-wide. No tiene sentido lógico otorgar cluster-wide algo que solo existe en un namespace. Por eso K8s no lo permite.
A Role is tied to a namespace. A ClusterRoleBinding is cluster-wide. Granting cluster-wide something that only exists in one namespace makes no logical sense. So K8s forbids it.
Un Role è legato a un namespace. Un ClusterRoleBinding è cluster-wide. Concedere cluster-wide qualcosa che esiste solo in un namespace non ha senso logico. Perciò K8s lo vieta.
★
El alcance lo define el Binding, no el Role. Un ClusterRole usado con un RoleBinding queda limitado a ese namespace. El "Cluster" en ClusterRole es solo la definición; el alcance real lo decide el binding.
Scope is defined by the Binding, not the Role. A ClusterRole used with a RoleBinding is confined to that namespace. The "Cluster" in ClusterRole is only about the definition; the real scope is the binding's call.
L'ambito lo definisce il Binding, non il Role. Un ClusterRole usato con un RoleBinding resta confinato a quel namespace. Il "Cluster" in ClusterRole riguarda solo la definizione; l'ambito reale lo decide il binding.
🗺️
Tarjeta de referencia · las combinaciones resueltas
Reference card · the combinations, resolved
Scheda di riferimento · le combinazioni, risolte
El role es el QUÉ · el binding es el DÓNDE
The role is the WHAT · the binding is the WHERE
Il role è il COSA · il binding è il DOVE
Dos ejes independientes: dónde se DEFINE el permiso vs dónde APLICA.
Two independent axes: where the permission is DEFINED vs where it APPLIES.
Due assi indipendenti: dove il permesso è DEFINITO contro dove si APPLICA.
Eje 1 — el ROLE (el QUÉ)
Axis 1 — the ROLE (the WHAT)
Asse 1 — il ROLE (il COSA)
Role: permisos definidos en 1 namespace, solo recursos namespaced. ClusterRole: definición cluster-wide; cubre namespaced y cluster-scoped (nodes, PV).
Role: permissions defined in 1 namespace, namespaced resources only. ClusterRole: a cluster-wide definition; covers namespaced and cluster-scoped (nodes, PV).
Role: permessi definiti in 1 namespace, solo risorse namespaced. ClusterRole: definizione cluster-wide; copre namespaced e cluster-scoped (node, PV).
Eje 2 — el BINDING (el DÓNDE aplica)
Axis 2 — the BINDING (WHERE it applies)
Asse 2 — il BINDING (DOVE si applica)
RoleBinding: el permiso aplica en 1 namespace (el suyo). ClusterRoleBinding: el permiso aplica en todo el cluster.
RoleBinding: the permission applies in 1 namespace (its own). ClusterRoleBinding: the permission applies across the whole cluster.
RoleBinding: il permesso si applica in 1 namespace (il suo). ClusterRoleBinding: il permesso si applica su tutto il cluster.
① Role + RoleBinding
Permiso en UN namespace
Permission in ONE namespace
Permesso in UN namespace
k create role pod-reader \
--verb=get,list,watch --resource=pods -n dev
k create rolebinding juan-pods \
--role=pod-reader --user=juan -n dev
vive: Role y Binding en dev · aplica: solo dev
lives: Role and Binding in dev · applies: dev only
vive: Role e Binding in dev · si applica: solo dev
El caso más común: permiso puntual en un namespace.
The most common case: a targeted permission in one namespace.
Il caso più comune: un permesso puntuale in un namespace.
② ClusterRole + RoleBinding
Definición reutilizable, ACOTADA a un namespace
Reusable definition, CONFINED to one namespace
Definizione riutilizzabile, LIMITATA a un namespace
k create clusterrole pod-reader \
--verb=get,list,watch --resource=pods # sin -n# no -n# senza -nk create rolebinding juan-pods \
--clusterrole=pod-reader --user=juan -n dev
vive: ClusterRole cluster-wide, Binding en dev · aplica: solo dev
lives: ClusterRole cluster-wide, Binding in dev · applies: dev only
vive: ClusterRole cluster-wide, Binding in dev · si applica: solo dev
Reusar 1 definición en varios ns (1 RoleBinding por ns). El "Cluster" NO implica alcance total.
Reuse 1 definition across several ns (1 RoleBinding per ns). "Cluster" does NOT imply total reach.
Riusare 1 definizione in più ns (1 RoleBinding per ns). "Cluster" NON implica portata totale.
③ ClusterRole + ClusterRoleBinding
Permiso en TODO el cluster
Permission across the WHOLE cluster
Permesso su TUTTO il cluster
k create clusterrole node-reader \
--verb=get,list,watch --resource=nodes # sin -n# no -n# senza -nk create clusterrolebinding juan-nodes \
--clusterrole=node-reader --user=juan # sin -n# no -n# senza -n
vive: todo cluster-wide · aplica: todos los ns + recursos cluster-scoped
lives: all cluster-wide · applies: every ns + cluster-scoped resources
vive: tutto cluster-wide · si applica: ogni ns + risorse cluster-scoped
Recursos cluster-scoped (nodes, PV) o permisos globales (admin, monitoreo).
Cluster-scoped resources (nodes, PV) or global permissions (admin, monitoring).
Risorse cluster-scoped (node, PV) o permessi globali (admin, monitoraggio).
④ Role + ClusterRoleBinding
❌ No existe
❌ Does not exist
❌ Non esiste
k create clusterrolebinding x --role=...
# el flag --role NO existe: solo --clusterrole# the --role flag does NOT exist: only --clusterrole# il flag --role NON esiste: solo --clusterrole
Un ClusterRoleBinding nunca referencia un Role: no se puede otorgar cluster-wide algo que solo vive en un namespace.
A ClusterRoleBinding never references a Role: you cannot grant cluster-wide something that lives in one namespace only.
Un ClusterRoleBinding non referenzia mai un Role: non puoi concedere cluster-wide qualcosa che vive solo in un namespace.
★
El derrame de los dos namespaces (SA como subject): en un RoleBinding con un ServiceAccount hay DOS namespaces que responden preguntas distintas. El -n del binding = dónde APLICA el permiso. El <ns>: de --serviceaccount=<ns>:nombre = dónde VIVE el SA (su identidad). Pueden coincidir o no. Un --user no lleva ns (los usuarios no son namespaced); un SA sí, siempre.
The two-namespace spill (SA as subject): in a RoleBinding with a ServiceAccount there are TWO namespaces answering different questions. The binding's -n = where the permission APPLIES. The <ns>: in --serviceaccount=<ns>:name = where the SA LIVES (its identity). They may or may not match. A --user carries no ns (users are not namespaced); an SA always does.
Il travaso dei due namespace (SA come subject): in un RoleBinding con un ServiceAccount ci sono DUE namespace che rispondono a domande diverse. Il -n del binding = dove il permesso SI APPLICA. Il <ns>: di --serviceaccount=<ns>:nome = dove VIVE il SA (la sua identità). Possono coincidere o no. Un --user non porta ns (gli utenti non sono namespaced); un SA sì, sempre.
⚠
El -n del RoleBinding no es opcional: es el límite de seguridad. Si lo omitís, el binding cae en tu namespace actual y el permiso aplica donde no querías (el objeto se crea igual → "parece que anduvo"). Y los nombres de objetos namespaced son únicos por namespace, no globalmente.
The RoleBinding's -n is not optional: it is the security boundary. Omit it and the binding lands in your current namespace, granting where you did not intend (the object is created either way → "looks like it worked"). And names of namespaced objects are unique per namespace, not globally.
Il -n del RoleBinding non è opzionale: è il confine di sicurezza. Se lo ometti, il binding finisce nel tuo namespace corrente e concede dove non volevi (l'oggetto viene creato comunque → "sembra aver funzionato"). E i nomi degli oggetti namespaced sono unici per namespace, non globalmente.
Los dos roles conceden lo mismo: get,list sobre pods y nodes. Lo único que cambia es el tipo de objeto.
Both roles grant the same thing: get,list on pods and nodes. The only difference is the object kind.
I due role concedono la stessa cosa: get,list su pods e nodes. L'unica differenza è il tipo di oggetto.
2.3
Identidad de pods · 15 min
Pod identity · 15 min
Identità dei pod · 15 min
ServiceAccounts
Los users son para humanos; los ServiceAccounts son para pods.
Users are for humans; ServiceAccounts are for pods.
Gli user sono per gli umani; i ServiceAccount sono per i pod.
Práctica · SA y pods
Practice · SAs and pods
Pratica · SA e pod
Crear y usar un ServiceAccount
Creating and using a ServiceAccount
Creare e usare un ServiceAccount
# Crear un SA# Create an SA# Creare un SAk create serviceaccount miapp
# Ver los SA del namespace# List the namespace's SAs# Elencare gli SA del namespacek get serviceaccounts
# Siempre existe uno llamado 'default'# There is always one called 'default'# Ne esiste sempre uno chiamato 'default'
Asignar el SA a un pod
Assigning the SA to a pod
Assegnare il SA a un pod
# En el YAML del pod:# In the pod YAML:# Nello YAML del pod:spec:
serviceAccountName: miapp
containers:
- name: app
image: nginx
Imperativo: setear el SA de un deployment
Imperative: set a deployment's SA
Imperativo: impostare il SA di un deployment
k set serviceaccount deployment/web miapp
Darle permisos al SA (combina todo)
Granting the SA permissions (it all comes together)
Dare permessi al SA (mette insieme tutto)
# El SA es el SUBJECT del binding# The SA is the binding's SUBJECT# Il SA è il SUBJECT del bindingk create rolebinding miapp-pods \
--role=pod-reader \
--serviceaccount=default:miapp $do
⚠
Si no asignás un SA a un pod, usa el default del namespace, que normalmente NO tiene permisos. Si tu app necesita hablar con el API server, creale un SA con los permisos justos.
If you do not assign an SA to a pod, it uses the namespace's default, which normally has NO permissions. If your app must talk to the API server, give it an SA with exactly the permissions it needs.
Se non assegni un SA a un pod, usa il default del namespace, che normalmente NON ha permessi. Se la tua app deve parlare con l'API server, dalle un SA con esattamente i permessi necessari.
Teoría · Por qué existen
Theory · Why they exist
Teoria · Perché esistono
User vs ServiceAccount
User vs ServiceAccount
User contro ServiceAccount
User
ServiceAccount
User
ServiceAccount
User
ServiceAccount
Para
Humanos
Pods / procesos
For
Humans
Pods / processes
Per
Umani
Pod / processi
Lo gestiona K8s
No (externo)
Sí (objeto del cluster)
Managed by K8s
No (external)
Yes (a cluster object)
Gestito da K8s
No (esterno)
Sì (oggetto del cluster)
Tiene namespace
No
Sí
Has a namespace
No
Yes
Ha un namespace
No
Sì
Se crea con kubectl
No
Sí
Created with kubectl
No
Yes
Si crea con kubectl
No
Sì
El dato clave
The key fact
Il dato chiave
Kubernetes no tiene objetos User. Los usuarios vienen de afuera (certificados, OIDC, etc.). Pero los ServiceAccounts SÍ son objetos que creás y gestionás con kubectl.
Kubernetes has no User objects. Users come from outside (certificates, OIDC, etc.). But ServiceAccounts ARE objects you create and manage with kubectl.
Kubernetes non ha oggetti User. Gli utenti vengono da fuori (certificati, OIDC, ecc.). Ma i ServiceAccount SONO oggetti che crei e gestisci con kubectl.
Cómo se nombra un SA en un binding
How an SA is named in a binding
Come si nomina un SA in un binding
Formato: namespace:nombre. Por eso --serviceaccount=default:miapp significa "el SA llamado miapp en el namespace default".
Format: namespace:name. That is why --serviceaccount=default:miapp means "the SA called miapp in the default namespace".
Formato: namespace:nome. Per questo --serviceaccount=default:miapp significa "il SA chiamato miapp nel namespace default".
★
El token del SA se monta automáticamente en el pod (en /var/run/secrets/kubernetes.io/serviceaccount/). El pod lo usa para autenticarse contra el API server.
The SA token is mounted into the pod automatically (at /var/run/secrets/kubernetes.io/serviceaccount/). The pod uses it to authenticate against the API server.
Il token del SA viene montato automaticamente nel pod (in /var/run/secrets/kubernetes.io/serviceaccount/). Il pod lo usa per autenticarsi contro l'API server.
2.4
Diagnóstico · 10 min
Diagnosis · 10 min
Diagnosi · 10 min
kubectl auth can-i
Tu herramienta para verificar permisos sin prueba y error.
Your tool for verifying permissions without trial and error.
Il tuo strumento per verificare i permessi senza tentativi.
Práctica · Verificar
Practice · Verifying
Pratica · Verificare
¿Puedo hacer X?
Can I do X?
Posso fare X?
# ¿Puedo crear deployments?# Can I create deployments?# Posso creare deployment?k auth can-i create deployments
# ¿Puedo borrar pods en el ns kube-system?# Can I delete pods in the kube-system ns?# Posso cancellare pod nel ns kube-system?k auth can-i delete pods -n kube-system
# Respuesta: yes / no# Answer: yes / no# Risposta: yes / no
¿Puede OTRO hacer X? (impersonation)
Can SOMEONE ELSE do X? (impersonation)
Può QUALCUN ALTRO fare X? (impersonation)
# ¿El usuario juan puede listar pods?# Can user juan list pods?# L'utente juan può elencare i pod?k auth can-i list pods --as juan
# ¿El SA miapp puede crear services?# Can the miapp SA create services?# Il SA miapp può creare service?k auth can-i create services \
--as=system:serviceaccount:default:miapp
Ver TODO lo que puede alguien
See EVERYTHING someone can do
Vedere TUTTO ciò che qualcuno può fare
k auth can-i --list --as juan
★
El --as (impersonation) es clave en el examen: te piden "verificá que el usuario X puede/no puede hacer Y". En vez de loguearte como X, impersonás con --as. Para un SA el formato es system:serviceaccount:NS:NOMBRE.
--as (impersonation) is key in the exam: you get asked to "verify that user X can/cannot do Y". Instead of logging in as X, you impersonate with --as. For an SA the format is system:serviceaccount:NS:NAME.
--as (impersonation) è chiave all'esame: ti chiedono di "verificare che l'utente X possa/non possa fare Y". Invece di autenticarti come X, impersoni con --as. Per un SA il formato è system:serviceaccount:NS:NOME.
Teoría · Cómo razonar
Theory · How to reason
Teoria · Come ragionare
El flujo de diagnóstico de RBAC
The RBAC diagnostic flow
Il flusso diagnostico RBAC
Cuando algo "no tiene permisos" (como tu Forbidden del Módulo 1), el camino es:
When something "has no permissions" (like your Forbidden from Module 1), the path is:
Quando qualcosa "non ha permessi" (come il tuo Forbidden del Modulo 1), il percorso è:
auth can-i para confirmar qué falta
Buscar el Role/ClusterRole que debería tener el permiso
Buscar el Binding que conecta al subject
Si falta el binding o el permiso en el role, lo agregás
auth can-i to confirm what is missing
Find the Role/ClusterRole that should hold the permission
Find the Binding connecting the subject
If the binding or the permission in the role is missing, add it
auth can-i per confermare cosa manca
Trovare il Role/ClusterRole che dovrebbe avere il permesso
Trovare il Binding che collega il subject
Se manca il binding o il permesso nel role, lo aggiungi
Formato del subject SA
SA subject format
Formato del subject SA
Un ServiceAccount como subject en impersonation o en bindings se escribe completo: system:serviceaccount:<ns>:<nombre>
A ServiceAccount as a subject in impersonation or bindings is written in full: system:serviceaccount:<ns>:<name>
Un ServiceAccount come subject in impersonation o nei binding si scrive per intero: system:serviceaccount:<ns>:<nome>
★
El auth can-i --list es oro para diagnosticar: te muestra el mapa completo de permisos de un subject, sin adivinar.
auth can-i --list is gold for diagnosis: it shows a subject's full permission map, no guessing.
auth can-i --list è oro per la diagnosi: mostra la mappa completa dei permessi di un subject, senza indovinare.
2.5
Identidad · 15 min
Identity · 15 min
Identità · 15 min
Certificados y kubeconfig
Certificates and kubeconfig
Certificati e kubeconfig
Cómo kubectl sabe quién sos y a qué cluster apuntás.
How kubectl knows who you are and which cluster you point at.
Come kubectl sa chi sei e a quale cluster punti.
Práctica · Contexts
Practice · Contexts
Pratica · Context
Ver y cambiar contexts
Viewing and switching contexts
Vedere e cambiare context
# Ver el context actual# Show the current context# Mostrare il context correntek config current-context
# Listar todos los contexts# List all contexts# Elencare tutti i contextk config get-contexts
# Cambiar de context# Switch context# Cambiare contextk config use-context <nombre>
# Ver el kubeconfig completo# View the whole kubeconfig# Vedere l'intero kubeconfigk config view
Cambiar el namespace por defecto del context
Changing the context's default namespace
Cambiare il namespace predefinito del context
k config set-context --current --namespace=dev
# Ahora todos los comandos van al ns 'dev' sin -n# Now every command goes to ns 'dev' without -n# Ora ogni comando va nel ns 'dev' senza -n
★
En el examen, cambiar de cluster/context es frecuente: cada tarea puede pedir un cluster distinto. El k config use-context es de los comandos que más vas a tipear. Y el --namespace en el context te ahorra poner -n en cada comando.
In the exam, switching cluster/context is frequent: each task may ask for a different cluster. k config use-context is among the commands you will type most. And --namespace on the context saves you a -n on every command.
All'esame cambiare cluster/context è frequente: ogni task può richiedere un cluster diverso. k config use-context è fra i comandi che digiterai di più. E --namespace sul context ti risparmia un -n a ogni comando.
Teoría · Las 3 piezas
Theory · The 3 pieces
Teoria · I 3 pezzi
El kubeconfig tiene 3 secciones
A kubeconfig has 3 sections
Un kubeconfig ha 3 sezioni
Sección
Qué define
Section
What it defines
Sezione
Cosa definisce
clusters
A qué API server (URL + CA)
clusters
Which API server (URL + CA)
clusters
Quale API server (URL + CA)
users
Quién sos (cert/token/credenciales)
users
Who you are (cert/token/credentials)
users
Chi sei (cert/token/credenziali)
contexts
Combina cluster + user + namespace
contexts
Combines cluster + user + namespace
contexts
Combina cluster + user + namespace
El context es el "perfil activo"
The context is the "active profile"
Il context è il "profilo attivo"
Un context dice: "usá ESTE user para hablar con ESTE cluster en ESTE namespace". Cambiar de context = cambiar de identidad y/o destino de un saque.
A context says: "use THIS user to talk to THIS cluster in THIS namespace". Switching context = changing identity and/or destination in one move.
Un context dice: "usa QUESTO user per parlare con QUESTO cluster in QUESTO namespace". Cambiare context = cambiare identità e/o destinazione in un colpo solo.
Dónde vive
Where it lives
Dove vive
Por defecto en ~/.kube/config (el que copiaste con admin.conf en el Módulo 1). La variable KUBECONFIG puede apuntar a otro.
By default at ~/.kube/config (the one you copied from admin.conf in Module 1). The KUBECONFIG variable can point elsewhere.
Di default in ~/.kube/config (quello che hai copiato da admin.conf nel Modulo 1). La variabile KUBECONFIG può puntare altrove.
★
Conecta con el Módulo 1: el admin.conf que copiaste a ~/.kube/config ES un kubeconfig. Tiene el cluster (tu API server), el user (admin con su cert), y un context que los une. Por eso al copiarlo, kubectl supo quién sos y a dónde conectarte.
This ties back to Module 1: the admin.conf you copied to ~/.kube/config IS a kubeconfig. It has the cluster (your API server), the user (admin with its cert), and a context joining them. That is why, once copied, kubectl knew who you were and where to connect.
Si ricollega al Modulo 1: l'admin.conf che hai copiato in ~/.kube/config È un kubeconfig. Ha il cluster (il tuo API server), l'user (admin col suo cert), e un context che li unisce. Per questo, una volta copiato, kubectl sapeva chi eri e dove connettersi.
★
Cierre del módulo
Module wrap-up
Chiusura del modulo
Lo que te llevás del Módulo 2
What you take from Module 2
Cosa porti via dal Modulo 2
Resumen · Comandos clave
Summary · Key commands
Riassunto · Comandi chiave
# Crear permisos (el QUÉ)# Create permissions (the WHAT)# Creare permessi (il COSA)k create role NAME --verb=get,list --resource=pods $do
k create clusterrole NAME --verb=... --resource=nodes $do
# Conectar (el pegamento)# Connect (the glue)# Collegare (la colla)k create rolebinding NAME --role=R --user=U $do
k create clusterrolebinding NAME --clusterrole=CR --user=U $do
# ServiceAccount (identidad de pods)# ServiceAccount (pod identity)# ServiceAccount (identità dei pod)k create serviceaccount NAME
k create rolebinding NAME --role=R \
--serviceaccount=NS:SA $do
# Verificar permisos# Verify permissions# Verificare i permessik auth can-i VERB RESOURCE --as USER
k auth can-i --list --as USER
# Contextsk config use-context NAME
k config set-context --current --namespace=NS
Teoría · Lo esencial
Theory · The essentials
Teoria · L'essenziale
Las 4 ideas que no se negocian
The 4 non-negotiable ideas
Le 4 idee non negoziabili
QUIÉN + QUÉ + BINDING. El Role define permisos; el Binding los otorga a un subject.
Role/RoleBinding = 1 namespace. ClusterRole/ClusterRoleBinding = todo el cluster.
RoleBinding puede usar un ClusterRole (queda scoped al ns). ClusterRoleBinding NUNCA usa un Role.
SA = identidad de pods. Users = humanos (externos). SA = objetos del cluster.
WHO + WHAT + BINDING. The Role defines permissions; the Binding grants them to a subject.
Role/RoleBinding = 1 namespace. ClusterRole/ClusterRoleBinding = the whole cluster.
A RoleBinding can use a ClusterRole (scoped to the ns). A ClusterRoleBinding NEVER uses a Role.
SA = pod identity. Users = humans (external). SAs = cluster objects.
CHI + COSA + BINDING. Il Role definisce i permessi; il Binding li concede a un subject.
Role/RoleBinding = 1 namespace. ClusterRole/ClusterRoleBinding = tutto il cluster.
Un RoleBinding può usare un ClusterRole (limitato al ns). Un ClusterRoleBinding NON usa MAI un Role.
SA = identità dei pod. User = umani (esterni). SA = oggetti del cluster.
★
Si te trabás con RBAC, volvé siempre al modelo del principio: ¿quién (subject)? ¿qué permiso (role)? ¿están conectados (binding)? El 90% de los problemas es que falta el binding o el role no tiene el verbo correcto.
When RBAC stalls you, always return to the model at the top: who (subject)? which permission (role)? are they connected (binding)? 90% of problems are a missing binding or a role without the right verb.
Se ti blocchi con RBAC, torna sempre al modello iniziale: chi (subject)? quale permesso (role)? sono collegati (binding)? Il 90% dei problemi è un binding mancante o un role senza il verbo giusto.
Checkpoint Módulo 2: modelo QUIÉN+QUÉ+BINDING claro, combinaciones de bindings memorizadas, SA entendidos, auth can-i y contexts dominados. Siguiente: Módulo 3 — Helm, Kustomize y CRDs.
Module 2 checkpoint: the WHO+WHAT+BINDING model clear, binding combinations memorised, SAs understood, auth can-i and contexts owned. Next: Module 3 — Helm, Kustomize and CRDs.
Checkpoint Modulo 2: modello CHI+COSA+BINDING chiaro, combinazioni di binding memorizzate, SA compresi, auth can-i e context padroneggiati. Prossimo: Modulo 3 — Helm, Kustomize e CRD.
★
Fase 2 · resolver en vivo
Phase 2 · solve it live
Fase 2 · risolvere dal vivo
Práctica — 9 ejercicios
Practice — 9 exercises
Pratica — 9 esercizi
~5 min cada uno: el ritmo del examen. No abras la solución hasta intentarlo.
~5 min each: exam pace. Do not open the solution until you have tried.
~5 min ciascuno: il ritmo dell'esame. Non aprire la soluzione prima di provare.
0 / 9
🧠
Modelo mental. QUIÉN (subject) + QUÉ (Role/ClusterRole) = conectados por un BINDING. El Role sin binding no hace nada. Y RBAC es aditivo: solo tenés lo que algún binding te otorgó explícitamente — no existen reglas de negación.
Mental model. WHO (subject) + WHAT (Role/ClusterRole) = connected by a BINDING. A Role with no binding does nothing. And RBAC is additive: you only have what some binding explicitly granted — there are no deny rules.
Modello mentale. CHI (subject) + COSA (Role/ClusterRole) = connessi da un BINDING. Un Role senza binding non fa nulla. E RBAC è additivo: hai solo ciò che un binding ti ha concesso esplicitamente — non esistono regole di negazione.
◆
Preparación. Estos ejercicios no rompen el cluster, así que no hace falta snapshot. Sí hacen falta namespaces: k create ns dev staging prod pipeline. Para limpiar entre reps, etiquetá lo que creás con ej=rbac y borralo: k delete role,clusterrole,rolebinding,clusterrolebinding,sa -l ej=rbac -A --ignore-not-found.
Setup. These exercises do not break the cluster, so no snapshot is needed. Namespaces are: k create ns dev staging prod pipeline. To clean between reps, label what you create with ej=rbac and delete it: k delete role,clusterrole,rolebinding,clusterrolebinding,sa -l ej=rbac -A --ignore-not-found.
Preparazione. Questi esercizi non rompono il cluster, quindi non serve snapshot. Servono i namespace: k create ns dev staging prod pipeline. Per pulire fra le rep, etichetta ciò che crei con ej=rbac e cancellalo: k delete role,clusterrole,rolebinding,clusterrolebinding,sa -l ej=rbac -A --ignore-not-found.
E1
El binding básico (SA + Role + RoleBinding)
The basic binding (SA + Role + RoleBinding)
Il binding di base (SA + Role + RoleBinding)
~5 min
En el namespace default, creá un ServiceAccount llamado tester. Creá un Role svc-reader que permita get, list y watch sobre services. Otorgale ese role al SA tester con un RoleBinding llamado tester-svc. Verificá que tester puede listar services pero no puede listar pods.
Es el patrón canónico de RBAC — que te salga sin pensar.
In the default namespace, create a ServiceAccount called tester. Create a Role svc-reader allowing get, list and watch on services. Grant that role to the tester SA with a RoleBinding called tester-svc. Verify tester can list services but cannot list pods.
This is the canonical RBAC pattern — it should come out without thinking.
Nel namespace default, crea un ServiceAccount chiamato tester. Crea un Role svc-reader che permetta get, list e watch sui services. Concedi quel role al SA tester con un RoleBinding chiamato tester-svc. Verifica che tester possa elencare i service ma non i pod.
È il pattern canonico di RBAC — deve uscirti senza pensare.
Ver soluciónShow solutionMostra soluzione
# QUIÉN# WHO# CHIk create serviceaccount tester
# QUÉ# WHAT# COSAk create role svc-reader --verb=get,list,watch --resource=services
# BINDING (pegamento): conecta el QUIÉN con el QUÉ# BINDING (the glue): connects the WHO to the WHAT# BINDING (la colla): collega il CHI al COSAk create rolebinding tester-svc --role=svc-reader --serviceaccount=default:tester
# VERIFICAR (impersonando al SA)# VERIFY (impersonating the SA)# VERIFICARE (impersonando il SA)k auth can-i list services --as=system:serviceaccount:default:tester # yesk auth can-i list pods --as=system:serviceaccount:default:tester # no
Claves
Key points
Punti chiave
El SA como subject se escribe completo: system:serviceaccount:<ns>:<nombre>.
El role solo cubre services, así que pods da no: el permiso que no otorgás, no existe.
Tres objetos, tres comandos. Si te sale en menos de 2 minutos sin mirar, este patrón ya es tuyo.
An SA as a subject is written in full: system:serviceaccount:<ns>:<name>.
The role only covers services, so pods returns no: a permission you do not grant does not exist.
Three objects, three commands. If it takes under 2 minutes from memory, this pattern is yours.
Un SA come subject si scrive per intero: system:serviceaccount:<ns>:<nome>.
Il role copre solo i services, quindi pods dà no: un permesso che non concedi non esiste.
Tre oggetti, tre comandi. Se ti riesce in meno di 2 minuti a memoria, questo pattern è tuo.
E2
La trampa: ClusterRoleBinding → Role
The trap: ClusterRoleBinding → Role
La trappola: ClusterRoleBinding → Role
~5 min
Tenés el Role svc-reader (namespaced, del E1). Querés dárselo al usuario juana nivel de todo el cluster con un ClusterRoleBinding. Intentalo. ¿Qué pasa y por qué? Después, lográ el objetivo real ("juan puede leer services en el namespace dev") de la forma correcta.
You have the svc-reader Role (namespaced, from E1). You want to give it to user juanacross the whole cluster with a ClusterRoleBinding. Try it. What happens and why? Then achieve the real goal ("juan can read services in the dev namespace") the correct way.
Hai il Role svc-reader (namespaced, dall'E1). Vuoi darlo all'utente juansu tutto il cluster con un ClusterRoleBinding. Provaci. Cosa succede e perché? Poi raggiungi l'obiettivo vero ("juan può leggere i service nel namespace dev") nel modo giusto.
Ver soluciónShow solutionMostra soluzione
No se puede, y el propio kubectl te lo impide:create clusterrolebinding solo tiene el flag --clusterrole, no existe --role. Un ClusterRoleBinding nunca referencia un Role.
It cannot be done, and kubectl itself stops you:create clusterrolebinding only has the --clusterrole flag; --role does not exist. A ClusterRoleBinding never references a Role.
Non si può, e kubectl stesso te lo impedisce:create clusterrolebinding ha solo il flag --clusterrole; --role non esiste. Un ClusterRoleBinding non referenzia mai un Role.
# la forma correcta: ClusterRole (reutilizable) + RoleBinding (acotado)# the correct way: ClusterRole (reusable) + RoleBinding (scoped)# il modo giusto: ClusterRole (riutilizzabile) + RoleBinding (limitato)k create clusterrole svc-reader-cr --verb=get,list,watch --resource=services
k create rolebinding juan-svc-dev --clusterrole=svc-reader-cr --user=juan -n dev
# el alcance lo pone el BINDING, no el ClusterRole:# scope comes from the BINDING, not the ClusterRole:# l'ambito lo dà il BINDING, non il ClusterRole:k auth can-i list services --as=juan -n dev # yesk auth can-i list services --as=juan -n default # no
Claves
Key points
Punti chiave
Por qué: un Role vive atado a un namespace; un ClusterRoleBinding es cluster-wide. Otorgar cluster-wide algo que solo existe en un namespace no tiene sentido, así que la API lo prohíbe.
Idea que no se negocia: el "Cluster" en ClusterRole es solo la definición; el alcance real lo decide el binding.
Además el CRB acá habría sido un over-grant: pedían dev, no todo el cluster.
Why: a Role is tied to a namespace; a ClusterRoleBinding is cluster-wide. Granting cluster-wide something that exists in one namespace makes no sense, so the API forbids it.
Non-negotiable idea: the "Cluster" in ClusterRole is only the definition; the real scope is the binding's call.
Besides, a CRB here would have been an over-grant: dev was asked for, not the whole cluster.
Perché: un Role è legato a un namespace; un ClusterRoleBinding è cluster-wide. Concedere cluster-wide qualcosa che esiste in un namespace non ha senso, perciò l'API lo vieta.
Idea non negoziabile: il "Cluster" in ClusterRole è solo la definizione; l'ambito reale lo decide il binding.
Inoltre qui un CRB sarebbe stato un over-grant: chiedevano dev, non tutto il cluster.
E3
Misma trampa, pero el subject es un ServiceAccount
Same trap, but the subject is a ServiceAccount
Stessa trappola, ma il subject è un ServiceAccount
~5 min
En el namespace pipeline existe el ServiceAccount runner. Reutilizando el ClusterRole secret-reader (ya existe: get,list,watch sobre secrets), hacé que runner pueda leer los secrets solo en pipeline. No crees ningún Role nuevo.
Criterio:get secrets --as=system:serviceaccount:pipeline:runner → yes en pipeline, no en default.
In the pipeline namespace the ServiceAccount runner exists. Reusing the secret-reader ClusterRole (already there: get,list,watch on secrets), make runner able to read secrets only in pipeline. Create no new Role.
Criterion:get secrets --as=system:serviceaccount:pipeline:runner → yes in pipeline, no in default.
Nel namespace pipeline esiste il ServiceAccount runner. Riutilizzando il ClusterRole secret-reader (già presente: get,list,watch sui secrets), fai in modo che runner possa leggere i secret solo in pipeline. Non creare nessun Role nuovo.
Criterio:get secrets --as=system:serviceaccount:pipeline:runner → yes in pipeline, no in default.
Ver soluciónShow solutionMostra soluzione
k create rolebinding runner-secrets \
--clusterrole=secret-reader --serviceaccount=pipeline:runner -n pipeline
k auth can-i get secrets --as=system:serviceaccount:pipeline:runner -n pipeline # yesk auth can-i get secrets --as=system:serviceaccount:pipeline:runner -n default # no
Claves
Key points
Punti chiave
Mismo patrón que E2 (ClusterRole + RoleBinding acotado); cambia solo el subject.
Un SA se pasa con --serviceaccount=<ns>:<nombre> en el binding y se impersona con --as=system:serviceaccount:<ns>:<nombre>. Dos sintaxis para lo mismo — memorizá las dos.
El alcance lo sigue poniendo el RoleBinding, que vive en pipeline.
Same pattern as E2 (ClusterRole + scoped RoleBinding); only the subject changes.
An SA is passed as --serviceaccount=<ns>:<name> in the binding and impersonated as --as=system:serviceaccount:<ns>:<name>. Two syntaxes for the same thing — memorise both.
Scope still comes from the RoleBinding, which lives in pipeline.
Stesso pattern dell'E2 (ClusterRole + RoleBinding limitato); cambia solo il subject.
Un SA si passa come --serviceaccount=<ns>:<nome> nel binding e si impersona come --as=system:serviceaccount:<ns>:<nome>. Due sintassi per la stessa cosa — memorizzale entrambe.
L'ambito continua a darlo il RoleBinding, che vive in pipeline.
E4
Cuándo el ClusterRoleBinding SÍ corresponde
When a ClusterRoleBinding IS the right call
Quando il ClusterRoleBinding È la scelta giusta
~5 min
El usuario ops tiene que poder listar nodes en todo el cluster. Logralo. Después respondé: ¿podrías haber acotado esto a un solo namespace con un RoleBinding? ¿Por qué no?
User ops must be able to list nodes across the whole cluster. Make it happen. Then answer: could you have confined this to a single namespace with a RoleBinding? Why not?
L'utente ops deve poter elencare i nodes su tutto il cluster. Fallo. Poi rispondi: avresti potuto limitarlo a un solo namespace con un RoleBinding? Perché no?
Ver soluciónShow solutionMostra soluzione
k create clusterrole node-viewer --verb=get,list,watch --resource=nodes
k create clusterrolebinding ops-nodes --clusterrole=node-viewer --user=ops
k auth can-i list nodes --as=ops # yes (nodes no vive en ningún namespace)# yes (nodes lives in no namespace)# yes (nodes non vive in alcun namespace)
Claves
Key points
Punti chiave
nodes es un recurso cluster-scoped — no pertenece a ningún namespace. Un RoleBinding solo gobierna recursos de su namespace, así que no hay forma de acotarlo.
Para recursos cluster-scoped el único binding válido es el ClusterRoleBinding.
Contraste con E2: acá el CRB no es over-grant (es la única opción); allá sí lo era, porque services es namespaced y existía la alternativa acotada.
nodes is a cluster-scoped resource — it belongs to no namespace. A RoleBinding governs only resources in its namespace, so there is no way to confine it.
For cluster-scoped resources the only valid binding is the ClusterRoleBinding.
Contrast with E2: here the CRB is not an over-grant (it is the only option); there it was, because services is namespaced and the scoped alternative existed.
nodes è una risorsa cluster-scoped — non appartiene a nessun namespace. Un RoleBinding governa solo risorse del suo namespace, quindi non c'è modo di limitarlo.
Per le risorse cluster-scoped l'unico binding valido è il ClusterRoleBinding.
Contrasto con E2: qui il CRB non è un over-grant (è l'unica opzione); là lo era, perché services è namespaced ed esisteva l'alternativa limitata.
E5
Un ClusterRole, dos namespaces (y un tercero que no)
One ClusterRole, two namespaces (and a third that stays out)
Un ClusterRole, due namespace (e un terzo che resta fuori)
~5 min
El usuario dev-lead tiene que poder listar services en devy en staging, pero no en prod. Reutilizá un solo ClusterRole (svc-reader-cr, del E2).
User dev-lead must be able to list services in devandstaging, but not in prod. Reuse a single ClusterRole (svc-reader-cr, from E2).
L'utente dev-lead deve poter elencare i services in deve in staging, ma non in prod. Riutilizza un solo ClusterRole (svc-reader-cr, dall'E2).
Ver soluciónShow solutionMostra soluzione
k create rolebinding devlead-svc --clusterrole=svc-reader-cr --user=dev-lead -n dev
k create rolebinding devlead-svc --clusterrole=svc-reader-cr --user=dev-lead -n staging
k auth can-i list services --as=dev-lead -n dev # yesk auth can-i list services --as=dev-lead -n staging # yesk auth can-i list services --as=dev-lead -n prod # no
Claves
Key points
Punti chiave
Un RoleBinding gobierna un namespace: dos namespaces = dos RoleBindings.
Los dos bindings pueden tener el mismo nombre: los objetos namespaced son únicos por namespace, no globalmente.
prod no tiene binding, así que queda afuera: el ClusterRole por sí solo no otorga nada hasta que un binding lo activa en un namespace concreto.
A RoleBinding governs one namespace: two namespaces = two RoleBindings.
Both bindings can share the same name: namespaced objects are unique per namespace, not globally.
prod has no binding, so it stays out: a ClusterRole alone grants nothing until a binding activates it in a concrete namespace.
Un RoleBinding governa un namespace: due namespace = due RoleBinding.
I due binding possono avere lo stesso nome: gli oggetti namespaced sono unici per namespace, non globalmente.
prod non ha binding, quindi resta fuori: un ClusterRole da solo non concede nulla finché un binding non lo attiva in un namespace concreto.
E6
El SA que usa un pod
The SA a pod actually uses
Il SA che un pod usa davvero
~5 min
Creá un ServiceAccount reader-sa. Creá un pod probe (imagen nginx) que use ese SA. Verificá desde el objeto pod que quedó asignado (no el default).
Create a ServiceAccount reader-sa. Create a pod probe (image nginx) that uses that SA. Verify from the pod object that it stuck (not the default).
Crea un ServiceAccount reader-sa. Crea un pod probe (immagine nginx) che usi quel SA. Verifica dall'oggetto pod che sia stato assegnato (non il default).
Ver soluciónShow solutionMostra soluzione
k create serviceaccount reader-sa
# generá el pod y agregá serviceAccountName (el imperativo no tiene flag)# generate the pod and add serviceAccountName (no imperative flag exists)# genera il pod e aggiungi serviceAccountName (non esiste un flag imperativo)k run probe --image=nginx $do > probe.yaml
vim probe.yaml # bajo spec: serviceAccountName: reader-sa# under spec: serviceAccountName: reader-sa# sotto spec: serviceAccountName: reader-sak apply -f probe.yaml
k get pod probe -o jsonpath='{.spec.serviceAccountName}' # reader-sa
Claves
Key points
Punti chiave
serviceAccountName va en spec: del pod, al mismo nivel que containers:.
No hay flag imperativo para un pod — es de los casos de "generá y editá" del M0.
Para un deployment ya existente sí lo hay: k set serviceaccount deployment/web reader-sa.
serviceAccountName goes under the pod's spec:, at the same level as containers:.
There is no imperative flag for a pod — one of M0's "generate and edit" cases.
For an existing deployment there is one: k set serviceaccount deployment/web reader-sa.
serviceAccountName va sotto spec: del pod, allo stesso livello di containers:.
Non esiste un flag imperativo per un pod — è uno dei casi "genera e modifica" del M0.
Per un deployment esistente sì: k set serviceaccount deployment/web reader-sa.
E7
Del pod al permiso (encadenar todo)
From pod to permission (chaining it all)
Dal pod al permesso (concatenare tutto)
~5 min
El SA reader-sa del E6 debe poder leer configmaps (get, list) solo en el namespace default. Otorgale el permiso y verificá como el SA. Extra: confirmá que NO puede crearlos.
The reader-sa SA from E6 must be able to read configmaps (get, list) only in the default namespace. Grant the permission and verify as the SA. Extra: confirm it CANNOT create them.
Il SA reader-sa dell'E6 deve poter leggere le configmap (get, list) solo nel namespace default. Concedi il permesso e verifica come il SA. Extra: conferma che NON può crearle.
Ver soluciónShow solutionMostra soluzione
k create role cm-reader --verb=get,list --resource=configmaps
k create rolebinding reader-sa-cm --role=cm-reader --serviceaccount=default:reader-sa
k auth can-i list configmaps --as=system:serviceaccount:default:reader-sa # yesk auth can-i create configmaps --as=system:serviceaccount:default:reader-sa # no
Claves
Key points
Punti chiave
configmaps es del core group (apiGroups: [""]), como pods y services.
El verbo create no está en el role → no. RBAC es aditivo: solo tenés lo que algún binding te otorga explícitamente.
Encadenaste las tres piezas del módulo: un SA que usa un pod, un Role, y el binding que los une.
configmaps is in the core group (apiGroups: [""]), like pods and services.
The create verb is not in the role → no. RBAC is additive: you only have what a binding explicitly grants.
You chained the module's three pieces: an SA a pod uses, a Role, and the binding joining them.
configmaps è nel core group (apiGroups: [""]), come pod e service.
Il verbo create non è nel role → no. RBAC è additivo: hai solo ciò che un binding concede esplicitamente.
Hai concatenato i tre pezzi del modulo: un SA usato da un pod, un Role, e il binding che li unisce.
E8
Diagnóstico rápido con auth can-i · y kubeconfig
Fast diagnosis with auth can-i · and kubeconfig
Diagnosi rapida con auth can-i · e kubeconfig
~5 min
Sin crear nada nuevo, un comando por respuesta: (1) ¿vos podés borrar pods en kube-system? (2) ¿juan puede listar services en dev? (3) mostrá el mapa completo de lo que puede hacer el SA tester. (4) Mostrá el context actual y listá todos. (5) Cambiá el namespace por defecto de tu context a dev. (6) Explicá con tus palabras las 3 secciones de un kubeconfig.
Without creating anything new, one command per answer: (1) can you delete pods in kube-system? (2) can juan list services in dev? (3) show the full map of what the tester SA can do. (4) Show the current context and list them all. (5) Change your context's default namespace to dev. (6) Explain in your own words the 3 sections of a kubeconfig.
Senza creare nulla di nuovo, un comando per risposta: (1) puoi cancellare pod in kube-system? (2) juan può elencare i service in dev? (3) mostra la mappa completa di ciò che può fare il SA tester. (4) Mostra il context corrente ed elencali tutti. (5) Cambia il namespace predefinito del tuo context a dev. (6) Spiega a parole tue le 3 sezioni di un kubeconfig.
Ver soluciónShow solutionMostra soluzione
k auth can-i delete pods -n kube-system # 1 yes (sos admin)# 1 yes (you are admin)# 1 yes (sei admin)k auth can-i list services --as=juan -n dev # 2 yesk auth can-i --list --as=system:serviceaccount:default:tester # 3 tabla de permisos# 3 permission table# 3 tabella dei permessik config current-context
k config get-contexts
k config set-context --current --namespace=dev
# para volver: k config set-context --current --namespace=default# to go back: k config set-context --current --namespace=default# per tornare: k config set-context --current --namespace=default
Claves
Key points
Punti chiave
--as impersona sin tener que loguearte como ese subject; auth can-i --list es la radiografía completa. Es el paso 1 de todo diagnóstico de RBAC.
clusters = a qué API server apuntás (URL + CA). users = quién sos (cert/token). contexts = el perfil activo: cluster + user + namespace.
En el examen cada tarea puede pedir un cluster distinto: k config use-context es de los comandos que más vas a tipear.
--as impersonates without logging in as that subject; auth can-i --list is the full X-ray. It is step 1 of every RBAC diagnosis.
clusters = which API server you point at (URL + CA). users = who you are (cert/token). contexts = the active profile: cluster + user + namespace.
In the exam each task may want a different cluster: k config use-context is among the commands you type most.
--as impersona senza autenticarti come quel subject; auth can-i --list è la radiografia completa. È il passo 1 di ogni diagnosi RBAC.
clusters = a quale API server punti (URL + CA). users = chi sei (cert/token). contexts = il profilo attivo: cluster + user + namespace.
All'esame ogni task può volere un cluster diverso: k config use-context è fra i comandi che digiterai di più.
T1
Troubleshooting — el pod con Forbidden
Troubleshooting — the pod with Forbidden
Troubleshooting — il pod con Forbidden
~6 min
Una app corre con el SA app-sa en default y en sus logs aparece:
Error: pods is forbidden: User "system:serviceaccount:default:app-sa" cannot list resource "pods"
Diagnosticá por qué y arreglalo para que el SA pueda listar pods. Prepararlo:k create sa app-sa.
An app runs with the app-sa SA in default and its logs show:
Error: pods is forbidden: User "system:serviceaccount:default:app-sa" cannot list resource "pods"
Diagnose why and fix it so the SA can list pods. To set it up:k create sa app-sa.
Un'app gira con il SA app-sa in default e nei log compare:
Error: pods is forbidden: User "system:serviceaccount:default:app-sa" cannot list resource "pods"
Diagnostica perché e sistemalo così che il SA possa elencare i pod. Per prepararlo:k create sa app-sa.
Ver soluciónShow solutionMostra soluzione
# 1 · confirmar qué falta# 1 · confirm what is missing# 1 · confermare cosa mancak auth can-i list pods --as=system:serviceaccount:default:app-sa # no# 2 · ver el mapa: ¿tiene algún permiso?# 2 · see the map: does it have any permission at all?# 2 · vedere la mappa: ha qualche permesso?k auth can-i --list --as=system:serviceaccount:default:app-sa # casi nada# almost nothing# quasi nulla# 3 · diagnóstico: no hay Role con list pods, ni Binding que conecte al SA# 3 · diagnosis: no Role with list pods, and no Binding connecting the SA# 3 · diagnosi: nessun Role con list pods, né Binding che colleghi il SA# 4 · arreglar# 4 · fix# 4 · sistemarek create role pod-reader --verb=get,list,watch --resource=pods
k create rolebinding app-sa-pods --role=pod-reader --serviceaccount=default:app-sa
# 5 · reverificar# 5 · re-verify# 5 · riverificarek auth can-i list pods --as=system:serviceaccount:default:app-sa # yes
Claves
Key points
Punti chiave
El error es un dato, no un obstáculo: el mensaje te da el subject completo y el recurso. Ya sabés qué preguntarle a can-i.
El 90% de los "Forbidden" de RBAC es falta el binding o el role no tiene el verbo/recurso correcto.
Volvé siempre al modelo: ¿quién? ¿qué permiso? ¿están conectados? Y reverificá siempre al final.
The error is data, not an obstacle: the message hands you the full subject and the resource. You already know what to ask can-i.
90% of RBAC "Forbidden" is a missing binding or a role without the right verb/resource.
Always return to the model: who? which permission? are they connected? And always re-verify at the end.
L'errore è un dato, non un ostacolo: il messaggio ti dà il subject completo e la risorsa. Sai già cosa chiedere a can-i.
Il 90% dei "Forbidden" di RBAC è un binding mancante o un role senza il verbo/risorsa giusti.
Torna sempre al modello: chi? quale permesso? sono collegati? E riverifica sempre alla fine.
Autoevaluación — antes de marcar M2 como ★ dominado
Self-check — before marking M2 as ★ mastered
Autovalutazione — prima di segnare M2 come ★ padroneggiato
Escribir el trío SA + Role + RoleBinding de memoria en menos de 2 min.
Explicar por qué ClusterRoleBinding → Role no existe.
Elegir entre RoleBinding y ClusterRoleBinding sabiendo si el recurso es namespaced o cluster-scoped.
Reutilizar un ClusterRole en varios namespaces con RoleBindings.
Asignar un SA a un pod y saber dónde va el campo.
Verificar permisos de cualquier subject con --as y --as … --list.
Diagnosticar un Forbidden desde el mensaje hasta el fix.
Cambiar context y namespace por defecto.
Write the SA + Role + RoleBinding trio from memory in under 2 min.
Explain why ClusterRoleBinding → Role does not exist.
Choose between RoleBinding and ClusterRoleBinding knowing whether the resource is namespaced or cluster-scoped.
Reuse a ClusterRole across several namespaces with RoleBindings.
Assign an SA to a pod and know where the field goes.
Verify any subject's permissions with --as and --as … --list.
Diagnose a Forbidden from the message all the way to the fix.
Switch context and default namespace.
Scrivere il trio SA + Role + RoleBinding a memoria in meno di 2 min.
Spiegare perché ClusterRoleBinding → Role non esiste.
Scegliere fra RoleBinding e ClusterRoleBinding sapendo se la risorsa è namespaced o cluster-scoped.
Riutilizzare un ClusterRole in più namespace con RoleBinding.
Assegnare un SA a un pod e sapere dove va il campo.
Verificare i permessi di qualsiasi subject con --as e --as … --list.
Diagnosticare un Forbidden dal messaggio fino al fix.
Cambiare context e namespace predefinito.
Módulo 2 completado · Quién puede hacer qué, resuelto · Siguiente: Helm, Kustomize y CRDs
Module 2 complete · Who can do what, resolved · Next: Helm, Kustomize and CRDs
Modulo 2 completato · Chi può fare cosa, risolto · Prossimo: Helm, Kustomize e CRD