RBAC questions are easy points when your mental model is exact, and brutal time sinks when it's fuzzy. Secrets are the other half of the competency, where the real craft isn't the Secret object itself but the three sanctioned ways to keep plaintext out of git.
make up secmake gitopsOrientation
Every Forbidden error you'll ever hit (inside a workflow node, an operator log, a CI job, or an exam task) breaks down into the same four pieces: subject, verb, resource, and namespace. Learn to read that error line cleanly and half this domain answers itself.
A request arrives authenticated as a subject with a set of groups. Every RBAC rule is strictly an allow; there is no deny rule anywhere in Kubernetes RBAC. Your effective permissions are simply the union of every matching rule, and anything not matched is forbidden. That's why debugging RBAC is always "find the missing rule or missing binding", never "find what blocked me".
The RBAC model
| Object | Scope | Contains |
|---|---|---|
| Role | One namespace | Rules: apiGroups × resources × verbs (+ optional resourceNames) |
| ClusterRole | Cluster-wide definition | The same, plus cluster-scoped resources and non-resource URLs |
| RoleBinding | Grants in one namespace | Subjects + a roleRef to a Role or a ClusterRole |
| ClusterRoleBinding | Grants everywhere | Subjects + a roleRef to a ClusterRole |
A RoleBinding can reference a ClusterRole, granting its rules inside that one namespace only. That's how you define a "developer" role once and bind it per tenant. A ClusterRoleBinding grants access everywhere and is almost always the wrong default. Whenever a task's final check says "and they must not have access in another namespace", that check is specifically hunting for a ClusterRoleBinding.
Four combinations of role and binding, and where each one grants access:
Subjects
Users and Groups are asserted by your authentication layer (client certificates, OIDC claims, proxy headers) rather than stored as API objects. That's why you can bind to dev-a even though no dev-a object exists in the cluster, and why --as=dev-a works out of the box for testing. ServiceAccounts are real objects, and they're how software gets identity: system:serviceaccount:<ns>:<name>, automatically placed in group system:serviceaccounts:<ns>. Every controller log yelling Forbidden traces back to a ServiceAccount missing a rule.
Modern ServiceAccount tokens are short-lived, audience-bound, and mounted as projected volumes instead of the old forever-Secrets. That same identity also underpins workload identity (section 5.5's SPIFFE IDs are built right from the SA name). Setting automountServiceAccountToken: false on pods that never talk to the API server is a cheap, meaningful hardening win.
Verbs and rules, the details that decide tasks
get,list, andwatchare separate verbs. A dashboard listing pods needslist, and a controller needswatchtoo. Granting onlygetand wondering whykubectl get pods(plural) fails is a classic trap.- Subresources have their own resource strings:
pods/exec,pods/log,pods/portforward,deployments/scale,*/status. Allowing log reads while blockingexecis easy to express and makes a great tenant default. resourceNamesnarrows a rule to specific named objects, which is how you allow editing a single ConfigMap. Keep in mind it can't restrictcreateordeletecollection, and a plainlistorwatchonly succeeds if paired with a matchingmetadata.namefield selector.- Wildcards (
*) exist, and least privilege says to avoid them.escalateandbindare special verbs that let someone grant permissions they don't hold themselves; treat both as admin-only. - Aggregated ClusterRoles (
aggregationRulewith label selectors) let the built-inview,edit, andadminroles absorb new CRDs automatically. Label your ClusterRolerbac.authorization.k8s.io/aggregate-to-view: "true"and every viewer immediately gets read access to your new kind. That's the right platform-engineering move whenever you ship a CRD. - Built-in roles to know by heart:
view(read-only, no Secrets),edit(read/write, no RBAC),admin(edit plus managing RBAC in that namespace), andcluster-admin(everything).
kubectl auth can-i <verb> <resource> --as=<user> -n <ns>
kubectl auth can-i --list --as=system:serviceaccount:<ns>:<sa> -n <ns>outputcaptured 2026-11-18
$ kubectl auth can-i create deployments --as=dev-a -n team-a
yes
$ kubectl auth can-i --list --as=system:serviceaccount:team-a:reporter -n team-a
Resources Non-Resource URLs Resource Names Verbs
selfsubjectreviews.authentication.k8s.io [] [] [create]
selfsubjectaccessreviews.authorization.k8s.io [] [] [create]
selfsubjectrulesreviews.authorization.k8s.io [] [] [create]
clustertrustbundles.certificates.k8s.io [] [] [get list watch]
pods [] [] [get list]
[/.well-known/openid-configuration/] [] [get]
[/.well-known/openid-configuration] [] [get]
[/api/*] [] [get]
[/api] [] [get]
[/apis/*] [] [get]
[/apis] [] [get]
[/healthz] [] [get]
[/healthz] [] [get]
[/livez] [] [get]
[/livez] [] [get]
[/openapi/*] [] [get]
[/openapi] [] [get]
[/openid/v1/jwks/] [] [get]
[/openid/v1/jwks] [] [get]
[/readyz] [] [get]
[/readyz] [] [get]
[/version/] [] [get]
[/version/] [] [get]
[/version] [] [get]
[/version] [] [get]End every RBAC task with one of these as proof. --list is the one that catches surprises: it prints the full effective matrix, including permissions inherited from group bindings you forgot existed.
RBAC edges that decide tasks
Verbs and rules people get wrong
- Escalation prevention. You can only create or update a Role if you already hold every permission it grants, or hold the
escalateverb onroles/clusterroles. Similarly, you can only create a binding if you hold those permissions or hold thebindverb on that role (optionally narrowed withresourceNames). Otherwise you getattempt to grant extra privileges. A tenant admin who "cannot bind the view role" needsbindon that one ClusterRole, notcluster-admin. impersonateonusers,groups,serviceaccounts(anduserextras) powerskubectl --asand--as-group. Onlycluster-adminholds it by default, so a tenant who wants to test their own SA with--asneeds it granted explicitly.kubectl auth whoami(theSelfSubjectReviewAPI) prints the exact username, UID, groups, and extra attributes the API server sees after authentication. Reach for it first whenever an OIDC user or workload gets Forbidden and you aren't sure what identity actually arrived: prefixes, group names, and impersonation all show up right there.nonResourceURLs(/metrics,/healthz,/logs/*) only work in ClusterRoles. A scraper hitting the API server's/metricsneedsgeton that URL, and wildcards act as suffix globs.- Default ClusterRoles.
viewreads most namespaced objects, excluding Secrets, Roles, and RoleBindings.editadds writes, and less obviously, lets you read and write Secrets and launch pods as any ServiceAccount in the namespace, which makes it too broad for many developers.adminadds Role and RoleBinding management inside that namespace, andcluster-adminunlocks everything. All four aggregate labeled roles (rbac.authorization.k8s.io/aggregate-to-view|edit|admin). Meanwhile,system:authenticatedinheritssystem:basic-userandsystem:discovery; ifsystem:unauthenticatedcan read discovery, check for thesystem:public-info-viewerbinding. - Auto-reconciliation. Built-in roles and bindings reset on API server restart unless annotated with
rbac.authorization.kubernetes.io/autoupdate: "false". Any direct edit toviewgets overwritten, which is why aggregation exists. Runkubectl auth reconcile -f rbac.yamlto apply RBAC manifests additively and see what changed. kubectl create roleshortcuts. Use--verb=get,list --resource=pods,pods/log,--resource=deployments.appsfor group-qualified resources,--resource-name=xfor named objects, andkubectl create clusterrole --aggregation-rule=.... Generating and inspecting the YAML beats writing it from scratch under exam pressure.
Identity mechanics
- Tokens. Pods receive a projected token (
serviceAccountTokenwithexpirationSecondsandaudience) that the kubelet refreshes via theTokenRequestAPI; it's bound to that pod and dies with it. Usekubectl create token <sa> --duration=1hto mint one for scripts, or add--bound-object-kind Pod --bound-object-name xto bind it to an object. Long-lived Secret tokens stopped being auto-created in 1.24 and get cleaned up when unused. If a task says "the CI system needs a token", reach forkubectl create token, and only create an explicitkubernetes.io/service-account-tokenSecret if a non-expiring token is genuinely required. SetautomountServiceAccountToken: falseon the pod or SA to drop the mount completely. - OIDC. Legacy flags are
--oidc-issuer-url,--oidc-client-id,--oidc-username-claim(defaultsub),--oidc-username-prefix,--oidc-groups-claim, and--oidc-groups-prefix. The modern structured form is anAuthenticationConfigurationfile passed via--authentication-config, supporting multiple issuers withjwt[].issuer.url/audiences,claimMappings.username.claim|prefix,claimMappings.groups.claim|prefix, and CELclaimValidationRules. Remember that groups arrive with their prefix attached (likeoidc:platform-team), so binding to bareplatform-teamsilently matches nobody;kubectl auth whoamireveals the exact string. - Built-in groups you get for free.
system:serviceaccounts(every SA),system:serviceaccounts:<ns>(one namespace),system:masters(bypasses RBAC entirely, so never put a real user in it), andsystem:nodes.
Expect three flavors: "user X can do Y in namespace Z and nothing else", "the CI ServiceAccount can submit workflows and read their status", and "why does user X still get Forbidden when a binding exists?" (usually prefixes, group names, a Role in the wrong namespace, or resourceNames paired with list). Close every one with kubectl auth can-i --as and, for real identities, kubectl auth whoami.
Secrets: the controls half
A stock Kubernetes Secret is just base64, not encryption. Anyone who can get secrets in that namespace has the plaintext, and so does anyone with etcd access unless you've turned on encryption at rest on the API server (EncryptionConfiguration, optionally backed by a KMS). That gives you three non-negotiable habits: never hand out get secrets lightly, prefer short-lived projected tokens over static credentials, and never let a plain Secret near git.
| Approach | What git holds | Who can decrypt | Good for |
|---|---|---|---|
| Sealed Secrets | Ciphertext (a SealedSecret CR) | Only the in-cluster controller's private key | Self-contained clusters with no external secret store |
| External Secrets (ESO) | A reference (SecretStore + ExternalSecret) | Whoever the backing store authorizes | Environments where Vault or a cloud secret manager is already the source of truth |
| SOPS | Partially encrypted YAML | Holders of the age, PGP, or KMS key | Flux-native repos where reviewable diffs matter |
Be ready to state the core distinction crisply: Sealed Secrets stores encrypted data in git, whereas ESO stores only pointers in git while the external store holds truth and handles rotation outside your repo. Both keep plaintext out of version control, but only ESO gives you centralized rotation and audit trails.
ESO's object model, since it's the one you're most likely to meet
SecretStore(namespaced) orClusterSecretStore(cluster-wide, referenced withkind: ClusterSecretStore) defines where secrets live and how to authenticate: a provider block (vault, aws, gcp, azure, kubernetes, orfakefor practice) plus credentials, typically a ServiceAccount token or Secret ref.ExternalSecretdefines what to materialize:secretStoreRef, arefreshInterval, and either explicitdata[]mappings (remote key → local key) ordataFromto pull a whole path. Usetarget.nameto name the generated Secret,target.creationPolicyto control ownership, andtarget.templateto assemble structured outputs like config files or connection strings instead of raw key-value pairs.- Check the
SecretSyncedstatus condition: when syncing fails, the message usually points straight to the store, a missing key, or an auth error, in that order of likelihood. PushSecretreverses the flow for the rarer case where the cluster itself is the source of truth.
What the exam tests here mirrors the rest of this domain: inspect the CRD, wire the two objects together, and verify the materialized Secret itself rather than stopping at a green apply.
Every sealed value is encrypted for one specific controller and (by default) one specific namespace and name. Rebuild the cluster without restoring that controller's private key and every SealedSecret in git turns into unreadable noise, so back up the sealing key like production data.
Secrets: the fields and formats
Encryption at rest
Pass an EncryptionConfiguration (apiserver.config.k8s.io/v1) via --encryption-provider-config listing resources[] (such as secrets, configmaps, CRDs like externalsecrets.external-secrets.io, or wildcards like *.*) and an ordered providers[] list. The first provider encrypts new writes while all listed providers can decrypt, which dictates the rotation sequence: place the new key first, restart the API server, rewrite every object (kubectl get secrets -A -o json | kubectl replace -f -), and only then drop the old key. Available providers are identity (plaintext; the default if unconfigured), aescbc, aesgcm (must rotate every 200k writes), secretbox, and kms with apiVersion: v2 talking to an external KMS plugin over a Unix socket (v1 is deprecated). Wildcards require 1.27+ and custom resources 1.26+. Reading raw etcd shows prefixes like k8s:enc:aescbc:v1:key1: once encryption is active.
External Secrets Operator, the decisive fields
apiVersion: external-secrets.io/v1
kind: ExternalSecret
metadata: { name: db, namespace: team-a }
spec:
secretStoreRef: { name: vault, kind: ClusterSecretStore }
refreshPolicy: Periodic # CreatedOnce | Periodic (default) | OnChange
refreshInterval: 1h # 0 means create once, never update
target:
name: db-credentials
creationPolicy: Owner # Owner | Orphan | Merge | None
deletionPolicy: Retain # Retain | Delete | Merge
template:
engineVersion: v2
data:
DSN: "postgres://{{ .username }}:{{ .password }}@db:5432/app"
data:
- secretKey: username
remoteRef: { key: team-a/db, property: username }
dataFrom:
- extract: { key: team-a/db } # every property becomes a keyrefreshPolicy:Periodicsyncs everyrefreshIntervaland on spec edits;OnChangesyncs only when theExternalSecretitself changes;CreatedOncefetches once per object (recreating the ExternalSecret triggers a fresh pull, so pair it withtarget.immutable: truefor credentials nothing should overwrite in place). Need an immediate refresh? Runkubectl annotate es x force-sync=$(date +%s).creationPolicy:Owner(ESO owns the Secret and deletes it with the ExternalSecret),Orphan(leaves it behind),Merge(injects keys into an existing Secret you own), orNone(never creates a Secret).deletionPolicycontrols what happens to the Secret if the remote key disappears.dataFrom.extractunpacks an entire JSON object into keys,dataFrom.findmatches by path regex or tags, andrewriterenames keys.template(engine v2, Go templates with Sprig) builds full config files and DSNs,templateFrompulls templates from a ConfigMap, andmergePolicy: Mergekeeps raw keys alongside the templated ones.- Scoping:
SecretStoreis namespaced, whileClusterSecretStorecan restrict which namespaces may use it viaconditions[].namespaceSelectorornamespaces.ClusterExternalSecretstamps one ExternalSecret across every namespace matchingnamespaceSelectors, andPushSecretpushes cluster Secrets back to an external store withupdatePolicy: Replace|IfNotExists. - Status: check the
Readycondition for reasonSecretSyncedorSecretSyncedError; errors typically name the store, missing key, or auth issue in that order. The store itself carries its ownReadycondition (Validreason) that trips first when credentials are bad.
The other three tools, in fields
- Sealed Secrets. Scope controls where a ciphertext can be decrypted:
strict(the default, binding both name and namespace so renaming triggers adecryption error),namespace-wide(annotationsealedsecrets.bitnami.com/namespace-wide: "true", allowing any name inside that namespace), orcluster-wide(any namespace). Useful CLI flags:kubeseal --scope,--fetch-certfor offline sealing,--merge-intoto append one key, and--rawfor a single value. The controller rotates its sealing key every 30 days while retaining older keys so existing ciphertexts keep working; back up thesealed-secrets-key*Secrets inkube-system. Annotating an existing Secret withsealedsecrets.bitnami.com/managed: "true"lets a SealedSecret adopt it, and.../patch: "true"merges instead of overwriting. - SOPS with Flux. Create a
.sops.yamlwithcreation_rules(path_regex,age/pgp/kmsrecipients, andencrypted_regex: ^(data|stringData)$so metadata stays cleartext) and runsops --encrypt --in-place secret.yaml. Point your Flux Kustomization at it viaspec.decryption: { provider: sops, secretRef: { name: sops-age } }, where that Secret holds the age key file (age.agekey) or GPG private key.kustomize-controllerdecrypts in memory at apply time, while git diffs stay readable because only values are encrypted. - Secrets Store CSI driver. Pair a
SecretProviderClass(providers:vault,azure,aws,gcp) with a pod volume usingcsi.driver: secrets-store.csi.k8s.ioandvolumeAttributes.secretProviderClass. Secrets mount directly as files and never touch etcd unless you addsecretObjectsto mirror them into a Kubernetes Secret (for env vars). Turn on rotation with--enable-secret-rotationand--rotation-poll-intervalon the driver. Choose CSI when "the secret must never exist in etcd"; choose ESO when workloads already expect standard Kubernetes Secrets.
list and watch on Secrets return the actual secret values, not just their names. A "read-only" role with those verbs hands over every secret in the namespace. Kubernetes best practice is to grant get on named Secrets via resourceNames and reserve list/watch for controllers that genuinely need them. That single distinction is a rock-solid exam answer on its own.
Exercises
examples/multitenancy/team-a.yaml binds the developer Role to user dev-a. Predict the answer before running each check:
kubectl auth can-i create deployments --as=dev-a -n team-a
kubectl auth can-i delete secrets --as=dev-a -n team-a
kubectl auth can-i list secrets --as=dev-a -n team-a
kubectl auth can-i create pods --as=dev-a -n team-b
kubectl auth can-i list nodes --as=dev-aoutputcaptured 2026-08-26
$ kubectl auth can-i create deployments --as=dev-a -n team-a
yes
$ kubectl auth can-i delete secrets --as=dev-a -n team-a
no
$ kubectl auth can-i list secrets --as=dev-a -n team-a
yes
$ kubectl auth can-i create pods --as=dev-a -n team-b
no
$ kubectl auth can-i list nodes --as=dev-a
Warning: resource 'nodes' is not namespace scoped
noTurn developer into a ClusterRole and bind it inside team-b with a RoleBinding for user dev-b.
kubectl auth can-i create deployments --as=dev-b -n team-b returns yes, while -n team-a returns no. One role definition, per-tenant grants: this exact pattern answers almost every "design RBAC for tenants" prompt.Create SA reporter in team-a with only get,list on pods, then test it from inside a pod. One wrinkle first: team-a's deny-all egress also blocks the API server (just like in 3.3), so open that path temporarily with a CiliumNetworkPolicy named allow-apiserver in team-a (endpointSelector: {}, one egress rule with toEntities: [kube-apiserver]), and delete it when you finish:
kubectl -n team-a create sa reporter
kubectl -n team-a create role pod-reader --verb=get,list --resource=pods
kubectl -n team-a create rolebinding reporter --role=pod-reader --serviceaccount=team-a:reporter
kubectl -n team-a run api-probe --image=bitnami/kubectl:latest --restart=Never \
--overrides='{"spec":{"serviceAccountName":"reporter"}}' -- get pods
kubectl -n team-a wait --for=jsonpath='{.status.phase}'=Succeeded pod/api-probe --timeout=120s
kubectl -n team-a logs api-probeoutputcaptured 2026-11-18
$ kubectl -n team-a create sa reporter
serviceaccount/reporter created
$ kubectl -n team-a create role pod-reader --verb=get,list --resource=pods
role.rbac.authorization.k8s.io/pod-reader created
$ kubectl -n team-a create rolebinding reporter --role=pod-reader --serviceaccount=team-a:reporter
rolebinding.rbac.authorization.k8s.io/reporter created
$ kubectl -n team-a run api-probe --image=bitnami/kubectl:latest --restart=Never \
--overrides='{"spec":{"serviceAccountName":"reporter"}}' -- get pods
Warning: would violate PodSecurity "restricted:latest": allowPrivilegeEscalation != false (container "api-probe" must set securityContext.allowPrivilegeEscalation=false), unrestricted capabilities (container "api-probe" must set securityContext.capabilities.drop=["ALL"]), runAsNonRoot != true (pod or container "api-probe" must set securityContext.runAsNonRoot=true), seccompProfile (pod or container "api-probe" must set securityContext.seccompProfile.type to "RuntimeDefault" or "Localhost")
pod/api-probe created
$ kubectl -n team-a wait --for=jsonpath='{.status.phase}'=Succeeded pod/api-probe --timeout=120s
pod/api-probe condition met
$ kubectl -n team-a logs api-probe
NAME READY STATUS RESTARTS AGE
api-probe 1/1 Running 0 5s
broken-d588c6865-z29kj 1/1 Running 0 87m
demo-dff9796f6-5fkxf 1/1 Running 0 175m
demo-dff9796f6-6ghgz 1/1 Running 0 3h
demo-dff9796f6-qvkzq 1/1 Running 0 175m
demo-dff9796f6-wzlxb 1/1 Running 0 177m
staging-demo-5fbf76bbbf-hk9b7 1/1 Running 0 151m
staging-demo-5fbf76bbbf-tcn2t 1/1 Running 0 151m
staging-demo-5fbf76bbbf-wc5jq 1/1 Running 0 151m(Because the image's entrypoint is already kubectl, pass just get pods; adding kubectl runs kubectl kubectl.)
-- get secrets and read the Forbidden message, noting how it calls out the SA, verb, and resource. That's the exact same error shape you saw in workflow failures (3.4) and will see again in operator logs.The Sealed Secrets controller from make sec lives in kube-system:
kubectl -n team-a create secret generic db-pass --from-literal=password=hunter2 \
--dry-run=client -o yaml | kubeseal --controller-namespace kube-system --controller-name sealed-secrets -o yaml > /tmp/sealed.yaml
grep -c hunter2 /tmp/sealed.yaml # must print 0
kubectl apply -f /tmp/sealed.yaml
kubectl -n team-a wait --for=create secret/db-pass --timeout=60s # the controller unseals it a moment later
kubectl -n team-a get secret db-pass -o jsonpath='{.data.password}' | base64 -doutputcaptured 2026-11-18
$ kubectl -n team-a create secret generic db-pass --from-literal=password=hunter2 \
--dry-run=client -o yaml | kubeseal --controller-namespace kube-system --controller-name sealed-secrets -o yaml > /tmp/sealed.yaml
$ grep -c hunter2 /tmp/sealed.yaml # must print 0
0
$ kubectl apply -f /tmp/sealed.yaml
sealedsecret.bitnami.com/db-pass created
$ kubectl -n team-a wait --for=create secret/db-pass --timeout=60s # the controller unseals it a moment later
secret/db-pass condition met
$ kubectl -n team-a get secret db-pass -o jsonpath='{.data.password}' | base64 -d
hunter2hunter2. Now delete only the Secret and watch the controller recreate it from the SealedSecret; that reconciliation loop is why the sealed manifest is the source of truth you commit to git.External Secrets ships a built-in fake provider made for local practice: create a SecretStore using the fake provider holding key pg/password, point an ExternalSecret at it, and confirm the materialized Secret shows up and refreshes on schedule.
kubectl get externalsecret reports SecretSynced True. The backend is fake, but the CRD wiring (which is what the exam cares about) is completely real.Run FAULT=rbac make break. Everything stays Running; only the can-i matrix reveals what broke.
auth can-i output.kubectl auth whoami answers the first question of every impersonation task. Run it with --as to see the exact identity the API server evaluates rules against, including any groups you might have left off.
kubectl auth whoami
kubectl auth whoami --as dev-a
kubectl auth whoami --as dev-a --as-group platform --as-group system:authenticated
kubectl auth can-i --list --as dev-a --as-group platform -n team-a | head -15outputcaptured 2026-09-12
$ kubectl auth whoami
ATTRIBUTE VALUE
Username kubernetes-admin
Groups [kubeadm:cluster-admins system:authenticated]
Extra: authentication.kubernetes.io/credential-id [X509SHA256=5e1514c2eb0eb304bb87c1a2eb03282a5074648ec504dd0ed919195f9d9017d5]
$ kubectl auth whoami --as dev-a
ATTRIBUTE VALUE
Username dev-a
Groups [system:authenticated]
$ kubectl auth whoami --as dev-a --as-group platform --as-group system:authenticated
ATTRIBUTE VALUE
Username dev-a
Groups [platform system:authenticated]
$ kubectl auth can-i --list --as dev-a --as-group platform -n team-a | head -15
Resources Non-Resource URLs Resource Names Verbs
selfsubjectreviews.authentication.k8s.io [] [] [create]
selfsubjectaccessreviews.authorization.k8s.io [] [] [create]
selfsubjectrulesreviews.authorization.k8s.io [] [] [create]
configmaps [] [] [get list watch create update patch delete]
deployments [] [] [get list watch create update patch delete]
jobs [] [] [get list watch create update patch delete]
pods/log [] [] [get list watch create update patch delete]
pods [] [] [get list watch create update patch delete]
services [] [] [get list watch create update patch delete]
statefulsets [] [] [get list watch create update patch delete]
configmaps.apps [] [] [get list watch create update patch delete]
deployments.apps [] [] [get list watch create update patch delete]
jobs.apps [] [] [get list watch create update patch delete]
pods.apps/log [] [] [get list watch create update patch delete]--as-group only puts you in the default groups, which is why a group-based binding can look broken when you test it carelessly.Kubernetes RBAC blocks privilege escalation: you can't bind permissions you don't hold yourself. The sanctioned bypass is the bind verb on that specific role, and the error before you grant it is worth recognizing on sight.
kubectl -n team-a create rolebinding dev-a-admin --clusterrole=admin --user=dev-a
kubectl create clusterrole node-reader --verb=get,list --resource=nodes
kubectl -n team-a create rolebinding node-reader-binding --clusterrole=node-reader --user=dev-b --as dev-a
kubectl create clusterrole binder --verb=bind --resource=clusterroles --resource-name=node-reader
kubectl -n team-a create rolebinding dev-a-binder --clusterrole=binder --user=dev-a
kubectl -n team-a create rolebinding node-reader-binding --clusterrole=node-reader --user=dev-b --as dev-a
kubectl -n team-a delete rolebinding node-reader-binding dev-a-binder dev-a-admin --ignore-not-found
kubectl delete clusterrole node-reader binderoutputcaptured 2026-09-12
$ kubectl -n team-a create rolebinding dev-a-admin --clusterrole=admin --user=dev-a
rolebinding.rbac.authorization.k8s.io/dev-a-admin created
$ kubectl create clusterrole node-reader --verb=get,list --resource=nodes
clusterrole.rbac.authorization.k8s.io/node-reader created
$ kubectl -n team-a create rolebinding node-reader-binding --clusterrole=node-reader --user=dev-b --as dev-a
error: failed to create rolebinding: rolebindings.rbac.authorization.k8s.io "node-reader-binding" is forbidden: user "dev-a" (groups=["system:authenticated"]) is attempting to grant RBAC permissions not currently held:
{APIGroups:[""], Resources:["nodes"], Verbs:["get" "list"]}
$ kubectl create clusterrole binder --verb=bind --resource=clusterroles --resource-name=node-reader
clusterrole.rbac.authorization.k8s.io/binder created
$ kubectl -n team-a create rolebinding dev-a-binder --clusterrole=binder --user=dev-a
rolebinding.rbac.authorization.k8s.io/dev-a-binder created
$ kubectl -n team-a create rolebinding node-reader-binding --clusterrole=node-reader --user=dev-b --as dev-a
rolebinding.rbac.authorization.k8s.io/node-reader-binding created
$ kubectl -n team-a delete rolebinding node-reader-binding dev-a-binder dev-a-admin --ignore-not-found
rolebinding.rbac.authorization.k8s.io "node-reader-binding" deleted from team-a namespace
rolebinding.rbac.authorization.k8s.io "dev-a-binder" deleted from team-a namespace
rolebinding.rbac.authorization.k8s.io "dev-a-admin" deleted from team-a namespace
$ kubectl delete clusterrole node-reader binder
clusterrole.rbac.authorization.k8s.io "node-reader" deleted
clusterrole.rbac.authorization.k8s.io "binder" deletedbind on that exact ClusterRole. Be able to explain why scoping that rule with resourceNames matters even more than the verb itself.A ServiceAccount token is a signed JWT carrying an expiry and an audience. Now that Kubernetes no longer auto-generates Secret tokens, knowing how to mint and decode one is basic operational hygiene, and those bound claims are what keep it safe.
kubectl -n team-a create serviceaccount reporter --dry-run=client -o yaml | kubectl apply --server-side -f - # already there if you did the reporter exercise above
TOKEN=$(kubectl -n team-a create token reporter --duration=10m)
echo "$TOKEN" | cut -d. -f2 | tr '_-' '/+' | base64 -d 2>/dev/null | jq
kubectl -n team-a run tokenholder --image=nginx:1.27-alpine --restart=Never --overrides='{"spec":{"serviceAccountName":"reporter","containers":[{"name":"tokenholder","image":"nginx:1.27-alpine","resources":{"requests":{"cpu":"25m","memory":"32Mi"},"limits":{"cpu":"100m","memory":"64Mi"}}}]}}'
kubectl -n team-a wait --for=condition=Ready pod/tokenholder --timeout=120s
kubectl -n team-a exec tokenholder -- cat /var/run/secrets/kubernetes.io/serviceaccount/token | cut -d. -f2 | tr '_-' '/+' | base64 -d 2>/dev/null | jq '{aud, exp, "kubernetes.io": ."kubernetes.io"}'
kubectl -n team-a delete pod tokenholder
kubectl -n team-a delete serviceaccount reporteroutputcaptured 2026-11-18
$ kubectl -n team-a create serviceaccount reporter --dry-run=client -o yaml | kubectl apply --server-side -f - # already there if you did the reporter exercise above
serviceaccount/reporter serverside-applied
$ TOKEN=$(kubectl -n team-a create token reporter --duration=10m)
$ echo "$TOKEN" | cut -d. -f2 | tr '_-' '/+' | base64 -d 2>/dev/null | jq
{
"aud": [
"https://kubernetes.default.svc.cluster.local"
],
"exp": 1794997942,
"iat": 1794997342,
"iss": "https://kubernetes.default.svc.cluster.local",
"jti": "6ca50893-3531-4571-8e13-f66591173554",
"kubernetes.io": {
"namespace": "team-a",
"serviceaccount": {
"name": "reporter",
"uid": "425130bc-d191-48d6-8514-4572fabc993b"
}
},
"nbf": 1794997342,
"sub": "system:serviceaccount:team-a:reporter"
}
$ kubectl -n team-a run tokenholder --image=nginx:1.27-alpine --restart=Never --overrides='{"spec":{"serviceAccountName":"reporter","containers":[{"name":"tokenholder","image":"nginx:1.27-alpine","resources":{"requests":{"cpu":"25m","memory":"32Mi"},"limits":{"cpu":"100m","memory":"64Mi"}}}]}}'
Warning: would violate PodSecurity "restricted:latest": allowPrivilegeEscalation != false (container "tokenholder" must set securityContext.allowPrivilegeEscalation=false), unrestricted capabilities (container "tokenholder" must set securityContext.capabilities.drop=["ALL"]), runAsNonRoot != true (pod or container "tokenholder" must set securityContext.runAsNonRoot=true), seccompProfile (pod or container "tokenholder" must set securityContext.seccompProfile.type to "RuntimeDefault" or "Localhost")
pod/tokenholder created
$ kubectl -n team-a wait --for=condition=Ready pod/tokenholder --timeout=120s
pod/tokenholder condition met
$ kubectl -n team-a exec tokenholder -- cat /var/run/secrets/kubernetes.io/serviceaccount/token | cut -d. -f2 | tr '_-' '/+' | base64 -d 2>/dev/null | jq '{aud, exp, "kubernetes.io": ."kubernetes.io"}'
{
"aud": [
"https://kubernetes.default.svc.cluster.local"
],
"exp": 1826533343,
"kubernetes.io": {
"namespace": "team-a",
"node": {
"name": "cnpe-worker",
"uid": "56e4f11f-c0b1-467a-bf0b-0a9427440906"
},
"pod": {
"name": "tokenholder",
"uid": "e96fb419-eaab-4a21-a21a-04e850d679b9"
},
"serviceaccount": {
"name": "reporter",
"uid": "425130bc-d191-48d6-8514-4572fabc993b"
},
"warnafter": 1795000950
}
}
$ kubectl -n team-a delete pod tokenholder
pod "tokenholder" deleted from team-a namespace
$ kubectl -n team-a delete serviceaccount reporter
serviceaccount "reporter" deleted from team-a namespaceexp and aud claims, and the one projected into the pod also binds the pod's identity under kubernetes.io.ESO's refreshPolicy decides whether your Kubernetes Secret tracks remote rotations or freezes as a one-time snapshot. Paired with an immutable target, CreatedOnce stops a secret rotation from pulling the rug out from under a running workload between deploys.
# start from nothing: an immutable target from a previous run cannot be updated
kubectl delete externalsecret pg-once pg-periodic --ignore-not-found
kubectl delete secret pg-once pg-periodic --ignore-not-found
kubectl delete secretstore fake-store --ignore-not-found
kubectl apply -f - <<'EOF'
apiVersion: external-secrets.io/v1
kind: SecretStore
metadata: { name: fake-store, namespace: default }
spec:
provider:
fake:
data:
- key: pg/password
value: first-value
---
apiVersion: external-secrets.io/v1
kind: ExternalSecret
metadata: { name: pg-once, namespace: default }
spec:
refreshPolicy: CreatedOnce
secretStoreRef: { name: fake-store, kind: SecretStore }
target:
name: pg-once
immutable: true
data:
- secretKey: password
remoteRef: { key: pg/password }
EOF
sleep 20
kubectl get secret pg-once -o jsonpath='{.data.password}' | base64 -d; echo
kubectl patch secretstore fake-store --type merge -p '{"spec":{"provider":{"fake":{"data":[{"key":"pg/password","value":"second-value"}]}}}}'
sleep 60
kubectl get secret pg-once -o jsonpath='{.data.password}' | base64 -d; echo
kubectl apply -f - <<'EOF'
apiVersion: external-secrets.io/v1
kind: ExternalSecret
metadata: { name: pg-periodic, namespace: default }
spec:
refreshPolicy: Periodic
refreshInterval: 30s
secretStoreRef: { name: fake-store, kind: SecretStore }
target: { name: pg-periodic }
data:
- secretKey: password
remoteRef: { key: pg/password }
EOF
sleep 20
kubectl get secret pg-periodic -o jsonpath='{.data.password}' | base64 -d; echo
kubectl patch secretstore fake-store --type merge -p '{"spec":{"provider":{"fake":{"data":[{"key":"pg/password","value":"third-value"}]}}}}'
sleep 60
kubectl get secret pg-periodic -o jsonpath='{.data.password}' | base64 -d; echo
kubectl delete externalsecret pg-once pg-periodic
kubectl delete secret pg-once pg-periodic --ignore-not-found
kubectl delete secretstore fake-store --ignore-not-foundoutputcaptured 2026-09-12
$ # start from nothing: an immutable target from a previous run cannot be updated
$ kubectl delete externalsecret pg-once pg-periodic --ignore-not-found
$ kubectl delete secret pg-once pg-periodic --ignore-not-found
$ kubectl delete secretstore fake-store --ignore-not-found
secretstore.external-secrets.io "fake-store" deleted from default namespace
$ kubectl apply -f - <<'EOF'
apiVersion: external-secrets.io/v1
kind: SecretStore
metadata: { name: fake-store, namespace: default }
spec:
provider:
fake:
data:
- key: pg/password
value: first-value
---
apiVersion: external-secrets.io/v1
kind: ExternalSecret
metadata: { name: pg-once, namespace: default }
spec:
refreshPolicy: CreatedOnce
secretStoreRef: { name: fake-store, kind: SecretStore }
target:
name: pg-once
immutable: true
data:
- secretKey: password
remoteRef: { key: pg/password }
EOF
Warning: store fake-store isn't currently maintained. Please plan and prepare accordingly.
secretstore.external-secrets.io/fake-store created
externalsecret.external-secrets.io/pg-once created
$ sleep 20
$ kubectl get secret pg-once -o jsonpath='{.data.password}' | base64 -d; echo
first-value
$ kubectl patch secretstore fake-store --type merge -p '{"spec":{"provider":{"fake":{"data":[{"key":"pg/password","value":"second-value"}]}}}}'
Warning: store fake-store isn't currently maintained. Please plan and prepare accordingly.
secretstore.external-secrets.io/fake-store patched
$ sleep 60
$ kubectl get secret pg-once -o jsonpath='{.data.password}' | base64 -d; echo
first-value
$ kubectl apply -f - <<'EOF'
apiVersion: external-secrets.io/v1
kind: ExternalSecret
metadata: { name: pg-periodic, namespace: default }
spec:
refreshPolicy: Periodic
refreshInterval: 30s
secretStoreRef: { name: fake-store, kind: SecretStore }
target: { name: pg-periodic }
data:
- secretKey: password
remoteRef: { key: pg/password }
EOF
externalsecret.external-secrets.io/pg-periodic created
$ sleep 20
$ kubectl get secret pg-periodic -o jsonpath='{.data.password}' | base64 -d; echo
second-value
$ kubectl patch secretstore fake-store --type merge -p '{"spec":{"provider":{"fake":{"data":[{"key":"pg/password","value":"third-value"}]}}}}'
Warning: store fake-store isn't currently maintained. Please plan and prepare accordingly.
secretstore.external-secrets.io/fake-store patched
$ sleep 60
$ kubectl get secret pg-periodic -o jsonpath='{.data.password}' | base64 -d; echo
third-value
$ kubectl delete externalsecret pg-once pg-periodic
externalsecret.external-secrets.io "pg-once" deleted from default namespace
externalsecret.external-secrets.io "pg-periodic" deleted from default namespace
$ kubectl delete secret pg-once pg-periodic --ignore-not-found
$ kubectl delete secretstore fake-store --ignore-not-found
secretstore.external-secrets.io "fake-store" deleted from default namespaceCreatedOnce secret holds onto its first value across two rotations, while the Periodic one picks up the new value within one interval.Real secret stores usually hand back JSON blobs rather than neat key-value pairs. dataFrom.extract unpacks the blob and target.template formats the exact connection string your app expects, keeping the application completely decoupled from the store layout.
# start from nothing: an immutable target from a previous run cannot be updated
kubectl delete externalsecret pg-dsn --ignore-not-found
kubectl delete secret pg-dsn --ignore-not-found
kubectl delete secretstore json-store --ignore-not-found
kubectl apply -f - <<'EOF'
apiVersion: external-secrets.io/v1
kind: SecretStore
metadata: { name: json-store, namespace: default }
spec:
provider:
fake:
data:
- key: pg/creds
value: '{"username":"app","password":"s3cr3t","host":"pg-rw.team-a.svc","port":"5432","db":"orders"}'
---
apiVersion: external-secrets.io/v1
kind: ExternalSecret
metadata: { name: pg-dsn, namespace: default }
spec:
refreshInterval: 1m
secretStoreRef: { name: json-store, kind: SecretStore }
target:
name: pg-dsn
template:
engineVersion: v2
data:
DATABASE_URL: "postgres://{{ .username }}:{{ .password }}@{{ .host }}:{{ .port }}/{{ .db }}?sslmode=require"
dataFrom:
- extract: { key: pg/creds }
EOF
sleep 20
kubectl get externalsecret pg-dsn -o jsonpath='{.status.conditions}' | jq '.[] | {type, status, reason}'
kubectl get secret pg-dsn -o jsonpath='{.data.DATABASE_URL}' | base64 -d; echo
kubectl delete externalsecret pg-dsn
kubectl delete secretstore json-storeoutputcaptured 2026-09-13
$ # start from nothing: an immutable target from a previous run cannot be updated
$ kubectl delete externalsecret pg-dsn --ignore-not-found
$ kubectl delete secret pg-dsn --ignore-not-found
$ kubectl delete secretstore json-store --ignore-not-found
$ kubectl apply -f - <<'EOF'
apiVersion: external-secrets.io/v1
kind: SecretStore
metadata: { name: json-store, namespace: default }
spec:
provider:
fake:
data:
- key: pg/creds
value: '{"username":"app","password":"s3cr3t","host":"pg-rw.team-a.svc","port":"5432","db":"orders"}'
---
apiVersion: external-secrets.io/v1
kind: ExternalSecret
metadata: { name: pg-dsn, namespace: default }
spec:
refreshInterval: 1m
secretStoreRef: { name: json-store, kind: SecretStore }
target:
name: pg-dsn
template:
engineVersion: v2
data:
DATABASE_URL: "postgres://{{ .username }}:{{ .password }}@{{ .host }}:{{ .port }}/{{ .db }}?sslmode=require"
dataFrom:
- extract: { key: pg/creds }
EOF
Warning: store json-store isn't currently maintained. Please plan and prepare accordingly.
secretstore.external-secrets.io/json-store created
externalsecret.external-secrets.io/pg-dsn created
$ sleep 20
$ kubectl get externalsecret pg-dsn -o jsonpath='{.status.conditions}' | jq '.[] | {type, status, reason}'
{
"type": "Ready",
"status": "True",
"reason": "SecretSynced"
}
$ kubectl get secret pg-dsn -o jsonpath='{.data.DATABASE_URL}' | base64 -d; echo
postgres://app:s3cr3t@pg-rw.team-a.svc:5432/orders?sslmode=require
$ kubectl delete externalsecret pg-dsn
externalsecret.external-secrets.io "pg-dsn" deleted from default namespace
$ kubectl delete secretstore json-store
secretstore.external-secrets.io "json-store" deleted from default namespaceBy default, a SealedSecret is locked to its exact name and namespace, which is great for security and occasionally awkward for reuse. Changing the scope trades part of that binding for portability, and if you get the scope wrong, the controller logs tell you right away.
echo -n 'strict-value' | kubeseal --raw --namespace default --name strict-secret --controller-namespace kube-system --controller-name sealed-secrets > /tmp/strict.b64
cat > /tmp/strict.yaml <<EOF
apiVersion: bitnami.com/v1alpha1
kind: SealedSecret
metadata: { name: strict-secret, namespace: default }
spec:
encryptedData:
value: $(cat /tmp/strict.b64)
EOF
kubectl apply -f /tmp/strict.yaml
sleep 10
kubectl get secret strict-secret -o jsonpath='{.data.value}' | base64 -d; echo
sed 's/name: strict-secret/name: renamed-secret/' /tmp/strict.yaml | kubectl apply -f -
sleep 10
kubectl get secret renamed-secret 2>/dev/null || echo 'not decrypted'
kubectl -n kube-system logs deploy/sealed-secrets --tail=10
echo -n 'wide-value' | kubeseal --raw --scope namespace-wide --namespace default --controller-namespace kube-system --controller-name sealed-secrets > /tmp/wide.b64
cat > /tmp/wide.yaml <<EOF
apiVersion: bitnami.com/v1alpha1
kind: SealedSecret
metadata:
name: wide-secret
namespace: default
annotations: { sealedsecrets.bitnami.com/namespace-wide: "true" }
spec:
encryptedData:
value: $(cat /tmp/wide.b64)
EOF
kubectl apply -f /tmp/wide.yaml
sleep 10
sed 's/name: wide-secret/name: wide-renamed/' /tmp/wide.yaml | kubectl apply -f -
sleep 10
kubectl get secret wide-renamed -o jsonpath='{.data.value}' | base64 -d; echo
kubectl delete sealedsecret strict-secret renamed-secret wide-secret wide-renamed --ignore-not-foundoutputcaptured 2026-09-12
$ echo -n 'strict-value' | kubeseal --raw --namespace default --name strict-secret --controller-namespace kube-system --controller-name sealed-secrets > /tmp/strict.b64
$ cat > /tmp/strict.yaml <<EOF
apiVersion: bitnami.com/v1alpha1
kind: SealedSecret
metadata: { name: strict-secret, namespace: default }
spec:
encryptedData:
value: $(cat /tmp/strict.b64)
EOF
$ kubectl apply -f /tmp/strict.yaml
sealedsecret.bitnami.com/strict-secret created
$ sleep 10
$ kubectl get secret strict-secret -o jsonpath='{.data.value}' | base64 -d; echo
strict-value
$ sed 's/name: strict-secret/name: renamed-secret/' /tmp/strict.yaml | kubectl apply -f -
sealedsecret.bitnami.com/renamed-secret created
$ sleep 10
$ kubectl get secret renamed-secret 2>/dev/null || echo 'not decrypted'
not decrypted
$ kubectl -n kube-system logs deploy/sealed-secrets --tail=10
time=2026-09-12T19:44:52.637Z level=INFO msg=Updating key=default/renamed-secret
time=2026-09-12T19:44:52.644Z level=ERROR msg="Error updating, will retry" key=default/renamed-secret error="no key could decrypt secret (value)"
time=2026-09-12T19:44:52.644Z level=INFO msg="Event(v1.ObjectReference{Kind:\"SealedSecret\", Namespace:\"default\", Name:\"renamed-secret\", UID:\"9f10a4d2-f72f-4f66-ad14-12352277718c\", APIVersion:\"bitnami.com/v1alpha1\", ResourceVersion:\"27307\", FieldPath:\"\"}): type: 'Warning' reason: 'ErrUnsealFailed' Failed to unseal: no key could decrypt secret (value)"
time=2026-09-12T19:44:52.685Z level=INFO msg=Updating key=default/renamed-secret
time=2026-09-12T19:44:52.692Z level=ERROR msg="Error updating, will retry" key=default/renamed-secret error="no key could decrypt secret (value)"
time=2026-09-12T19:44:52.692Z level=INFO msg="Event(v1.ObjectReference{Kind:\"SealedSecret\", Namespace:\"default\", Name:\"renamed-secret\", UID:\"9f10a4d2-f72f-4f66-ad14-12352277718c\", APIVersion:\"bitnami.com/v1alpha1\", ResourceVersion:\"27307\", FieldPath:\"\"}): type: 'Warning' reason: 'ErrUnsealFailed' Failed to unseal: no key could decrypt secret (value)"
time=2026-09-12T19:44:52.773Z level=INFO msg=Updating key=default/renamed-secret
time=2026-09-12T19:44:52.780Z level=ERROR msg="Error updating, giving up" key=default/renamed-secret error="no key could decrypt secret (value)"
E0912 19:44:52.780710 1 controller.go:320] "Unhandled Error" err="no key could decrypt secret (value)" logger="UnhandledError"
time=2026-09-12T19:44:52.780Z level=INFO msg="Event(v1.ObjectReference{Kind:\"SealedSecret\", Namespace:\"default\", Name:\"renamed-secret\", UID:\"9f10a4d2-f72f-4f66-ad14-12352277718c\", APIVersion:\"bitnami.com/v1alpha1\", ResourceVersion:\"27307\", FieldPath:\"\"}): type: 'Warning' reason: 'ErrUnsealFailed' Failed to unseal: no key could decrypt secret (value)"
$ echo -n 'wide-value' | kubeseal --raw --scope namespace-wide --namespace default --controller-namespace kube-system --controller-name sealed-secrets > /tmp/wide.b64
$ cat > /tmp/wide.yaml <<EOF
apiVersion: bitnami.com/v1alpha1
kind: SealedSecret
metadata:
name: wide-secret
namespace: default
annotations: { sealedsecrets.bitnami.com/namespace-wide: "true" }
spec:
encryptedData:
value: $(cat /tmp/wide.b64)
EOF
$ kubectl apply -f /tmp/wide.yaml
sealedsecret.bitnami.com/wide-secret created
$ sleep 10
$ sed 's/name: wide-secret/name: wide-renamed/' /tmp/wide.yaml | kubectl apply -f -
sealedsecret.bitnami.com/wide-renamed created
$ sleep 10
$ kubectl get secret wide-renamed -o jsonpath='{.data.value}' | base64 -d; echo
wide-value
$ kubectl delete sealedsecret strict-secret renamed-secret wide-secret wide-renamed --ignore-not-found
sealedsecret.bitnami.com "strict-secret" deleted from default namespace
sealedsecret.bitnami.com "renamed-secret" deleted from default namespace
sealedsecret.bitnami.com "wide-secret" deleted from default namespace
sealedsecret.bitnami.com "wide-renamed" deleted from default namespacestrict secret refuses to unseal under a new name (check the decryption error in the controller log), while the namespace-wide one decrypts under any name in that namespace. Think through what cluster-wide gives up, and why you'd almost never reach for it.SOPS is the Flux-native way to store secrets in git: keys stay readable in diffs while values stay encrypted, and Flux decrypts them in memory using a cluster-only key. The entire round trip takes five commands.
START=$PWD # the cd below would otherwise follow you into every later command
mkdir -p "$HOME/.local/bin"; export PATH="$HOME/.local/bin:$PATH"
curl -sL "$(curl -s https://api.github.com/repos/FiloSottile/age/releases/latest | jq -r '.assets[] | select(.name | endswith("linux-amd64.tar.gz")) | .browser_download_url')" | tar xz -C /tmp && install /tmp/age/age /tmp/age/age-keygen "$HOME/.local/bin/"
curl -sLo "$HOME/.local/bin/sops" "$(curl -s https://api.github.com/repos/getsops/sops/releases/latest | jq -r '.assets[] | select(.name | endswith("linux.amd64")) | .browser_download_url')" && chmod +x "$HOME/.local/bin/sops"
age-keygen --version; sops --version | head -1
rm -f /tmp/sops.agekey && age-keygen -o /tmp/sops.agekey
PUB=$(grep 'public key' /tmp/sops.agekey | awk '{print $NF}'); echo "recipient: $PUB"
kubectl -n flux-system create secret generic sops-age --from-file=age.agekey=/tmp/sops.agekey --dry-run=client -o yaml | kubectl apply -f -
source lab.env # GITEA_PASS for the clone, as in 2.1
rm -rf /tmp/platform-sops && git clone "http://lab:${GITEA_PASS}@gitea.lab:3000/lab/platform.git" /tmp/platform-sops && cd /tmp/platform-sops
mkdir -p secrets
cat > .sops.yaml <<EOF
creation_rules:
- path_regex: secrets/.*\.yaml$
encrypted_regex: '^(data|stringData)$'
age: $PUB
EOF
kubectl -n flux-demo create secret generic app-config --from-literal=api-key=super-secret --dry-run=client -o yaml > secrets/app-config.yaml
sops --encrypt --in-place secrets/app-config.yaml
head -12 secrets/app-config.yaml
git add .sops.yaml secrets && git commit -m 'sops-encrypted secret' && git push
kubectl create ns flux-demo --dry-run=client -o yaml | kubectl apply -f -
kubectl apply -f - <<'EOF'
apiVersion: kustomize.toolkit.fluxcd.io/v1
kind: Kustomization
metadata: { name: secrets, namespace: flux-system }
spec:
interval: 1m
prune: true
sourceRef: { kind: GitRepository, name: platform }
path: ./secrets
decryption:
provider: sops
secretRef: { name: sops-age }
EOF
sleep 60
kubectl -n flux-demo get secret app-config -o jsonpath='{.data.api-key}' | base64 -d; echo
# put the lab back: this repo is shared with every other GitOps exercise on the site
flux delete kustomization secrets -s
sleep 10
kubectl -n flux-demo get secret app-config --ignore-not-found
git rm -r --quiet secrets .sops.yaml && git commit -m 'remove the sops demo' && git push
kubectl -n flux-system delete secret sops-age
cd "$START"outputcaptured 2026-11-18
$ START=$PWD # the cd below would otherwise follow you into every later command
$ mkdir -p "$HOME/.local/bin"; export PATH="$HOME/.local/bin:$PATH"
$ curl -sL "$(curl -s https://api.github.com/repos/FiloSottile/age/releases/latest | jq -r '.assets[] | select(.name | endswith("linux-amd64.tar.gz")) | .browser_download_url')" | tar xz -C /tmp && install /tmp/age/age /tmp/age/age-keygen "$HOME/.local/bin/"
$ curl -sLo "$HOME/.local/bin/sops" "$(curl -s https://api.github.com/repos/getsops/sops/releases/latest | jq -r '.assets[] | select(.name | endswith("linux.amd64")) | .browser_download_url')" && chmod +x "$HOME/.local/bin/sops"
$ age-keygen --version; sops --version | head -1
v1.3.2
sops 3.13.3 (latest)
$ rm -f /tmp/sops.agekey && age-keygen -o /tmp/sops.agekey
Public key: age1qted7qzjccvx8kag5s24jf7ahcn33zn22jz7qj9gg0tusl3ecg4sggp4rs
$ PUB=$(grep 'public key' /tmp/sops.agekey | awk '{print $NF}'); echo "recipient: $PUB"
recipient: age1qted7qzjccvx8kag5s24jf7ahcn33zn22jz7qj9gg0tusl3ecg4sggp4rs
$ kubectl -n flux-system create secret generic sops-age --from-file=age.agekey=/tmp/sops.agekey --dry-run=client -o yaml | kubectl apply -f -
secret/sops-age created
$ source lab.env # GITEA_PASS for the clone, as in 2.1
$ rm -rf /tmp/platform-sops && git clone "http://lab:${GITEA_PASS}@gitea.lab:3000/lab/platform.git" /tmp/platform-sops && cd /tmp/platform-sops
Cloning into '/tmp/platform-sops'...
warning: redirecting to http://gitea.lab:3000/lab/platform.git/
$ mkdir -p secrets
$ cat > .sops.yaml <<EOF
creation_rules:
- path_regex: secrets/.*\.yaml$
encrypted_regex: '^(data|stringData)$'
age: $PUB
EOF
$ kubectl -n flux-demo create secret generic app-config --from-literal=api-key=super-secret --dry-run=client -o yaml > secrets/app-config.yaml
$ sops --encrypt --in-place secrets/app-config.yaml
$ head -12 secrets/app-config.yaml
apiVersion: v1
data:
api-key: ENC[AES256_GCM,data:yIOoda6lWnkpgM9KEPW9vA==,iv:1uFjzx7lCvDRRXRTKLgVMAZ6fMiJCSr5da4hjCA3l1o=,tag:SV/M+9bWeyJK8hXITWf3uw==,type:str]
kind: Secret
metadata:
name: app-config
namespace: flux-demo
sops:
age:
- enc: |
-----BEGIN AGE ENCRYPTED FILE-----
YWdlLWVuY3J5cHRpb24ub3JnL3YxCi0+IFgyNTUxOSBSK2thZDc4M3M1MXZyTDNl
$ git add .sops.yaml secrets && git commit -m 'sops-encrypted secret' && git push
[main be3a6db] sops-encrypted secret
2 files changed, 26 insertions(+)
create mode 100644 .sops.yaml
create mode 100644 secrets/app-config.yaml
warning: redirecting to http://gitea.lab:3000/lab/platform.git/
To http://gitea.lab:3000/lab/platform.git
e8545e3..be3a6db main -> main
$ kubectl create ns flux-demo --dry-run=client -o yaml | kubectl apply -f -
namespace/flux-demo unchanged
$ kubectl apply -f - <<'EOF'
apiVersion: kustomize.toolkit.fluxcd.io/v1
kind: Kustomization
metadata: { name: secrets, namespace: flux-system }
spec:
interval: 1m
prune: true
sourceRef: { kind: GitRepository, name: platform }
path: ./secrets
decryption:
provider: sops
secretRef: { name: sops-age }
EOF
kustomization.kustomize.toolkit.fluxcd.io/secrets created
$ sleep 60
$ kubectl -n flux-demo get secret app-config -o jsonpath='{.data.api-key}' | base64 -d; echo
super-secret
$ # put the lab back: this repo is shared with every other GitOps exercise on the site
$ flux delete kustomization secrets -s
► deleting kustomization secrets in flux-system namespace
✔ kustomization deleted
$ sleep 10
$ kubectl -n flux-demo get secret app-config --ignore-not-found
$ git rm -r --quiet secrets .sops.yaml && git commit -m 'remove the sops demo' && git push
[main 84589a8] remove the sops demo
2 files changed, 26 deletions(-)
delete mode 100644 .sops.yaml
delete mode 100644 secrets/app-config.yaml
warning: redirecting to http://gitea.lab:3000/lab/platform.git/
To http://gitea.lab:3000/lab/platform.git
be3a6db..84589a8 main -> main
$ kubectl -n flux-system delete secret sops-age
secret "sops-age" deleted from flux-system namespace
$ cd "$START"Self-check
Define "developer" once and grant it in twelve namespaces. What objects, and how many?
One ClusterRole plus twelve RoleBindings (one per namespace, each pointing its roleRef at that ClusterRole). Never a ClusterRoleBinding: that would grant permissions cluster-wide and fail any "not in another namespace" check.
A user can get a pod by name but kubectl get pods fails. Why?
list is a separate verb from get, and a rule scoped with resourceNames can't satisfy an unfiltered list. Add list (and watch if anything streams updates), knowing that list exposes every object of that kind in the namespace.
How do you let a tenant read pod logs but never exec into a pod?
Grant get on pods/log and withhold create on pods/exec. Because Kubernetes treats subresources as distinct resource strings, you can separate them cleanly.
You ship a new CRD. How do existing view users get read access without editing the built-in role?
Create a ClusterRole granting read verbs on your new kind and label it rbac.authorization.k8s.io/aggregate-to-view: "true". Role aggregation folds it straight into the built-in view role automatically, which is the standard platform move when shipping a CRD.
Sealed Secrets versus ESO: which would you pick for a regulated environment with an existing vault, and why?
Pick ESO. Your vault remains the single source of truth with its own audit trail and rotation policies, and git only ever stores references rather than secret material (even encrypted). Sealed Secrets fits self-contained clusters without an external store, at the cost of managing and backing up the sealing keys yourself.
Is a Kubernetes Secret encrypted?
Not by default: base64 is just encoding. At rest in etcd, Secrets are only encrypted if the API server has an EncryptionConfiguration (optionally backed by a KMS); in transit, TLS protects them. In practice, strict RBAC over who can read Secrets does most of the day-to-day protection.
A namespace admin with the built-in admin role cannot create a RoleBinding to a custom ClusterRole that grants nodes read. Why, and what is the least-privilege fix?
Escalation prevention: you can only bind permissions you already hold, and admin doesn't include cluster-scoped nodes. The least-privilege fix is granting the bind verb on clusterroles scoped via resourceNames to that exact ClusterRole. Handing out node read access directly or granting cluster-admin would work, and would fail least privilege.
An OIDC user in group platform-team is bound via a ClusterRoleBinding to that group and still gets Forbidden. First command, likely cause?
Run kubectl auth whoami to see the exact groups the API server receives. With --oidc-groups-prefix (or claimMappings.groups.prefix in structured config), the group arrives prefixed, like oidc:platform-team, so bind to that exact string. The same check also catches username prefixes and mismatched groups claim names.
You rotate the aescbc key in EncryptionConfiguration. Order of operations, and what happens if you simply replace the key?
Add the new key first in providers[] while keeping the old key second, restart the API servers, rewrite every Secret so it re-encrypts under the new key (kubectl get secrets -A -o json | kubectl replace -f -), and finally remove the old key. If you simply swap the key out, every existing Secret becomes unreadable, failing loudly on get secrets rather than at API server startup.
ESO: a database password rotates in Vault every hour, the ExternalSecret has refreshInterval: 0, and pods keep failing to log in. Two fixes and their trade-offs?
refreshInterval: 0 means "create once and never refresh", so the Secret stays frozen on the original password. Option one: set a refreshInterval shorter than the rotation window (with Periodic policy) and ensure pods pick up updates (via file mounts or a restart trigger like Reloader, since env vars don't reload). Option two: if running pods shouldn't see credentials shift underneath them, keep CreatedOnce with immutable: true and roll deployments intentionally on rotation.
Docs to know your way around
- kubernetes.io: Using RBAC Authorization (covers both the RoleBinding-to-ClusterRole pattern and aggregation), Managing Service Accounts, and Encrypting Secret Data at Rest.
- sealed-secrets and external-secrets docs: one page each on their CRDs; the
fakeprovider sits in ESO's provider list. - Offline:
kubectl auth can-i --list,kubectl api-resources --verbs=list, andkubectl create role --help(its examples double as a rules cheat sheet). - kubernetes.io/docs/reference/access-authn-authz/rbac, specifically "Privilege escalation prevention and bootstrapping" and "Default roles and role bindings": the two sections every tricky Forbidden puzzle sends you to.
- kubernetes.io/docs/tasks/administer-cluster/encrypt-data (providers table and rotation steps) and /docs/reference/access-authn-authz/authentication (OIDC flags,
AuthenticationConfiguration,SelfSubjectReview). - external-secrets.io/latest/api/externalsecret (refresh and creation policies) and /guides/templating; fluxcd.io/flux/guides/mozilla-sops for the Kustomization
decryptionblock.
make down-gitops