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.

needsmake up secmake gitops

Orientation

competency 5.2 · RBAC and security controls

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.

Authorization in three sentences

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

roles · bindings · subjects · verbs
ObjectScopeContains
RoleOne namespaceRules: apiGroups × resources × verbs (+ optional resourceNames)
ClusterRoleCluster-wide definitionThe same, plus cluster-scoped resources and non-resource URLs
RoleBindingGrants in one namespaceSubjects + a roleRef to a Role or a ClusterRole
ClusterRoleBindingGrants everywhereSubjects + a roleRef to a ClusterRole
The asymmetry exams love

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, and watch are separate verbs. A dashboard listing pods needs list, and a controller needs watch too. Granting only get and wondering why kubectl 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 blocking exec is easy to express and makes a great tenant default.
  • resourceNames narrows a rule to specific named objects, which is how you allow editing a single ConfigMap. Keep in mind it can't restrict create or deletecollection, and a plain list or watch only succeeds if paired with a matching metadata.name field selector.
  • Wildcards (*) exist, and least privilege says to avoid them. escalate and bind are special verbs that let someone grant permissions they don't hold themselves; treat both as admin-only.
  • Aggregated ClusterRoles (aggregationRule with label selectors) let the built-in view, edit, and admin roles absorb new CRDs automatically. Label your ClusterRole rbac.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), and cluster-admin (everything).
The two interrogation commands
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

special verbs, identity checks, tokens, OIDC groups

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 escalate verb on roles/clusterroles. Similarly, you can only create a binding if you hold those permissions or hold the bind verb on that role (optionally narrowed with resourceNames). Otherwise you get attempt to grant extra privileges. A tenant admin who "cannot bind the view role" needs bind on that one ClusterRole, not cluster-admin.
  • impersonate on users, groups, serviceaccounts (and userextras) powers kubectl --as and --as-group. Only cluster-admin holds it by default, so a tenant who wants to test their own SA with --as needs it granted explicitly.
  • kubectl auth whoami (the SelfSubjectReview API) 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 /metrics needs get on that URL, and wildcards act as suffix globs.
  • Default ClusterRoles. view reads most namespaced objects, excluding Secrets, Roles, and RoleBindings. edit adds 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. admin adds Role and RoleBinding management inside that namespace, and cluster-admin unlocks everything. All four aggregate labeled roles (rbac.authorization.k8s.io/aggregate-to-view|edit|admin). Meanwhile, system:authenticated inherits system:basic-user and system:discovery; if system:unauthenticated can read discovery, check for the system:public-info-viewer binding.
  • Auto-reconciliation. Built-in roles and bindings reset on API server restart unless annotated with rbac.authorization.kubernetes.io/autoupdate: "false". Any direct edit to view gets overwritten, which is why aggregation exists. Run kubectl auth reconcile -f rbac.yaml to apply RBAC manifests additively and see what changed.
  • kubectl create role shortcuts. Use --verb=get,list --resource=pods,pods/log, --resource=deployments.apps for group-qualified resources, --resource-name=x for named objects, and kubectl 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 (serviceAccountToken with expirationSeconds and audience) that the kubelet refreshes via the TokenRequest API; it's bound to that pod and dies with it. Use kubectl create token <sa> --duration=1h to mint one for scripts, or add --bound-object-kind Pod --bound-object-name x to 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 for kubectl create token, and only create an explicit kubernetes.io/service-account-token Secret if a non-expiring token is genuinely required. Set automountServiceAccountToken: false on the pod or SA to drop the mount completely.
  • OIDC. Legacy flags are --oidc-issuer-url, --oidc-client-id, --oidc-username-claim (default sub), --oidc-username-prefix, --oidc-groups-claim, and --oidc-groups-prefix. The modern structured form is an AuthenticationConfiguration file passed via --authentication-config, supporting multiple issuers with jwt[].issuer.url/audiences, claimMappings.username.claim|prefix, claimMappings.groups.claim|prefix, and CEL claimValidationRules. Remember that groups arrive with their prefix attached (like oidc:platform-team), so binding to bare platform-team silently matches nobody; kubectl auth whoami reveals 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), and system:nodes.
How this gets tested

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

and the three GitOps answers

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.

ApproachWhat git holdsWho can decryptGood for
Sealed SecretsCiphertext (a SealedSecret CR)Only the in-cluster controller's private keySelf-contained clusters with no external secret store
External Secrets (ESO)A reference (SecretStore + ExternalSecret)Whoever the backing store authorizesEnvironments where Vault or a cloud secret manager is already the source of truth
SOPSPartially encrypted YAMLHolders of the age, PGP, or KMS keyFlux-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) or ClusterSecretStore (cluster-wide, referenced with kind: ClusterSecretStore) defines where secrets live and how to authenticate: a provider block (vault, aws, gcp, azure, kubernetes, or fake for practice) plus credentials, typically a ServiceAccount token or Secret ref.
  • ExternalSecret defines what to materialize: secretStoreRef, a refreshInterval, and either explicit data[] mappings (remote key → local key) or dataFrom to pull a whole path. Use target.name to name the generated Secret, target.creationPolicy to control ownership, and target.template to assemble structured outputs like config files or connection strings instead of raw key-value pairs.
  • Check the SecretSynced status condition: when syncing fails, the message usually points straight to the store, a missing key, or an auth error, in that order of likelihood.
  • PushSecret reverses 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.

Sealed Secrets' sharp edge

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, ESO, Sealed Secrets, SOPS, CSI

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 key
  • refreshPolicy: Periodic syncs every refreshInterval and on spec edits; OnChange syncs only when the ExternalSecret itself changes; CreatedOnce fetches once per object (recreating the ExternalSecret triggers a fresh pull, so pair it with target.immutable: true for credentials nothing should overwrite in place). Need an immediate refresh? Run kubectl 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), or None (never creates a Secret). deletionPolicy controls what happens to the Secret if the remote key disappears.
  • dataFrom.extract unpacks an entire JSON object into keys, dataFrom.find matches by path regex or tags, and rewrite renames keys. template (engine v2, Go templates with Sprig) builds full config files and DSNs, templateFrom pulls templates from a ConfigMap, and mergePolicy: Merge keeps raw keys alongside the templated ones.
  • Scoping: SecretStore is namespaced, while ClusterSecretStore can restrict which namespaces may use it via conditions[].namespaceSelector or namespaces. ClusterExternalSecret stamps one ExternalSecret across every namespace matching namespaceSelectors, and PushSecret pushes cluster Secrets back to an external store with updatePolicy: Replace|IfNotExists.
  • Status: check the Ready condition for reason SecretSynced or SecretSyncedError; errors typically name the store, missing key, or auth issue in that order. The store itself carries its own Ready condition (Valid reason) 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 a decryption error), namespace-wide (annotation sealedsecrets.bitnami.com/namespace-wide: "true", allowing any name inside that namespace), or cluster-wide (any namespace). Useful CLI flags: kubeseal --scope, --fetch-cert for offline sealing, --merge-into to append one key, and --raw for a single value. The controller rotates its sealing key every 30 days while retaining older keys so existing ciphertexts keep working; back up the sealed-secrets-key* Secrets in kube-system. Annotating an existing Secret with sealedsecrets.bitnami.com/managed: "true" lets a SealedSecret adopt it, and .../patch: "true" merges instead of overwriting.
  • SOPS with Flux. Create a .sops.yaml with creation_rules (path_regex, age/pgp/kms recipients, and encrypted_regex: ^(data|stringData)$ so metadata stays cleartext) and run sops --encrypt --in-place secret.yaml. Point your Flux Kustomization at it via spec.decryption: { provider: sops, secretRef: { name: sops-age } }, where that Secret holds the age key file (age.agekey) or GPG private key. kustomize-controller decrypts 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 using csi.driver: secrets-store.csi.k8s.io and volumeAttributes.secretProviderClass. Secrets mount directly as files and never touch etcd unless you add secretObjects to mirror them into a Kubernetes Secret (for env vars). Turn on rotation with --enable-secret-rotation and --rotation-poll-interval on the driver. Choose CSI when "the secret must never exist in etcd"; choose ESO when workloads already expect standard Kubernetes Secrets.
Trap

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

tick the dot when its check passes

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-a
outputcaptured 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

no
verify: yes, no, yes, no, no. For each "no", name what's missing (rule, binding, or scope). That secrets split (read yes, delete no) is intentional least-privilege design; find the comment explaining it in the file.

Turn developer into a ClusterRole and bind it inside team-b with a RoleBinding for user dev-b.

verify: 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-probe
outputcaptured 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.)

verify: the pod lists pods cleanly. Now re-run with -- 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 -d
outputcaptured 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
hunter2
verify: the sealed file holds zero plaintext, yet the unsealed Secret decodes back to hunter2. 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.

verify: 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.

verify: diagnosed and fixed in under 7 minutes, verified with restored 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 -15
outputcaptured 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]
verify: the username and groups echo back exactly as passed. Impersonating without --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 binder
outputcaptured 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" deleted
verify: the first attempt fails with an escalation error listing the rules you don't hold, and it succeeds once you grant bind 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 reporter
outputcaptured 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 namespace
verify: both tokens carry exp 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-found
outputcaptured 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 namespace
verify: the CreatedOnce 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-store
outputcaptured 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 namespace
verify: the resulting Secret contains a single key holding a full DSN stitched together from five fields you never wrote directly into the cluster.

By 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-found
outputcaptured 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 namespace
verify: the strict 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"
verify: the file in git keeps key names in plaintext and values as ciphertext, while the cluster Secret decodes cleanly to plaintext. Then notice the cleanup: deleting the Kustomization prunes the Secret, and the second commit removes the demo from the shared platform repo so it doesn't interfere with other GitOps exercises.

Self-check

answer before opening
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

study time, not exam time
  • 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 fake provider sits in ESO's provider list.
  • Offline: kubectl auth can-i --list, kubectl api-resources --verbs=list, and kubectl 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 decryption block.
free before 5.2make down-gitops