Courseiva

CCNA Minimize Microservice Vulnerabilities Questions

36 questions · Minimize Microservice Vulnerabilities · All types, answers revealed

1
MCQmedium

You need to drop all Linux capabilities from a container. Which YAML snippet is correct?

A.capabilities: { remove: ["ALL"] }
B.capabilities: { drop: ["ALL"] }
C.capabilities: { none: true }
D.securityContext: { capabilities: { drop: ["ALL"] } }
AnswerD

This is correct because the `securityContext` at the container level is the only place where Linux capabilities are configured in Kubernetes. The `capabilities.drop` list accepts `"ALL"` as a special token that removes every capability from the container's effective and permitted sets, giving a minimal attack surface. Because it is nested under `securityContext`, the kubelet applies it when creating the container via the container runtime.

Why this answer

In Kubernetes, to drop Linux capabilities from a container, you must use the `capabilities.drop` field inside `securityContext`. Option D correctly nests `capabilities` under `securityContext`. Option B is incorrect because it places `capabilities` directly under the container spec without the `securityContext` wrapper, which is not valid in most Kubernetes API versions.

Options A and C use invalid keywords (`remove` and `none`). Therefore, only Option D is correct.

Exam trap

CNCF often tests the distinction between `drop` and `remove` in the capabilities field, where `drop` is the correct Kubernetes API field name, and `remove` is a common but incorrect alternative that candidates might mistakenly use.

How to eliminate wrong answers

Option A is wrong because `remove` is not a valid field in the Kubernetes capabilities specification; the correct field is `drop`. Option C is wrong because `none: true` is not a valid syntax for managing capabilities in Kubernetes; capabilities must be explicitly dropped using the `drop` field. Option D is wrong because while the structure `securityContext: { capabilities: { drop: ["ALL"] } }` is technically correct, the question asks for the correct YAML snippet, and option B is the only one that directly provides the correct snippet without extraneous nesting; however, note that option D is also marked as correct in the answer options, but the question expects a single correct answer, and option B is the most concise and direct representation.

2
MCQmedium

A microservice running as a Deployment in a Kubernetes cluster needs to authenticate to a third-party API using a static API key. Which is the most secure way to store and inject this secret into the container?

A.Store the API key in a ConfigMap and expose it as an environment variable
B.Hardcode the API key in the container image
C.Store the API key in a Kubernetes Secret and mount it as a volume inside the container
D.Store the API key in a Kubernetes Secret and expose it as an environment variable
AnswerC

Secrets are designed for sensitive data; volume mounts avoid exposure in environment variable listings.

Why this answer

Mounting a Kubernetes Secret as a volume provides the most secure method for injecting sensitive data into a container. Unlike environment variables, which can be exposed through process listings, container logs, or `/proc` filesystem, a volume mount stores the secret in the container's filesystem with permissions restricted to the runtime user. This approach also supports automatic rotation of secret values without restarting the pod, as the filesystem is updated in place when the Secret object changes.

Exam trap

CNCF often tests the misconception that environment variables from Secrets are equally secure as volume mounts, but the trap is that environment variables are more exposed to runtime leaks and cannot be rotated without pod restart, whereas volume mounts offer better isolation and live update capabilities.

How to eliminate wrong answers

Option A is wrong because ConfigMaps store data in plaintext and are intended for non-sensitive configuration, not secrets like API keys. Option B is wrong because hardcoding secrets in a container image embeds them in the image layers, making them accessible to anyone with image pull access and violating immutable infrastructure principles. Option D is wrong because exposing a Secret as an environment variable increases the risk of leakage through container logs, debugging endpoints, or the `/proc/self/environ` file, and does not support seamless secret rotation without pod restart.

3
MCQmedium

You need to encrypt Kubernetes secrets at rest. Which resource should you configure?

A.EncryptionProvider
B.SecretEncryptionConfig
C.KMSProvider
D.EncryptionConfiguration
AnswerD

EncryptionConfiguration is the correct API resource, defined in apiserver.config.k8s.io/v1, that specifies encryption providers and their keys for etcd data. You pass it to the kube-apiserver via the --encryption-provider-config flag, and it governs how resources like Secrets are encrypted at rest. This is the only valid object among the options for configuring at-rest encryption.

Why this answer

Kubernetes uses an `EncryptionConfiguration` object to configure encryption at rest for secrets and other resources in etcd. This YAML-based resource defines which providers (e.g., `aescbc`, `kms`, `secretbox`) are used to encrypt data before it is written to the underlying storage. The API server reads this configuration from a file specified via the `--encryption-provider-config` flag, enabling transparent encryption and decryption of resource data.

Exam trap

A common Kubernetes certification pitfall is confusing the `EncryptionConfiguration` resource (the top-level configuration object) with the individual provider types like `KMSProvider` or `aescbc` that are listed inside it. Candidates may pick a provider name instead of the configuration resource itself.

How to eliminate wrong answers

Option A is wrong because `EncryptionProvider` is not a valid Kubernetes resource; the correct term is `EncryptionConfiguration`, which references provider types like `aescbc` or `kms` within its `resources` array. Option B is wrong because `SecretEncryptionConfig` is a fictional resource name; Kubernetes does not have a dedicated resource for secret-only encryption, and the `EncryptionConfiguration` object applies to any resource type listed in its `resources` field. Option C is wrong because `KMSProvider` is not a standalone resource; it is a provider type (e.g., `kms` or `kmstool`) that can be used inside an `EncryptionConfiguration` to delegate encryption to an external Key Management Service like AWS KMS or GCP Cloud KMS.

4
Multi-Selectmedium

Which TWO of the following are correct about container sandboxing technologies? (Select TWO)

Select 2 answers
A.Kata Containers run containers in lightweight VMs, providing hardware-level isolation.
B.gVisor provides a kernel-level sandbox by implementing a user-space kernel.
C.Kata Containers use the host kernel for system calls.
D.gVisor runs containers in separate VMs for each pod.
E.Both gVisor and Kata Containers require RuntimeClass to be used in Kubernetes.
AnswersA, B

Kata Containers provide hardware-level isolation by spawning each container or pod inside a lightweight VM that is booted with its own guest kernel, typically using KVM on Linux. The guest kernel handles system calls as if it were a real host, and the hypervisor enforces CPU and memory isolation at the hardware boundary. This design gives each container a full kernel of its own, which is a stronger isolation boundary than syscall interception because even a compromised guest kernel cannot directly access the host kernel.

Why this answer

Kata Containers provide hardware-level isolation by running each container or pod in a lightweight VM with its own guest kernel using KVM. Option B is correct because gVisor implements a user-space kernel (called Sentry) that intercepts system calls, providing a kernel-level sandbox without dedicated VMs. Option C is incorrect because Kata Containers use a guest kernel, not the host kernel.

Option D is incorrect because gVisor does not run containers in separate VMs; it runs as a kernel within the user space. Option E is incorrect because although RuntimeClass is commonly used to select non-default runtimes in Kubernetes, the statement is not universally required; it is a mechanism but not a strict requirement for using these technologies, making the claim that both 'require' RuntimeClass too absolute and thus false.

Exam trap

Candidates may be misled by the appealing combination of A, B, and E, but only A and B are correct. The statement in E is too absolute because RuntimeClass is not strictly required—it is an optional mechanism.

5
MCQmedium

A pod uses a Secret mounted as a volume. The Secret is updated. How can the pod consume the updated values without restarting?

A.Use a sidecar container that watches for changes and reloads the application
B.Update the pod spec to reference a new Secret version
C.The mounted volume is automatically updated over time
D.Delete and recreate the pod
AnswerC

For a Secret mounted as a regular volume (not via subPath or as a projected volume), the kubelet periodically syncs the Secret from the API server to the volume directory, so the file contents are updated automatically. This triggers inotify events that a well-designed application can watch to reload configuration without restarting the Pod. The update is eventually consistent and typically occurs within a minute, but the application must be coded to re-read the file from disk after receiving a change notification.

Why this answer

When a Secret is mounted as a volume in Kubernetes, the kubelet periodically syncs the secret data from the API server and updates the files in the volume. This means the pod can consume the updated values without needing a restart, as the files are refreshed automatically (with a default sync period of around 60 seconds). Option C correctly identifies this behavior.

Exam trap

Candidates often think that updating a Secret requires a pod restart, but in Kubernetes, Secrets mounted as volumes are automatically updated by the kubelet without restart.

How to eliminate wrong answers

Option A is wrong because while a sidecar container can watch for changes and reload the application, it is not the default or automatic mechanism; the question asks how the pod can consume updated values without restarting, and the built-in volume update handles that without requiring a sidecar. Option B is wrong because Kubernetes Secrets do not have versioning; you cannot reference a 'new Secret version' in the pod spec — you must update the same Secret object or create a new one and update the pod spec to reference the new name, which would require a pod restart. Option D is wrong because deleting and recreating the pod is unnecessary; the mounted volume is automatically updated by the kubelet, so restarting is not required.

6
Multi-Selecthard

Which ONE of the following is a valid Rego policy construct used in OPA Gatekeeper ConstraintTemplates to enforce security policies?

Select 1 answer
A.violation[{"msg": msg}] { condition }
B.allow { condition }
C.deny[{"msg": msg}] { condition }
D.audit { condition }
E.warn[{"msg": msg}] { condition }
AnswersA

The `violation[{"msg": msg}] { condition }` construct is the canonical rule format for Gatekeeper ConstraintTemplates. Gatekeeper's admission and audit controllers compile the template's Rego and expect a partial set rule named `violation`; whenever the `condition` evaluates to true, the set is non-empty and the constraint's enforcement action (deny, warn, or dryrun) is applied. The `msg` variable binds to a human-readable message that is surfaced in the audit results or admission response. This construct directly fulfills Gatekeeper's internal policy enforcement contract.

Why this answer

In OPA Gatekeeper ConstraintTemplates, the only Rego construct that directly triggers a constraint violation is `violation[{"msg": msg}] { condition }`. When the condition evaluates to true, Gatekeeper generates a violation message. The `allow` and `deny` rules are not standard constructs for enforcing constraints in Gatekeeper; they are general Rego rules used in other OPA contexts but not within ConstraintTemplates to report violations.

Options D (`audit`) and E (`warn`) are also not valid Rego constructs for Gatekeeper constraints.

Exam trap

Candidates may mistakenly think that `allow` and `deny` are valid constructs within Gatekeeper ConstraintTemplates. In reality, only the `violation` rule is used to trigger constraint violations. `allow` and `deny` are general Rego rules used in other OPA contexts, but not for defining Gatekeeper constraints.

7
MCQmedium

You are implementing a policy to ensure all containers in a namespace run as non-root. Which of the following is the most appropriate approach to enforce this at the cluster level?

A.Create a PodSecurityPolicy that requires runAsNonRoot
B.Use OPA/Gatekeeper with a ConstraintTemplate that checks runAsNonRoot is set to true
C.Set runAsNonRoot in the securityContext of each Pod spec manually
D.Configure a ValidatingAdmissionPolicy with a CEL rule requiring runAsNonRoot
AnswerB

OPA/Gatekeeper can enforce policies via admission webhooks, and a ConstraintTemplate can validate that all containers have runAsNonRoot: true.

Why this answer

OPA/Gatekeeper allows you to enforce custom policies at the cluster level via ConstraintTemplates and Constraints. By creating a ConstraintTemplate that checks `runAsNonRoot: true` in the Pod securityContext, you can ensure all Pods in a namespace (or cluster-wide) run as non-root, without modifying individual Pod specs. This approach is native to Kubernetes admission control and provides a flexible, cluster-wide enforcement mechanism.

Exam trap

A common pitfall in the CKS exam is assuming that PodSecurityPolicy (PSP) is still a viable cluster-level enforcement mechanism. However, PSP was deprecated in Kubernetes v1.21 and removed in v1.25. The modern approach uses either OPA/Gatekeeper with ConstraintTemplates or Kubernetes Pod Security Standards (PSS) via labels or built-in admission controllers.

Candidates often choose PSP out of habit, but it is no longer available in recent clusters.

How to eliminate wrong answers

Option A is wrong because PodSecurityPolicy (PSP) is deprecated in Kubernetes v1.21 and removed in v1.25, so it is not a viable cluster-level enforcement mechanism for current CKS exam contexts. Option C is wrong because manually setting `runAsNonRoot` in each Pod spec is not a cluster-level enforcement; it requires per-Pod changes and does not prevent non-compliant Pods from being created. Option D is wrong because ValidatingAdmissionPolicy with CEL is a newer feature (alpha in v1.26, beta in v1.28) and is not as mature or widely adopted as OPA/Gatekeeper for complex policy enforcement; it also lacks the rich constraint framework that OPA/Gatekeeper provides for this specific use case.

8
MCQmedium

A security engineer wants to enable mutual TLS (mTLS) between services in an Istio service mesh. Which Istio resource should be used to define the mTLS mode for the entire mesh?

A.DestinationRule with trafficPolicy.tls.mode: ISTIO_MUTUAL
B.PeerAuthentication with mTLS mode set to STRICT
C.VirtualService with tls configuration
D.ServiceEntry with mTLS enabled
AnswerB

PeerAuthentication with mTLS mode set to STRICT is the correct approach because PeerAuthentication is the Istio policy resource that enforces TLS at the server side. When mode: STRICT is applied, the sidecar proxy requires all incoming connections to use mutual TLS and rejects plaintext traffic, thereby enforcing mTLS for the selected workloads. This can be set at the mesh, namespace, or workload level, making it the standard way to enable mesh-wide mTLS.

Why this answer

PeerAuthentication is the Istio resource specifically designed to define the authentication policy for workloads, including the mTLS mode. Setting `mTLS.mode: STRICT` in a PeerAuthentication policy enforces mutual TLS for all traffic within the mesh, ensuring that every service-to-service connection requires a valid client certificate. This is the correct resource for mesh-wide mTLS enforcement, as it operates at the authentication layer rather than the traffic routing layer.

Exam trap

A common pitfall in the CKS exam is confusing DestinationRule (which handles traffic routing and connection pool settings) with PeerAuthentication (which handles mTLS enforcement). Candidates often choose DestinationRule because it has a tls field, but for mesh-wide mTLS, PeerAuthentication with mode: STRICT is the correct resource.

How to eliminate wrong answers

Option A is wrong because DestinationRule with `trafficPolicy.tls.mode: ISTIO_MUTUAL` configures TLS settings for traffic routing and load balancing, but it does not enforce authentication or mTLS at the service identity level; it only specifies the TLS mode for connections to a specific host, not the entire mesh. Option C is wrong because VirtualService is used for traffic routing, retries, and fault injection, not for defining mTLS or authentication policies; it has no `tls` configuration for mTLS mode. Option D is wrong because ServiceEntry is used to register external services into the mesh, not to define mTLS policies for internal mesh traffic; enabling mTLS on a ServiceEntry would apply to external endpoints, not the entire mesh.

9
MCQmedium

Which of the following is a best practice for storing sensitive information like database passwords in Kubernetes?

A.Use environment variables in the pod spec to pass secrets
B.Mount secrets as volumes in the pod
C.Embed secrets as literals in the pod YAML file
D.Store them in ConfigMaps
AnswerB

Mounting as volumes reduces the risk of exposure through environment variables.

Why this answer

Mounting secrets as volumes ensures that sensitive data is stored in the in-memory tmpfs filesystem, which is never written to disk and is automatically removed when the pod is deleted. This approach also allows for automatic updates of secret values when the Secret object is modified, without requiring a pod restart, and provides better access control through filesystem permissions.

Exam trap

Candidates often believe that environment variables are a secure way to pass secrets because they are 'injected' at runtime, but the trap is that environment variables are visible via /proc/self/environ, logs, and kubectl exec commands, making them less secure than volume mounts.

How to eliminate wrong answers

Option A is wrong because environment variables in the pod spec are exposed to all processes in the container, can be leaked through logs or debugging tools, and are not automatically updated when the Secret changes. Option C is wrong because embedding secrets as literals in the pod YAML file stores them in plaintext in the API server's etcd database and version control systems, violating the principle of least privilege and making them visible to anyone with access to the manifest. Option D is wrong because ConfigMaps are designed for non-sensitive configuration data and store values in plaintext; they lack encryption at rest and are not intended for secrets like database passwords.

10
Multi-Selectmedium

Which ONE of the following is a valid method to restrict a container's filesystem to read-only in Kubernetes?

Select 1 answer
A.Use a ConfigMap volume with defaultMode 0444
B.Set readOnly: true on a hostPath volume mount
C.Set readOnlyRootFilesystem: true in the container's securityContext
D.Mount an emptyDir volume with readOnly: true
AnswersC

Setting readOnlyRootFilesystem: true in the container's securityContext causes the entire root filesystem of the container to be mounted read-only, so any attempt to write to filesystem paths that are part of the image or container layer will fail. This is the standard, recognized method to enforce a read-only container filesystem, because it applies globally to the container's base filesystem rather than to a specific volume. Note that this does not affect volumes that are explicitly mounted; each volume still needs to be explicitly marked readOnly if that is desired.

Why this answer

The only valid method listed. Setting `readOnlyRootFilesystem: true` in the container's securityContext directly makes the container's root filesystem read-only. Options A, B, and D only make specific volumes read-only (ConfigMap, hostPath, emptyDir), but do not prevent writes to the container's own filesystem (e.g., /etc, /tmp, /var).

Therefore, only option C correctly restricts the container's filesystem to read-only.

Exam trap

In the CKS exam, the distinction between making a specific volume read-only (e.g., via `readOnly: true` on a mount) versus making the entire container's root filesystem read-only via `readOnlyRootFilesystem` is often tested. Candidates mistakenly think that setting `readOnly: true` on any volume achieves the same effect.

11
MCQmedium

A cluster administrator wants to ensure that all pods in a namespace run with the `seccomp` profile set to `RuntimeDefault`. Which OPA Gatekeeper ConstraintTemplate would achieve this?

A.violation[{"msg": "Seccomp profile must be RuntimeDefault"}] { input.review.object.spec.containers[_].securityContext.seccompProfile.type == "Unconfined" }
B.violation[{"msg": "Seccomp profile must be RuntimeDefault"}] { input.review.object.spec.containers[_].securityContext.seccompProfile == "RuntimeDefault" }
C.violation[{"msg": "Seccomp profile must be RuntimeDefault"}] { input.review.object.spec.securityContext.seccompProfile.type != "RuntimeDefault" }
D.violation[{"msg": "Seccomp profile must be RuntimeDefault"}] { input.review.object.spec.containers[_].securityContext.seccompProfile.type != "RuntimeDefault" }
AnswerD

This denies pods that do not have the required seccomp profile.

Why this answer

It uses the Rego rule `input.review.object.spec.containers[_].securityContext.seccompProfile.type != "RuntimeDefault"` to check that every container in the pod has its seccomp profile type set to `RuntimeDefault`. This ensures that any container without the required profile triggers a violation, enforcing the cluster administrator's policy.

Exam trap

The exam often tests the distinction between pod-level (`spec.securityContext`) and container-level (`spec.containers[_].securityContext`) security contexts, and the trap here is that candidates mistakenly check the pod-level field, which does not enforce the policy on individual containers.

How to eliminate wrong answers

Option A is wrong because it only triggers a violation when the seccomp profile type is `Unconfined`, which would allow pods with no seccomp profile set (defaulting to unconfined) or other types to pass, failing to enforce `RuntimeDefault`. Option B is wrong because it incorrectly compares `seccompProfile` to a string `"RuntimeDefault"` instead of accessing the `.type` field, and it checks for equality rather than inequality, so it would only allow pods that explicitly set the profile to `RuntimeDefault` but not catch those missing the setting. Option C is wrong because it checks `spec.securityContext` at the pod level instead of `spec.containers[_].securityContext` at the container level, missing container-specific overrides and potentially allowing pods where only the pod-level seccomp profile is set incorrectly.

12
MCQmedium

A DevOps team deploys a microservice that needs to access a third-party API using credentials stored in a Kubernetes Secret. The team wants to minimize the risk of credential exposure. Which approach best achieves this goal while following security best practices?

A.Store the credentials in a Secret and mount it as a volume with default permissions.
B.Store the credentials in a Secret, mount it as a read-only volume, and use a dedicated service account with RBAC limiting access to that secret.
C.Use a sidecar container that reads the secret from a file and exposes it via a Unix socket, running the container as root.
D.Store the credentials in a ConfigMap and inject them as environment variables.
AnswerB

This approach is correct because it combines confidentiality, integrity, and least privilege: mounting the Secret as a read-only volume prevents containers from modifying the credentials at runtime, while a dedicated ServiceAccount paired with a Role and RoleBinding strictly limits which pods can get or list the Secret through the Kubernetes API. The RBAC policy ensures that only the microservice's own service account can access the Secret, reducing the risk of unauthorized retrieval by other workloads in the cluster.

Why this answer

Mounting the Secret as a read-only volume prevents runtime modification, and using a dedicated service account with RBAC ensures only the specific microservice can access the Secret. This follows the principle of least privilege and minimizes exposure, as the credentials are never injected as environment variables (which can be leaked via /proc or logs) and are only available to the intended pod.

Exam trap

CNCF often tests the misconception that environment variables are safe for secrets, but the trap here is that environment variables can be exposed via `/proc/self/environ`, logs, or debug endpoints, making volume mounts with strict permissions and RBAC the more secure choice.

How to eliminate wrong answers

Option A is wrong because mounting a Secret with default permissions (typically 0644) allows other processes on the node to read the secret files, increasing exposure risk. Option C is wrong because running the sidecar container as root violates the principle of least privilege and could allow privilege escalation; a Unix socket approach adds complexity without addressing the core credential exposure issue. Option D is wrong because ConfigMaps are not designed for sensitive data—they lack encryption at rest and are often stored in plaintext in etcd, making credentials vulnerable to exposure.

13
MCQeasy

A security engineer needs to ensure that all containers in a cluster run as non-root users. Which Pod Security Context field should be set to enforce this requirement?

A.runAsNonRoot: true
B.runAsUser: 1000
C.privileged: false
D.allowPrivilegeEscalation: false
AnswerA

The `runAsNonRoot: true` Pod security context setting forces Kubernetes to validate that the container image specifies a non-root user (e.g., via USER in the Dockerfile) or that a `runAsUser` value is explicitly set to a non-zero UID; if the image would run as UID 0, the Pod API request is rejected during admission, preventing the container from ever starting as root. This is the only option that directly enforces non-root execution at the container level, independent of the image's default behavior. It is the correct choice for the requirement to ensure all containers run as non-root.

Why this answer

Setting `runAsNonRoot: true` in the Pod Security Context explicitly instructs the container runtime to verify that the container's user ID is non-zero (i.e., not root). If the container image is configured to run as root (UID 0), the Pod will fail to start, enforcing the requirement that all containers run as non-root users.

Exam trap

The CKS exam often tests the distinction between setting a specific user ID (`runAsUser`) and enforcing a non-root check (`runAsNonRoot`), where candidates mistakenly think that specifying a non-zero UID alone guarantees the container is not running as root, ignoring that the image might still run as root if the UID is not set in the image.

How to eliminate wrong answers

Option B is wrong because `runAsUser: 1000` only sets the user ID to 1000 but does not prevent the container from running as root if the image is configured to run as root; the runtime will still run as UID 1000, but the check against root is not enforced. Option C is wrong because `privileged: false` only disables privileged mode (e.g., access to host devices) but does not enforce a non-root user; a container can still run as root without privileged mode. Option D is wrong because `allowPrivilegeEscalation: false` prevents processes from gaining more privileges than their parent (e.g., via setuid binaries) but does not require the container to start as a non-root user; it can still start as root and simply not escalate further.

14
MCQhard

You are configuring encryption at rest for Kubernetes secrets. After creating an EncryptionConfiguration with aescbc provider, which additional step is required to enable encryption?

A.Restart the kube-apiserver with --encryption-provider-config flag
B.Apply the EncryptionConfiguration as a ConfigMap
C.Restart the kube-scheduler
D.Recreate all secrets in the cluster
AnswerA

The kube-apiserver reads --encryption-provider-config only at process startup, so the configuration file must be in place and the control plane component restarted for the change to take effect. This flag points to a YAML/JSON file that defines how to encrypt secrets at the etcd level. Without the restart, the apiserver continues using its previous, unencrypted write path. This is the required first step before any existing data can be migrated to encrypted form.

Why this answer

The EncryptionConfiguration resource defines how Kubernetes should encrypt data at rest, but it is not automatically applied. The kube-apiserver must be restarted with the `--encryption-provider-config` flag pointing to the configuration file so that it reads and enforces the encryption settings for all subsequent writes to etcd. Without this flag, the apiserver ignores the EncryptionConfiguration entirely.

Exam trap

A common pitfall is thinking that creating the EncryptionConfiguration resource is sufficient. In reality, the kube-apiserver must be configured with the --encryption-provider-config flag and restarted to activate encryption.

How to eliminate wrong answers

Option B is wrong because an EncryptionConfiguration is a custom resource, not a ConfigMap; applying it as a ConfigMap would not be recognized by the kube-apiserver. Option C is wrong because the kube-scheduler does not handle secret storage or encryption; encryption at rest is managed solely by the kube-apiserver when writing to etcd. Option D is wrong because existing secrets are not automatically re-encrypted; the encryption provider only applies to new or updated secrets, and existing secrets remain unencrypted until they are rewritten.

15
MCQhard

A pod runs with a service mesh sidecar (Istio). The team wants to enforce mutual TLS (mTLS) for all traffic between services in the 'production' namespace. Which resource should be applied?

A.DestinationRule with trafficPolicy: tls: mode: ISTIO_MUTUAL
B.VirtualService with TLS settings
C.PeerAuthentication with mode: STRICT in the namespace
D.ServiceEntry with mTLS enabled
AnswerC

PeerAuthentication is the Istio policy resource specifically designed to control mTLS adoption at mesh, namespace, or workload granularity. Setting mode: STRICT in the production namespace requires every service-to-service communication to be mutual TLS; any plaintext request will be rejected by the sidecar proxies, effectively enforcing the team's requirement. This is the standard and recommended way to enforce mTLS for an entire namespace.

Why this answer

PeerAuthentication with mode: STRICT enforces mutual TLS at the service mesh level by requiring all traffic within the namespace to use TLS certificates for both sides of the connection. This is the correct Istio resource to enforce mTLS for all services in the 'production' namespace, as it sets a namespace-wide policy that overrides any permissive defaults.

Exam trap

CNCF often tests the distinction between PeerAuthentication (which enforces mTLS on the server side) and DestinationRule (which configures client-side TLS), leading candidates to mistakenly choose DestinationRule for namespace-wide mTLS enforcement.

How to eliminate wrong answers

Option A is wrong because DestinationRule with trafficPolicy: tls: mode: ISTIO_MUTUAL configures client-side TLS settings for traffic to specific hosts, but does not enforce server-side mTLS acceptance; it only sets the client's TLS mode and can be bypassed if the server allows plaintext. Option B is wrong because VirtualService is used for traffic routing (e.g., canary deployments, A/B testing) and does not handle TLS authentication or mTLS enforcement; its TLS settings are for ingress gateway TLS termination, not peer authentication. Option D is wrong because ServiceEntry is used to register external services into the mesh and enable mTLS for those endpoints, but it does not enforce mTLS for internal services within the namespace.

16
MCQhard

An OPA/Gatekeeper ConstraintTemplate is defined with the following Rego rule: violation[{"msg": msg}] { container := input.review.object.spec.containers[_] container.securityContext.runAsNonRoot != true msg := "Container must run as non-root" } What happens when a pod is submitted with a container that has runAsNonRoot: true?

A.The pod is admitted but an audit log is generated
B.The pod is admitted
C.The pod is denied with a message
D.The pod is mutated to set runAsNonRoot
AnswerB

For a pod that explicitly sets securityContext.runAsNonRoot: true, the Gatekeeper constraint's violation condition (runAsNonRoot != true) evaluates to false. Since the Rego policy only triggers a denial when a violation is found, no violation exists and the admission request is allowed. Thus the pod is admitted without any message, mutation, or further side effects.

Why this answer

The Rego rule `container.securityContext.runAsNonRoot != true` only triggers a violation when the field is not set to `true`. When `runAsNonRoot: true` is explicitly set, the condition evaluates to `false`, so no violation is generated, and the pod is admitted without any denial or mutation. OPA/Gatekeeper by default enforces constraints by denying admission; it does not mutate resources or generate audit logs unless specifically configured for dry-run or audit mode.

Exam trap

The CKS exam often tests the subtle difference between `!= true` and `== false` in Rego — candidates mistakenly think `!= true` catches only `false` values, but it also catches `null` (missing field), and they forget that an explicit `true` passes the check, leading them to choose denial or mutation options.

How to eliminate wrong answers

Option A is wrong because OPA/Gatekeeper does not generate audit logs for admitted pods unless the constraint is explicitly configured in audit mode (e.g., with `spec.sync` and `spec.match`), and the Rego rule here is a validation rule that either denies or allows; it does not produce audit logs on success. Option C is wrong because the pod is not denied; the violation condition is false when `runAsNonRoot: true`, so no denial message is returned. Option D is wrong because OPA/Gatekeeper is a policy engine that validates and denies, not a mutating webhook; it cannot mutate fields like `runAsNonRoot` — mutation requires a separate MutatingAdmissionWebhook or a mutating Gatekeeper feature (e.g., via `modify` rules) which is not used here.

17
MCQmedium

A team wants to use an external secret manager (HashiCorp Vault) to inject secrets into pods. Which approach is most aligned with Kubernetes best practices?

A.Use a ConfigMap to mount secrets as files
B.Store secrets as environment variables in the pod spec
C.Use kubectl exec to copy secrets into the container at startup
D.Use a mutating webhook that injects a sidecar container to fetch secrets and mount them as volumes
AnswerD

This approach securely injects secrets without exposing them in the pod spec.

Why this answer

It follows the Kubernetes best practice of using a mutating admission webhook to inject a sidecar container (e.g., Vault Agent or Bank-Vaults) that authenticates with HashiCorp Vault, fetches secrets, and mounts them as volumes into the pod. This approach avoids storing secrets in etcd (as ConfigMaps or environment variables do) and eliminates the need for manual secret injection, aligning with the principle of least privilege and dynamic secret management.

Exam trap

The CKS exam often tests the misconception that ConfigMaps or environment variables are acceptable for secrets, but the exam emphasizes that any secret stored in etcd (even if base64-encoded) is not secure, and the only best-practice approach is to use external secret stores with sidecar injection or CSI drivers.

How to eliminate wrong answers

Option A is wrong because ConfigMaps store data in etcd in plaintext (unless encrypted at rest) and are not designed for secret management; they are for non-confidential configuration data. Option B is wrong because storing secrets as environment variables in the pod spec exposes them in the pod’s spec (visible via kubectl describe) and in etcd, and they can be leaked through process listings or logs. Option C is wrong because using kubectl exec to copy secrets into a container at startup is an insecure, manual, and non-scalable practice that violates the principle of immutable infrastructure and leaves secrets in the container filesystem without proper lifecycle management.

18
MCQmedium

You have created a ValidatingWebhookConfiguration to reject pods without resource limits. When you try to create a pod without limits, it is created successfully. What is the most likely reason?

A.The webhook is not matching the namespace labels
B.The webhook service is not running or is unreachable
C.The webhook is configured with failurePolicy: Fail
D.The pod is being created by a controller like a Deployment
AnswerB

If the webhook service is down, the API server will fail open (depending on failurePolicy) and allow the pod creation.

Why this answer

The most likely reason a pod without resource limits is created successfully despite a ValidatingWebhookConfiguration is that the webhook service itself is not running or is unreachable. When the API server cannot contact the webhook endpoint, the default behavior (failurePolicy: Ignore) allows the request to proceed, so the pod is created without validation. If the webhook were functioning correctly, it would reject the pod; thus, the failure to reject indicates a connectivity or service issue.

Exam trap

Candidates may incorrectly assume the ValidatingWebhookConfiguration is misconfigured (e.g., missing objectSelector or wrong failurePolicy) when the actual issue is that the webhook backend service is unreachable. In Kubernetes, if the API server cannot reach the webhook server, the failurePolicy (default Ignore) allows the pod creation, so the pod passes through without validation. This is a common pitfall where the webhook service itself is not running or not accessible, rather than a configuration error.

How to eliminate wrong answers

Option A is wrong because the question does not mention namespace labels or any namespaceSelector in the webhook configuration; even if labels were mismatched, the webhook would simply not be invoked for that namespace, but the pod would still be created without limits — however, the most likely reason given the scenario is a service issue, not a label mismatch. Option C is wrong because failurePolicy: Fail would cause the API server to reject the pod if the webhook is unreachable, which contradicts the pod being created successfully; the default failurePolicy is Ignore, which allows the pod through when the webhook is down. Option D is wrong because controllers like Deployments still go through the same admission webhook process; the webhook would reject the pod regardless of whether it is created directly or via a controller.

19
MCQeasy

Which of the following is a best practice for storing sensitive data like passwords in Kubernetes?

A.Store them in ConfigMaps [wrong]
B.Store them in Secrets and mount them as volumes [CORRECT]
C.Store them as environment variables in the Pod spec [wrong]
D.Store them as labels on Pods [wrong]
AnswerB

Storing Secrets and mounting them as volumes is a best practice because this method exposes data to the container as files on a filesystem, avoiding leakage through environment variables or process listings. Mounted Secrets support file-level permissions (e.g., read-only) and can be updated in place, allowing applications to pick up changes without redeployment. Additionally, the use of Secrets with volume mounts enables fine-grained RBAC controls and integrates with etcd encryption for Secrets, providing defense in depth for sensitive data.

Why this answer

Kubernetes Secrets are designed to store sensitive data such as passwords, API keys, and certificates. Mounting a Secret as a volume ensures the data is written to a tmpfs in-memory filesystem (not to disk), reducing the risk of exposure via host filesystem access. This approach also avoids leaking secrets through environment variable dumps or logs, and supports automatic rotation when the Secret is updated.

Exam trap

A common trap is believing that environment variables are safe for secrets because they are 'not written to disk', but they are exposed via /proc/<pid>/environ, appear in logs, crash dumps, and can be read by any process with access to the container's environment.

How to eliminate wrong answers

Option A is wrong because ConfigMaps store data in plaintext and are intended for non-sensitive configuration, not secrets; they lack encryption at rest by default and are often logged or exposed in etcd snapshots. Option C is wrong because storing secrets as environment variables in the Pod spec makes them visible in the container's environment, accessible via /proc/self/environ, and can be leaked in logs or debugging tools; they also cannot be rotated without Pod restart. Option D is wrong because labels on Pods are metadata used for selection and organization, not for storing sensitive data; they are visible in API responses and logs, and are not encrypted.

20
MCQeasy

Which of the following is the best practice for providing sensitive data like passwords to a pod?

A.Mount secrets as volumes into the pod.
B.Use environment variables to inject secrets directly.
C.Pass secrets via command-line arguments.
D.Hardcode the secret in the container image.
AnswerA

Mounting secrets as volumes provides a filesystem-based interface that keeps the secret out of process listings, environment variables, and command-line arguments. The volume is mounted read-only and backed by tmpfs, so the secret is never written to a container's writable layer. You can also use defaultMode to set strict file permissions, limiting access to the specific UID/GID of the container. This approach also enables secrets to be updated (with some delay) by simply changing the Secret object, without a coordinated environment variable update.

Why this answer

Mounting secrets as volumes into the pod is the best practice because it ensures that secrets are stored in a tmpfs (RAM-backed) filesystem, which is never written to disk and is automatically cleaned up when the pod terminates. This approach also allows the kubelet to update the secret contents in the volume without restarting the pod, and it avoids exposing the secret in process listings, logs, or environment variable dumps.

Exam trap

A common trap is thinking that environment variables are safe because they are not in the image, but they are still exposed in the pod spec, logs, and process listings, making them less secure than volume mounts.

How to eliminate wrong answers

Option B is wrong because environment variables can be leaked through the pod's spec, logs, or /proc filesystem, and they are not automatically rotated when the secret changes. Option C is wrong because command-line arguments are visible in the process table (e.g., via `ps aux`) and are stored in the pod's definition, making them easily accessible to anyone with read access to the pod's metadata. Option D is wrong because hardcoding secrets in a container image embeds them in the image layers, which can be inspected by anyone with access to the registry and violates the principle of immutable infrastructure.

21
MCQeasy

Which command creates a validating webhook configuration that checks all pods in the cluster?

A.kubectl create mutatingwebhookconfiguration my-webhook --from-file=webhook.yaml
B.kubectl run webhook --image=webhook
C.kubectl create validatingwebhookconfiguration my-webhook --from-file=webhook.yaml
D.kubectl apply -f webhook.yaml --validating
AnswerC

Correct.

Why this answer

`kubectl create validatingwebhookconfiguration` is the specific command to create a ValidatingWebhookConfiguration resource from a YAML file, which can be configured to intercept and validate pod creation requests across the cluster. This resource allows you to define a webhook that checks all pods before they are admitted, enforcing custom validation logic.

Exam trap

The CKS exam often tests the distinction between mutating and validating webhooks. Candidates may confuse `kubectl create mutatingwebhookconfiguration` with the validating variant, or assume `kubectl apply` with a flag can create a validating webhook.

How to eliminate wrong answers

Option A is wrong because `kubectl create mutatingwebhookconfiguration` creates a MutatingWebhookConfiguration, which mutates objects before admission, not a validating webhook that checks pods. Option B is wrong because `kubectl run webhook --image=webhook` simply runs a pod from an image named 'webhook'; it does not create any webhook configuration or validate pods. Option D is wrong because `kubectl apply -f webhook.yaml --validating` is invalid syntax; the `--validating` flag does not exist for `kubectl apply`, and ValidatingWebhookConfigurations are created via `kubectl create` or `kubectl apply` without such a flag.

22
MCQhard

A security team wants to use OPA/Gatekeeper to enforce that all namespaces must have a label 'security-tier' with value 'high' or 'medium'. What is the correct approach?

A.Write a MutatingWebhookConfiguration that adds the label automatically.
B.Use kubectl label command with a --validate flag.
C.Create a ValidatingWebhookConfiguration that directly contains the Rego policy.
D.Create a ConstraintTemplate with Rego that denies namespaces missing the label, then create a Constraint referencing that template.
AnswerD

This is the canonical OPA Gatekeeper workflow. A ConstraintTemplate defines a reusable Rego policy (e.g., detecting a missing required label) and specifies the target resource kind, such as namespaces. A Constraint then instantiates that template, setting the required label parameter and enforcing it against all namespaces. When a label-less namespace creation is attempted, the Gatekeeper admission webhook evaluates the Rego and rejects it, satisfying the 'deny namespaces missing the label' requirement.

Why this answer

OPA/Gatekeeper enforces policies via a two-part model: a ConstraintTemplate defines the Rego logic (e.g., denying a namespace if it lacks the required label), and a Constraint instantiates that template with specific parameters (e.g., 'security-tier' with values 'high' or 'medium'). This decouples policy definition from enforcement, allowing Gatekeeper's admission webhook to reject non-compliant resources at creation or update time.

Exam trap

The key distinction in OPA/Gatekeeper is between mutation (MutatingWebhookConfiguration) and validation (ValidatingWebhookConfiguration), and that policies must be defined via ConstraintTemplates and Constraints, not embedded directly in webhook configurations.

How to eliminate wrong answers

Option A is wrong because MutatingWebhookConfiguration can add labels automatically, but the question requires enforcement (denial), not mutation; also, OPA/Gatekeeper uses ValidatingWebhookConfiguration, not MutatingWebhookConfiguration, for policy enforcement. Option B is wrong because kubectl label with a --validate flag does not exist; kubectl validate is not a native command for enforcing OPA policies. Option C is wrong because a ValidatingWebhookConfiguration cannot directly contain Rego policy; it only registers the webhook endpoint (e.g., Gatekeeper's service), while the actual Rego logic resides in ConstraintTemplates and Constraints.

23
MCQmedium

You want to run a container with gVisor (runsc) runtime for sandboxing. Which resource is required to use a non-default runtime?

A.PodSecurityPolicy
B.ContainerRuntime resource
C.RuntimeClass resource
D.Node runtime configuration only
AnswerC

RuntimeClass is the correct mechanism because it is a cluster-scoped resource that maps a runtime handler name (for example, runsc) to a specific CRI runtime available on nodes. A pod opts into that runtime by setting the runtimeClassName field in its spec. The kubelet reads this field and launches the pod using the corresponding handler, which for gVisor means the runsc OCI runtime executes the container inside a user-space kernel. This abstraction allows you to mix sandboxed and regular pods on the same cluster and update the runtime implementation without changing pod specs.

Why this answer

In Kubernetes, to use a non-default runtime like gVisor (runsc), you must define a RuntimeClass resource that references the runtime handler (e.g., 'runsc') configured on the node. The RuntimeClass acts as a bridge between the Pod spec and the node's container runtime configuration, allowing the scheduler to select the appropriate runtime for sandboxing. Without a RuntimeClass, the default runtime (typically runc) is used, which does not provide the same isolation level.

Exam trap

The CKS exam often tests the misconception that node-level runtime installation alone is sufficient to use a non-default runtime, but the CKS exam emphasizes that a RuntimeClass resource must be created and referenced in the Pod spec to enable runtime selection.

How to eliminate wrong answers

Option A is wrong because PodSecurityPolicy (deprecated in v1.21 and removed in v1.25) controls security contexts and pod-level permissions, not the selection of container runtimes. Option B is wrong because there is no native 'ContainerRuntime' resource in Kubernetes; runtime selection is handled via RuntimeClass, not a dedicated resource for the runtime itself. Option D is wrong because node runtime configuration alone is insufficient; while the node must have the runtime installed and configured, the Pod must explicitly reference a RuntimeClass to opt into using that non-default runtime.

24
MCQmedium

You need to encrypt secrets at rest in a Kubernetes cluster. What must be configured?

A.Create an EncryptionConfiguration object in the cluster and pass it to kube-apiserver via --encryption-provider-config
B.Set the environment variable ENCRYPT_SECRETS=true on the kube-controller-manager
C.Use a MutatingWebhookConfiguration to encrypt secrets before storage
D.Enable the 'SecretEncryption' feature gate on all control plane components
AnswerA

The Kubernetes API server encrypts resources at the storage layer by reading an EncryptionConfiguration file supplied via the --encryption-provider-config flag. This configuration defines providers — such as aescbc, kms, or secretbox — and which resource types (like secrets) are encrypted before being written to etcd. The API server must be restarted with this flag, and the configuration file must be mounted into the API server pod or accessible on the host.

Why this answer

Kubernetes encrypts secrets at rest by defining an EncryptionConfiguration object that specifies which encryption providers (e.g., AES-CBC, secretbox, or KMS) to use, and then passing the configuration file to the kube-apiserver via the `--encryption-provider-config` flag. This ensures that when the API server writes secrets to etcd, they are encrypted before storage, and decrypted on read, meeting the requirement for encrypting secrets at rest.

Exam trap

The trap here is that candidates may think encryption at rest can be achieved via a webhook or a feature gate, but in reality it requires a specific configuration file passed to the kube-apiserver, and no feature gate or environment variable exists for this purpose.

How to eliminate wrong answers

Option B is wrong because the kube-controller-manager does not handle secret storage or encryption; encryption at rest is solely the responsibility of the kube-apiserver, and there is no `ENCRYPT_SECRETS` environment variable recognized by any control plane component. Option C is wrong because a MutatingWebhookConfiguration can modify resources before they are stored, but it cannot encrypt the data at the storage layer; encryption at rest must be performed by the API server using a configured encryption provider, not by a webhook. Option D is wrong because there is no `SecretEncryption` feature gate in Kubernetes; encryption at rest is configured via the `--encryption-provider-config` flag and does not require enabling any feature gate.

25
MCQmedium

A pod manifests with securityContext: { runAsNonRoot: true, runAsUser: 1001 }. However, the container image expects to run as root (UID 0). What will happen when the pod is created?

A.The container runs as root because runAsUser overrides runAsNonRoot
B.The container fails to start because it cannot run as root
C.The container runs as user 1001
D.The pod runs, but the securityContext is ignored
AnswerC

This is the correct behavior. The securityContext.runAsUser field explicitly sets the UID for the container's main process, overriding any USER directive from the image. Because the value is 1001, which is a non-root UID, it concurrently satisfies the runAsNonRoot constraint. The kubelet applies both settings during container startup: runAsUser determines the actual UID, and runAsNonRoot verifies that the resolved UID is not 0, ensuring the container runs as user 1001.

Why this answer

When `runAsNonRoot: true` is set, Kubernetes enforces that the container cannot run as root (UID 0). However, the pod also specifies `runAsUser: 1001`, which tells Kubernetes to run the container as UID 1001. Since UID 1001 is non-root, the `runAsNonRoot` constraint is satisfied.

The container image's expectation to run as root is irrelevant because Kubernetes overrides the user with the specified `runAsUser`. Therefore, the container will start and run as user 1001.

Exam trap

The trap is that candidates think `runAsNonRoot` alone blocks execution if the image expects root, but they overlook that `runAsUser` can override the image's user to a non-root UID. In this case, the container runs successfully as user 1001, not fails.

How to eliminate wrong answers

Option A is wrong because `runAsNonRoot` takes precedence over `runAsUser` when there is a conflict; it does not allow root execution. Option C is wrong because the container image expects to run as root, and the `runAsNonRoot` flag prevents the container from starting at all, so it never runs as user 1001. Option D is wrong because the securityContext is not ignored; it is enforced, and the container fails to start due to the violation.

26
MCQmedium

You are implementing a Gatekeeper policy to deny pods that run as root. Which Rego rule should you include in the ConstraintTemplate?

A.allow[{"msg": msg}] { msg := "container runs as root"; input.spec.containers[_].securityContext.runAsNonRoot == false }
B.deny[msg] { msg := "container runs as root"; not input.spec.containers[_].securityContext.runAsNonRoot }
C.deny[{"msg": msg}] { msg := "container runs as root"; not input.spec.containers[_].securityContext.runAsNonRoot }
D.deny[msg] { input.spec.containers[_].securityContext.runAsNonRoot == false }
AnswerC

This option fails to deny pods that specifically run as root (UID 0). The rule `not input.spec.containers[_].securityContext.runAsNonRoot` only checks for the absence or falsity of the `runAsNonRoot` flag. A container can still run as a non-root user (e.g., UID 1000) even if `runAsNonRoot` is unset, making this rule too broad for the objective of identifying actual root execution. It is tempting because `runAsNonRoot` relates to root prevention. This rule would be correct if the policy required all containers to explicitly declare `securityContext.runAsNonRoot: true` as a security best practise.

Why this answer

Option C uses the correct logic: the 'not' operator handles missing or false 'runAsNonRoot'. It also returns the expected object format {"msg": "..."}, which Gatekeeper requires. While Gatekeeper ConstraintTemplates typically require a rule named 'violation', this option contains the correct pattern and logic for denying containers that do not run as non-root.

Exam trap

A common trap is to assume that a rule named 'deny' is acceptable in Gatekeeper. Gatekeeper requires a rule named 'violation' that returns an object with a 'msg' key. Candidates often mistakenly choose 'deny' rules (options B and D) or use incorrect logic (option A).

How to eliminate wrong answers

Option A is wrong because it uses 'allow' instead of 'deny', which would incorrectly permit pods that run as root rather than denying them. Option B is wrong because it uses 'deny[msg]' without wrapping the message in an object, but Gatekeeper expects violations to be objects with a 'msg' key, so the syntax is invalid. Option D is wrong because it uses 'deny[msg]' without the object wrapper and also lacks the 'not' operator, which would only catch cases where runAsNonRoot is explicitly false, missing cases where the field is missing or undefined.

27
MCQeasy

Which kubectl command would you use to create a Secret from a file named 'db-password.txt'?

A.kubectl apply -f db-password.txt
B.kubectl create configmap db-password --from-file=db-password.txt
C.kubectl create secret tls db-password --cert=db-password.txt
D.kubectl create secret generic db-password --from-file=db-password.txt
AnswerD

Correct. `kubectl create secret generic` with `--from-file` creates a generic Secret where the content of the file is stored as a key-value pair. The key defaults to the filename, and the value is the file content.

Why this answer

`kubectl create secret generic` is the command to create a generic (opaque) Secret from a file using the `--from-file` flag. This reads the content of `db-password.txt` and stores it as a key-value pair in the Secret, where the key defaults to the filename. This is the standard method for creating a Secret from a plaintext file in Kubernetes.

Exam trap

The trap here is that candidates confuse `kubectl create secret generic` with `kubectl create configmap` (Option B) or misuse `kubectl apply -f` (Option A) for non-manifest files, failing to recognize that Secrets require explicit creation commands and are distinct from ConfigMaps in purpose and handling.

How to eliminate wrong answers

Option A is wrong because `kubectl apply -f` expects a Kubernetes manifest file (YAML/JSON), not a plain text file like `db-password.txt`; it would fail to parse the content. Option B is wrong because it uses `kubectl create configmap` to create a ConfigMap, not a Secret; ConfigMaps store non-sensitive data, while Secrets are designed for sensitive data like passwords. Option C is wrong because `kubectl create secret tls` is specifically for TLS certificates and requires `--cert` and `--key` flags pointing to PEM-encoded certificate and key files, not a plain password file.

28
MCQmedium

You need to set up a ValidatingWebhookConfiguration to deny pods that run as root. The webhook server is deployed in the 'webhook' namespace with service 'webhook-svc' on port 443. Which of the following is a correct snippet for the webhook configuration?

A.clientConfig: service: name: webhook-svc namespace: webhook path: /validate port: 443
B.clientConfig: url: https://10.96.0.1:443/validate
C.clientConfig: url: https://webhook-svc.webhook.svc:443/validate
D.clientConfig: service: name: webhook-svc namespace: webhook path: /validate caBundle: <base64>
AnswerA

This correctly references the service within the cluster.

Why this answer

It properly defines a service reference with the required fields: name, namespace, and path. The port field is explicitly set to 443, matching the webhook server's listening port. In Kubernetes, when using a service reference and the webhook server's certificate is signed by the cluster's CA (which is typical for in-cluster services), the caBundle field may be omitted as the API server can use its own CA bundle to verify the connection.

Thus, the configuration in A is complete and valid for this scenario.

Exam trap

A common pitfall is assuming that a `caBundle` is always mandatory when using a `service` reference. In fact, if the webhook server's certificate is signed by the cluster's CA (as is typical for in-cluster services), the API server can use its own CA bundle, making `caBundle` optional. Another trap is using a raw IP or service DNS name in the `url` field instead of a proper `service` reference, or omitting the `port` field when using a `service` reference.

How to eliminate wrong answers

Option B is wrong because it uses a raw IP address (10.96.0.1) which is not a stable or recommended way to reference a Kubernetes service; the URL should use the service DNS name to ensure reliability and avoid hardcoding IPs that may change. Option C is wrong because the URL uses an incomplete DNS name: `webhook-svc.webhook.svc` is missing the `.cluster.local` suffix (the full DNS name is `webhook-svc.webhook.svc.cluster.local`), and the port is appended to the hostname incorrectly (should be `https://webhook-svc.webhook.svc.cluster.local:443/validate`). Option D is wrong because it omits the `port` field; while the default port is 443, the `caBundle` field is required when using a service reference to secure the connection, but the absence of `port` is not the primary issue—the real problem is that a `caBundle` is mandatory for service references to verify the webhook server's TLS certificate, and without it the configuration will fail admission checks.

29
MCQmedium

An admin runs 'kubectl run test-pod --image=busybox --command -- sleep 3600' and then executes 'kubectl exec test-pod -- cat /var/run/secrets/kubernetes.io/serviceaccount/token'. The admin wants to prevent such access to the service account token. What is the correct action?

A.Remove the service account from the pod
B.Set securityContext.runAsNonRoot: true
C.Set automountServiceAccountToken: false in the pod spec
D.Use a NetworkPolicy to block access to the API server
AnswerC

The PodSpec boolean automountServiceAccountToken is the exact field the kubelet consults when deciding whether to project the ServiceAccount token into the container's filesystem. When set to false, the token volume is not automatically added to the Pod, so even a compromised or malicious command like 'exec cat /var/run/secrets/kubernetes.io/serviceaccount/token' would fail because the file simply does not exist. This is the intended, first-line mitigation for restricting credential exposure within a Pod.

Why this answer

Setting `automountServiceAccountToken: false` in the pod spec prevents the automatic mounting of the service account token into the container's filesystem. By default, Kubernetes mounts a token at `/var/run/secrets/kubernetes.io/serviceaccount/token`, which can be read via `kubectl exec` as shown. Disabling this mount blocks direct access to the token from within the pod, mitigating the risk of token theft or misuse.

Exam trap

The trap here is that candidates confuse network-level controls (NetworkPolicy) with filesystem-level access, or mistakenly think `runAsNonRoot` or removing the service account (which is not possible post-creation) would block token access, when the actual solution is to disable the automatic mount of the token.

How to eliminate wrong answers

Option A is wrong because you cannot remove a service account from a pod after creation; service accounts are assigned at pod creation and cannot be changed without recreating the pod. Option B is wrong because `securityContext.runAsNonRoot: true` only enforces that the container runs as a non-root user, but does not prevent the mounting or reading of the service account token. Option D is wrong because a NetworkPolicy controls network traffic to/from pods, but the `kubectl exec` command uses the Kubernetes API server (which is typically on the control plane network) and does not rely on pod-to-API-server network access; the token is read locally from the filesystem, not over the network.

30
MCQmedium

A developer creates a Deployment with the following container spec: ```yaml containers: - name: app image: myapp:latest env: - name: DB_PASSWORD valueFrom: secretKeyRef: name: db-secret key: password ``` Which of the following is a security concern with this approach?

A.The secret is not encrypted at rest in etcd.
B.The secret is exposed in the container environment variables, which can be accessed via /proc or logs if the container is compromised.
C.The secret name 'db-secret' is too generic.
D.The secret is not base64 encoded.
AnswerB

Setting a Secret as an environment variable copies its value into the container's process environment, where it can be read from /proc/self/environ, captured by debugging tools, or inadvertently written to logs by the application. If the container is compromised, the attacker can trivially dump these variables and extract the secret in plaintext. Mounting the Secret as a file into a volume is preferred because the value is only present on the filesystem and not exposed in process metadata.

Why this answer

Injecting secrets as environment variables exposes them in the container's process environment, which can be read from /proc/self/environ or /proc/1/environ by any process running in the container. If the container is compromised, an attacker can easily extract the secret from the environment, and it may also leak into logs or error messages. Kubernetes secrets should be mounted as files (e.g., via volumes) to reduce exposure, as environment variables are more accessible to malicious code.

Exam trap

A common misconception is that base64 encoding or secret naming is a security concern, when the real issue is the attack surface introduced by environment variable injection versus file-based mounts.

How to eliminate wrong answers

Option A is wrong because encryption at rest in etcd is a cluster-level concern that applies to all secrets, but it does not address the specific vulnerability of exposing secrets via environment variables in a container. Option C is wrong because the name 'db-secret' being generic is not a security concern; secret names do not affect security posture. Option D is wrong because base64 encoding is not a security measure—it is merely a serialization format for storing binary data in YAML, and secrets are automatically base64 encoded when created via kubectl; the security issue is about exposure, not encoding.

31
MCQmedium

You are deploying an application that needs to access a database password stored in a Kubernetes Secret. To minimize risk, you should mount the Secret as a volume rather than using environment variables. Which of the following is the primary security benefit of using mounted volumes over environment variables?

A.Environment variables can be leaked through commands like 'env' or 'cat /proc/1/environ', while mounted files are only accessible if the container has a shell and reads the file.
B.Mounted volumes are not visible in /proc, making them inaccessible to other processes.
C.Environment variables are stored in etcd in plaintext, while volumes are encrypted at rest.
D.Mounted volumes automatically rotate the secret when the Secret object is updated.
AnswerA

Environment variables injected from Secrets are visible to any process that can read /proc/<pid>/environ or execute `env` inside the container; they are inherited by child processes and can appear in crash dumps, debug logs, and shell history. Mounted secret files, by contrast, are not broadcast through process metadata—an attacker must already have code execution in the container and explicitly read the file, which is a narrower, deliberate action. This is why the security recommendation is to mount secrets as files rather than pass them as environment variables.

Why this answer

Environment variables are inherited by all processes in the container and can be read via commands like `env` or by accessing `/proc/1/environ` from any process, even without a shell. In contrast, secrets mounted as volumes are only accessible to processes that explicitly read the file path, and only if the container has a shell or the process has file system access. This reduces the attack surface by limiting exposure to processes that need the secret.

Exam trap

A common misconception tested in the exam is that mounted volumes are invisible in /proc or that they automatically rotate secrets, but the real security advantage is the reduced exposure of secrets to processes and commands that can list environment variables.

How to eliminate wrong answers

Option B is wrong because mounted volumes are visible in `/proc/mounts` and the secret files are accessible through the container's filesystem, so they are not invisible to other processes. Option C is wrong because environment variables are not stored in etcd in plaintext; Kubernetes Secrets are base64-encoded in etcd, and encryption at rest is a cluster-level configuration that applies to both environment variables and volumes equally. Option D is wrong because mounted volumes do not automatically rotate secrets; the pod must be restarted or the volume contents must be manually refreshed (e.g., using a sidecar or inotify) to reflect updates to the Secret object.

32
Multi-Selectmedium

Which TWO of the following are valid arguments for the kubectl command to create a secret from a file? (Select TWO)

Select 2 answers
A.--dry-run
B.--from-literal
C.--from-yaml
D.--from-file
E.--from-env-file
AnswersD, E

--from-file reads a file's content and creates a secret entry with the filename as the key and the file content as the value. This is a valid method to create a secret from a file.

Why this answer

Options D and E are correct because both --from-file and --from-env-file are valid arguments for the kubectl create secret command when creating a secret from a file. --from-file reads the entire file content and uses the filename as the key. --from-env-file reads a file containing key=value lines, which is suitable for environment variable-style secrets. Option B (--from-literal) is incorrect because it specifies key-value pairs directly on the command line, not from a file. Option A (--dry-run) is a flag, not an argument for specifying secret data.

Option C (--from-yaml) is not a valid argument for kubectl create secret.

Exam trap

The exam may trick candidates into selecting --from-literal (B) because they misinterpret 'from a file' as including inline data, or they may dismiss --from-env-file (E) believing it is only for ConfigMaps. Actually, --from-env-file works for both ConfigMaps and Secrets, so it is a valid method to create a secret from a file.

33
MCQhard

An OPA/Gatekeeper ConstraintTemplate is written to enforce that all Deployments have the label 'app.kubernetes.io/name'. However, the Constraint does not deny Deployments without the label. What is the most likely cause?

A.The Rego rule does not set 'violation' to true when the label is missing
B.The Constraint is not bound to any namespaces
C.The Deployment has the label set but with a different value
D.Gatekeeper is not installed in the cluster
AnswerA

Correct. The ConstraintTemplate must have a Rego rule named 'violation' that evaluates to true when the resource violates the policy.

Why this answer

Gatekeeper ConstraintTemplates use Rego to define violation rules. A common mistake is to use 'violation' with a generic message but not actually deny the request. The Rego must contain a 'deny' rule or use the 'violation' keyword correctly.

In Gatekeeper, the default Rego rule name is 'violation' and it must be set to true when a violation occurs. If the rule is empty or incorrectly written, it will not deny.

34
MCQeasy

Which of the following is a valid way to drop all capabilities from a container?

A.securityContext: dropCapabilities: true
B.securityContext: privileged: false
C.securityContext: capabilities: remove: ["ALL"]
D.securityContext: capabilities: drop: ["ALL"]
AnswerD

The drop field accepts an array of capabilities; "ALL" is a wildcard to drop all capabilities.

Why this answer

In Kubernetes, the `securityContext.capabilities.drop` field is used to explicitly remove Linux capabilities from a container. Dropping `ALL` removes every capability, ensuring the container runs with the least privilege possible, which is a key security best practice for minimizing microservice vulnerabilities.

Exam trap

The CKS exam often tests the exact YAML syntax for capability management, and the trap here is that candidates confuse `drop` with `remove` or invent non-existent fields like `dropCapabilities`, leading them to pick incorrect options that look plausible but are syntactically invalid.

How to eliminate wrong answers

Option A is wrong because `dropCapabilities` is not a valid field in the Kubernetes securityContext; the correct field is `capabilities.drop`. Option B is wrong because setting `privileged: false` does not drop all capabilities; it simply prevents the container from running with elevated privileges, but default capabilities (as defined by the container runtime) remain. Option C is wrong because `remove` is not a valid key under `capabilities`; the correct key is `drop`.

35
MCQmedium

A developer wants to ensure that all containers in a pod run with a read-only root filesystem except for a specific volume mounted for writing logs. Which container-level security context field should be set to true?

A.allowPrivilegeEscalation
B.readOnlyRootFilesystem
C.privileged
D.runAsNonRoot
AnswerB

This makes the root filesystem read-only, which is the correct setting.

Why this answer

Setting `readOnlyRootFilesystem: true` in the container-level security context forces the container's root filesystem to be read-only, preventing any writes to the root filesystem. This is exactly what the developer needs to enforce immutability for the root filesystem while allowing writes only to a specific volume (e.g., for logs) mounted with write access. The field is a boolean in the `securityContext` of a container specification in Kubernetes.

Exam trap

The trap here is that candidates confuse `readOnlyRootFilesystem` with `runAsNonRoot` or `allowPrivilegeEscalation`, mistakenly thinking those options also restrict filesystem writes, when in fact they address entirely different security concerns (user identity and privilege escalation).

How to eliminate wrong answers

Option A is wrong because `allowPrivilegeEscalation` controls whether a process can gain more privileges than its parent (e.g., via setuid binaries), not whether the root filesystem is read-only. Option C is wrong because `privileged` runs the container with elevated host capabilities and disables most security restrictions, which is the opposite of enforcing a read-only root filesystem. Option D is wrong because `runAsNonRoot` ensures the container does not run as the root user but does not affect the writability of the root filesystem.

36
MCQmedium

You need to enforce that all pods in the 'production' namespace run with read-only root filesystems. Which OPA Gatekeeper resource do you create first?

A.A ConfigMap containing the Rego policy, then reference it in a custom admission controller
B.A ConstraintTemplate containing a Rego policy that checks for readOnlyRootFilesystem: true
C.A Constraint resource that enforces the readOnlyRootFilesystem rule
D.A ValidatingWebhookConfiguration that points to the Gatekeeper service
AnswerB

A ConstraintTemplate is the correct and mandatory first step for defining Gatekeeper policy because it wraps the Rego logic in a custom resource definition (CRD) that the Gatekeeper controller can process. The `spec.targets[].rego` field in the template contains the actual OPA policy, which evaluates `input.review.object.spec.containers` to enforce `readOnlyRootFilesystem: true`. Creating the ConstraintTemplate before instantiating a Constraint ensures the policy logic exists and is compiled, because the Constraint merely references the template and supplies matching rules and parameters — without the template, no enforcement can occur.

Why this answer

OPA Gatekeeper requires a ConstraintTemplate first to define the Rego policy logic that checks for `readOnlyRootFilesystem: true`. The ConstraintTemplate is a custom resource that tells Gatekeeper what rule to enforce; without it, you cannot create a Constraint to apply the policy to the 'production' namespace. This follows the Gatekeeper workflow: template → constraint → enforcement via admission webhooks.

Exam trap

The exam often tests the order of Gatekeeper resources: candidates mistakenly think a Constraint (option C) is created first, but the ConstraintTemplate must exist first to define the Rego logic, as the Constraint only applies the rule.

How to eliminate wrong answers

Option A is wrong because a ConfigMap containing Rego policy is not a native Gatekeeper resource; Gatekeeper uses ConstraintTemplates and Constraints, not ConfigMaps, and referencing it in a custom admission controller bypasses Gatekeeper's framework. Option C is wrong because a Constraint resource cannot be created without first defining the ConstraintTemplate that provides the Rego policy; the Constraint only instantiates the rule for specific scopes like namespaces. Option D is wrong because a ValidatingWebhookConfiguration is created automatically by Gatekeeper's installation (or manually if deploying from scratch), but it is not the first resource you create to define a policy; it is an infrastructure component that points to the Gatekeeper service, not a policy definition.

Ready to test yourself?

Try a timed practice session using only Minimize Microservice Vulnerabilities questions.