Lab 05 — OPA Gatekeeper
In the previous Kubernetes labs, you built security layer by layer.
Lab 01 — Kubernetes Fundamentals ↓Understand Resources
Lab 02 — Kubernetes RBAC ↓Control Identity
Lab 03 — Kyverno ↓Enforce Kubernetes-Native Policy
Lab 04 — Network Policies ↓Control CommunicationNow you will work with another major Kubernetes policy-as-code technology:
Open Policy Agent Gatekeeper, commonly called OPA Gatekeeper.
Gatekeeper allows security and platform teams to define rules that Kubernetes resources must satisfy before they are accepted into the cluster.
The core question becomes:
Does this Kubernetes resourcecomply with our security policy?Mission Information
Section titled “Mission Information”Difficulty: Intermediate
Estimated Time: 90–120 minutes
Primary Skills:
OPA Gatekeeper
Admission Control
Policy-as-Code
ConstraintTemplates
Constraints
Rego Concepts
Kubernetes Governance
Workload Validation
Policy Testing
Compliance AssessmentLab Scenario
Section titled “Lab Scenario”Your organization has multiple Kubernetes development teams.
Security reviews have found recurring configuration problems such as:
Missing Ownership Labels
Privileged Containers
Unapproved Container Images
Missing Resource Controls
Non-Compliant Workload ConfigurationsManual reviews are no longer scalable.
The platform security team wants to convert security requirements into reusable admission policies.
You have been asked to build several Gatekeeper policies in an isolated Kubernetes training environment.
Your responsibilities are to:
Define Policy Requirements ↓Create ConstraintTemplates ↓Create Constraints ↓Test Compliant Workloads ↓Test Non-Compliant Workloads ↓Review Violations ↓Remediate ↓ValidateLab Objectives
Section titled “Lab Objectives”By the end of this lab, you should be able to:
- Explain Open Policy Agent
- Explain Gatekeeper
- Understand Kubernetes admission control
- Understand ConstraintTemplates
- Understand Constraints
- Understand basic Rego policy logic
- Build reusable policy templates
- Create policy instances
- Require labels
- Restrict privileged containers
- Restrict image sources
- Test compliant and non-compliant resources
- Understand enforcement actions
- Review policy violations
- Troubleshoot Gatekeeper policy behavior
- Document security findings
- Connect policy-as-code to compliance governance
Lab Architecture
Section titled “Lab Architecture”The admission workflow looks like:
Developer ↓kubectl / CI/CD ↓Kubernetes API ↓Authentication ↓RBAC Authorization ↓Admission Review ↓OPA Gatekeeper ↓Constraint Evaluation ↓Allow / Deny ↓Kubernetes ResourceGatekeeper Mental Model
Section titled “Gatekeeper Mental Model”Gatekeeper policy is commonly built using two important objects:
ConstraintTemplate ↓Defines Policy Logic ↓Constraint ↓Applies the PolicyThink of it this way:
ConstraintTemplate=Reusable Rule Definitionwhile:
Constraint=Actual Security RequirementExample
Section titled “Example”You might create a template defining:
Resources must containspecific labels.Then create a constraint saying:
Every Deployment must containan owner label.The same reusable template could later be used to require:
environment
cost-center
application-ownerdepending on policy design.
Part 01 — Understand OPA
Section titled “Part 01 — Understand OPA”OPA stands for:
Open Policy Agent
OPA is a general-purpose policy engine.
It evaluates:
Input Data +Policy ↓DecisionConceptually:
Request ↓OPA ↓Policy Evaluation ↓Allow / Deny / ResultOPA is not limited to Kubernetes.
It can be used in broader authorization and policy scenarios.
Part 02 — Understand Gatekeeper
Section titled “Part 02 — Understand Gatekeeper”Gatekeeper integrates OPA-style policy decisions with Kubernetes admission control.
Conceptually:
Kubernetes Resource ↓Admission Request ↓Gatekeeper ↓OPA Policy Evaluation ↓Admission DecisionGatekeeper provides Kubernetes-oriented resources such as:
ConstraintTemplate
Constraintthat allow policy rules to be managed using Kubernetes APIs.
Part 03 — Gatekeeper vs OPA
Section titled “Part 03 — Gatekeeper vs OPA”Think:
OPA=Policy Engineand:
Gatekeeper=Kubernetes Policy FrameworkUsing OPA ConceptsPart 04 — Gatekeeper vs Kyverno
Section titled “Part 04 — Gatekeeper vs Kyverno”You have already worked with Kyverno.
Both can provide Kubernetes admission-policy capabilities, but their approaches differ.
| Kyverno | Gatekeeper |
|---|---|
| Kubernetes-native policy syntax | OPA/Rego-based policy logic |
| Policies expressed primarily as Kubernetes YAML | ConstraintTemplates contain policy logic |
| Strong Kubernetes-focused user experience | Highly flexible policy model |
| Validation, mutation, generation and image controls | Strong admission validation and policy governance |
Do not think:
Kyverno is always betteror:
Gatekeeper is always betterOrganizations choose based on factors such as:
Existing Skills
Governance Requirements
Policy Complexity
Platform Standards
Operational ModelPart 05 — Understand Admission Control Again
Section titled “Part 05 — Understand Admission Control Again”A Kubernetes request may follow:
Request ↓Authentication ↓Authorization ↓Admission ↓Resource CreatedRBAC may answer:
Yes, this developercan create Deployments.Gatekeeper may still answer:
No, this Deploymentviolates security policy.Example
Section titled “Example”Developer ↓Has create Deployment permission ↓Submits privileged workload ↓Gatekeeper Policy ↓DeniedThis demonstrates:
Permission ≠Security ComplianceBefore You Start
Section titled “Before You Start”You need:
Authorized Kubernetes Training Cluster
kubectl
OPA Gatekeeper Installed
Permission to Create:NamespacesWorkloadsConstraintTemplatesConstraintsIf your training environment restricts cluster-scoped objects, study those sections conceptually or use a lab where Gatekeeper administration is allowed.
Important
Section titled “Important”ConstraintTemplates and many Gatekeeper governance objects are cluster-scoped.
Do not perform these exercises in production without explicit authorization.
Lab Safety Rules
Section titled “Lab Safety Rules”Use only:
Your Own Cluster
Training Cluster
Explicitly Authorized EnvironmentAdmission controls can affect the ability to deploy workloads.
A policy mistake can cause:
Application Deployment Failure
Platform Component Failure
Operational OutageTherefore always:
Scope Carefully
Test First
Validate Positive Cases
Validate Negative Cases
Plan RollbackPart 06 — Verify Cluster Context
Section titled “Part 06 — Verify Cluster Context”Run:
kubectl config current-contextThen:
kubectl cluster-infoRecord:
Cluster:
Context:
Environment:Important Habit
Section titled “Important Habit”Before changing cluster policy, verify:
Correct Cluster ↓Correct Context ↓Authorized EnvironmentPart 07 — Verify Gatekeeper Installation
Section titled “Part 07 — Verify Gatekeeper Installation”A common Gatekeeper installation uses the namespace:
gatekeeper-systemCheck:
kubectl get pods -n gatekeeper-systemThen:
kubectl get deployments -n gatekeeper-systemYou should see Gatekeeper components running.
Exact component names can vary by installed version and deployment method.
Student Task
Section titled “Student Task”Confirm:
- Gatekeeper namespace exists
- Gatekeeper Pods are running
- Gatekeeper components are healthy
Part 08 — Discover Gatekeeper Resources
Section titled “Part 08 — Discover Gatekeeper Resources”Run:
kubectl api-resources | grep -i gatekeeperYou can also search for:
kubectl api-resources | grep -i constraintYou should identify resources related to Gatekeeper.
One important object is:
ConstraintTemplatePart 09 — Create the Lab Namespace
Section titled “Part 09 — Create the Lab Namespace”Create:
kubectl create namespace ghc-gatekeeper-labVerify:
kubectl get namespace ghc-gatekeeper-labSet the working namespace if desired:
kubectl config set-context --current --namespace=ghc-gatekeeper-labPart 10 — Deploy a Baseline Application
Section titled “Part 10 — Deploy a Baseline Application”Create:
baseline-app.yamlAdd:
apiVersion: apps/v1kind: Deploymentmetadata: name: baseline-app namespace: ghc-gatekeeper-labspec: replicas: 1 selector: matchLabels: app: baseline-app template: metadata: labels: app: baseline-app spec: containers: - name: web image: nginxApply:
kubectl apply -f baseline-app.yamlVerify:
kubectl get deploymentkubectl get podsSecurity Review
Section titled “Security Review”Ask:
Who owns this application?
Which environment is it?
Does it follow workload standards?
Is the image approved?
Does it have security configuration?The application may run successfully while still violating organizational standards.
Part 11 — Understand ConstraintTemplates
Section titled “Part 11 — Understand ConstraintTemplates”A ConstraintTemplate defines reusable policy logic.
Conceptually:
ConstraintTemplate ↓Policy Schema +Evaluation LogicA template normally defines:
Constraint Kind
Parameters
Rego LogicExample Architecture
Section titled “Example Architecture”ConstraintTemplate:K8sRequiredLabels ↓Constraint:ProductionOwnerLabels ↓Requirement:Deployments must have owner labelPart 12 — Policy 01: Required Labels
Section titled “Part 12 — Policy 01: Required Labels”You will build a reusable label policy.
Create:
required-labels-template.yamlAdd:
apiVersion: templates.gatekeeper.sh/v1kind: ConstraintTemplatemetadata: name: k8srequiredlabelsspec: crd: spec: names: kind: K8sRequiredLabels validation: openAPIV3Schema: type: object properties: labels: type: array items: type: string targets: - target: admission.k8s.gatekeeper.sh rego: | package k8srequiredlabels
violation[{"msg": msg}] { required := input.parameters.labels[_] not input.review.object.metadata.labels[required] msg := sprintf("Missing required label: %v", [required]) }Apply:
kubectl apply -f required-labels-template.yamlWhat Did You Create?
Section titled “What Did You Create?”You created a new constraint type:
K8sRequiredLabelsThink:
ConstraintTemplate ↓Creates Reusable Policy TypePart 13 — Understand the Rego Logic
Section titled “Part 13 — Understand the Rego Logic”The key logic is conceptually:
For each required label ↓Check resource metadata ↓If missing ↓Return violationDo not worry about becoming a Rego expert immediately.
At this stage focus on:
Input
Condition
ViolationRego Mental Model
Section titled “Rego Mental Model”INPUT ↓POLICY CONDITION ↓VIOLATION RESULTPart 14 — Verify the ConstraintTemplate
Section titled “Part 14 — Verify the ConstraintTemplate”Run:
kubectl get constrainttemplatesThen:
kubectl describe constrainttemplate k8srequiredlabelsInspect YAML if required:
kubectl get constrainttemplate k8srequiredlabels -o yamlStudent Task
Section titled “Student Task”Identify:
Template Name:
Constraint Kind:
Parameters:
Target:Part 15 — Create the Required Labels Constraint
Section titled “Part 15 — Create the Required Labels Constraint”Now create the actual requirement.
Create:
require-owner-label.yamlAdd:
apiVersion: constraints.gatekeeper.sh/v1beta1kind: K8sRequiredLabelsmetadata: name: require-owner-labelspec: match: kinds: - apiGroups: - apps kinds: - Deployment namespaces: - ghc-gatekeeper-lab parameters: labels: - ownerApply:
kubectl apply -f require-owner-label.yamlPolicy Meaning
Section titled “Policy Meaning”You now have:
Deployment ↓In ghc-gatekeeper-lab ↓Must Have:ownerPart 16 — Test a Non-Compliant Deployment
Section titled “Part 16 — Test a Non-Compliant Deployment”Create:
missing-owner.yamlAdd:
apiVersion: apps/v1kind: Deploymentmetadata: name: missing-owner namespace: ghc-gatekeeper-labspec: replicas: 1 selector: matchLabels: app: missing-owner template: metadata: labels: app: missing-owner spec: containers: - name: web image: nginxTry:
kubectl apply -f missing-owner.yamlIf enforcement is active, Gatekeeper should reject the resource.
Expected Concept
Section titled “Expected Concept”Deployment Submitted ↓Constraint Evaluated ↓owner Missing ↓Violation ↓DeniedPart 17 — Create a Compliant Deployment
Section titled “Part 17 — Create a Compliant Deployment”Create:
compliant-owner.yamlAdd:
apiVersion: apps/v1kind: Deploymentmetadata: name: compliant-owner namespace: ghc-gatekeeper-lab labels: owner: platform-teamspec: replicas: 1 selector: matchLabels: app: compliant-owner template: metadata: labels: app: compliant-owner spec: containers: - name: web image: nginxApply:
kubectl apply -f compliant-owner.yamlExpected:
AllowedPolicy Testing Principle
Section titled “Policy Testing Principle”Always test:
Expected Failure +Expected SuccessThis confirms the policy does not simply:
Block EverythingPart 18 — Add Multiple Required Labels
Section titled “Part 18 — Add Multiple Required Labels”Modify the Constraint parameters to require:
owner
environmentConceptually:
parameters: labels: - owner - environmentNow a Deployment must contain both.
Enterprise Governance Example
Section titled “Enterprise Governance Example”Required metadata might include:
owner
application
environment
cost-center
data-classificationThese labels can support:
Security
Operations
Cost Management
Incident Response
CompliancePart 19 — Why Ownership Labels Matter
Section titled “Part 19 — Why Ownership Labels Matter”Suppose security discovers:
Critical Vulnerabilityin a running workload.
Without ownership metadata:
Security Team ↓Who Owns This? ↓Unknown ↓Response DelayedWith metadata:
Workload ↓owner=payments-team ↓Correct Team IdentifiedGovernance metadata can therefore have real operational security value.
Part 20 — Policy 02: Block Privileged Containers
Section titled “Part 20 — Policy 02: Block Privileged Containers”Now you will build a workload-security policy.
Security requirement:
Application containersmust not run privileged.Threat Scenario
Section titled “Threat Scenario”Application Vulnerability ↓Container Compromise ↓Privileged Container ↓Increased Host-Level RiskPart 21 — Create Privileged Container Template
Section titled “Part 21 — Create Privileged Container Template”Create:
disallow-privileged-template.yamlAdd:
apiVersion: templates.gatekeeper.sh/v1kind: ConstraintTemplatemetadata: name: k8sdisallowprivilegedspec: crd: spec: names: kind: K8sDisallowPrivileged targets: - target: admission.k8s.gatekeeper.sh rego: | package k8sdisallowprivileged
violation[{"msg": msg}] { container := input.review.object.spec.containers[_] container.securityContext.privileged == true msg := sprintf("Privileged container is not allowed: %v", [container.name]) }Apply:
kubectl apply -f disallow-privileged-template.yamlPart 22 — Create the Privileged Constraint
Section titled “Part 22 — Create the Privileged Constraint”Create:
disallow-privileged.yamlAdd:
apiVersion: constraints.gatekeeper.sh/v1beta1kind: K8sDisallowPrivilegedmetadata: name: disallow-privilegedspec: match: kinds: - apiGroups: - "" kinds: - Pod namespaces: - ghc-gatekeeper-labApply:
kubectl apply -f disallow-privileged.yamlPart 23 — Test a Privileged Pod
Section titled “Part 23 — Test a Privileged Pod”Create:
privileged-pod.yamlAdd:
apiVersion: v1kind: Podmetadata: name: privileged-test namespace: ghc-gatekeeper-labspec: containers: - name: web image: nginx securityContext: privileged: trueApply:
kubectl apply -f privileged-pod.yamlExpected:
DeniedStudent Task
Section titled “Student Task”Capture:
Policy:
Resource:
Violation Message:
Expected State:
Observed State:Part 24 — Test a Non-Privileged Pod
Section titled “Part 24 — Test a Non-Privileged Pod”Create:
nonprivileged-pod.yamlAdd:
apiVersion: v1kind: Podmetadata: name: nonprivileged-test namespace: ghc-gatekeeper-labspec: containers: - name: web image: nginx securityContext: privileged: falseApply:
kubectl apply -f nonprivileged-pod.yamlExpected:
AllowedPart 25 — Think About Missing securityContext
Section titled “Part 25 — Think About Missing securityContext”Now ask an important policy-testing question.
What happens if:
securityContextis completely absent?
Does your policy:
Allow it?
Deny it?
Ignore it?Test it.
This teaches a critical policy-engineering principle:
Policy Must HandleUnexpected Input ShapesPart 26 — Policy Completeness
Section titled “Part 26 — Policy Completeness”A weak policy may block:
privileged: truebut allow:
Missing Security Configurationeven when your real security requirement says:
privileged must explicitly be false.There is a difference between:
Block Known Badand:
Require Known GoodPart 27 — Policy Design Strategy
Section titled “Part 27 — Policy Design Strategy”You can design:
Deny Listsor:
Allow RequirementsExample deny approach:
If privileged=trueRejectExample required-state approach:
securityContext.privilegedmust equal falseThe better design depends on the security requirement.
Part 28 — Containers Beyond spec.containers
Section titled “Part 28 — Containers Beyond spec.containers”Production policy design may need to consider:
Containers
Init Containers
Ephemeral ContainersA rule that only checks:
spec.containersmay not cover the entire Pod attack surface.
Important Security Lesson
Section titled “Important Security Lesson”Policy quality depends on:
Complete Threat Model +Complete Resource CoveragePart 29 — Policy 03: Approved Container Registries
Section titled “Part 29 — Policy 03: Approved Container Registries”Now consider software supply-chain security.
Security requirement:
Production workloadsmust use approved image sources.Threat Model
Section titled “Threat Model”Without restrictions:
Developer ↓Arbitrary Public Image ↓Production ClusterPotential risks:
Malicious Image
Typosquatting
Compromised Publisher
Uncontrolled Base Image
Unknown ProvenanceDesired Model
Section titled “Desired Model”Trusted Registry ↓Approved Image ↓KubernetesPart 30 — Registry Policy Concept
Section titled “Part 30 — Registry Policy Concept”Imagine your organization uses:
registry.example.internalThis is only a training example.
You want:
registry.example.internal/*to be accepted.
Other sources should be rejected.
Part 31 — Create an Allowed Registry Template
Section titled “Part 31 — Create an Allowed Registry Template”Create:
allowed-registry-template.yamlA conceptual template may evaluate each container image and compare it with an approved prefix.
Your Rego logic should conceptually perform:
Container Image ↓Starts With Approved Registry? ↓Yes → No Violation
No → ViolationRego Concept
Section titled “Rego Concept”The important learning point is not memorizing syntax.
It is understanding:
Policy Parameter +Container Image ↓EvaluationPart 32 — Parameterized Policy Design
Section titled “Part 32 — Parameterized Policy Design”Instead of hardcoding:
registry.example.internalinside the template, design the template to accept:
Approved Registryas a parameter.
Then the same template can support:
Development Registry
Production Registry
Security Registrythrough different Constraints.
Why Parameterization Matters
Section titled “Why Parameterization Matters”Reusable policy logic enables:
One Template ↓Many Governance RulesThis is one of Gatekeeper’s strengths.
Part 33 — Example Registry Constraint
Section titled “Part 33 — Example Registry Constraint”Conceptually:
parameters: allowedRegistry: "registry.example.internal/"Then the policy compares:
Container Imagewith the configured parameter.
Part 34 — Test Registry Policy
Section titled “Part 34 — Test Registry Policy”Test two workloads.
Expected pass:
registry.example.internal/app:v1Expected fail:
random-registry.example/app:v1In your actual lab, use image references appropriate for testing without relying on inaccessible private images.
The important part is policy evaluation.
Part 35 — Image Tags and Immutability
Section titled “Part 35 — Image Tags and Immutability”Security teams may also restrict:
latestbecause mutable tags can create ambiguity.
Example:
app:latesttoday may not refer to the same image tomorrow.
A more controlled deployment may use:
Explicit Versionor immutable image references.
Policy Requirement Example
Section titled “Policy Requirement Example”Container images must not usethe latest tag.This can be implemented as another policy-as-code requirement.
Part 36 — Constraint Matching
Section titled “Part 36 — Constraint Matching”Constraints support matching behavior.
You should understand how to scope policies based on:
API Group
Kind
Namespace
LabelsExample
Section titled “Example”You may want a policy to affect:
Deploymentsbut not:
ConfigMapsOr:
productionbut not:
developmentSecurity Principle
Section titled “Security Principle”Use:
Minimum Necessary Policy Scopeespecially during initial testing.
Part 37 — Namespace Exclusions
Section titled “Part 37 — Namespace Exclusions”Some environments contain workloads requiring special treatment.
Examples may include:
Platform Components
Security Agents
Networking Components
Monitoring AgentsDo not automatically exclude them forever.
Instead use:
Documented Exception
Specific Scope
Business Justification
Compensating Controls
ReviewPart 38 — Dangerous Exclusion Pattern
Section titled “Part 38 — Dangerous Exclusion Pattern”Avoid:
Exclude Half the Clusterjust because applications initially fail policy.
That creates:
Security Blind SpotsBetter Approach
Section titled “Better Approach”Identify Why Workload Fails ↓Remediate Where Possible ↓Create Narrow Exception if RequiredPart 39 — Enforcement Actions
Section titled “Part 39 — Enforcement Actions”Gatekeeper policies can be used in ways that support different governance phases depending on version and configuration.
Conceptually, you should understand:
Denyversus:
Audit / Observestyle workflows.
Recommended Enterprise Rollout
Section titled “Recommended Enterprise Rollout”Policy Development ↓Lab Testing ↓Audit / Observation ↓Violation Review ↓Workload Remediation ↓EnforcementPart 40 — Why Audit First?
Section titled “Part 40 — Why Audit First?”Suppose you create:
Require Resource Limitsand immediately enforce it cluster-wide.
You might discover that:
30% of production workloadsdo not satisfy the policy.The result could be:
Future Deployments Fail ↓Operational ImpactAn observation phase helps teams understand impact first.
Part 41 — Gatekeeper Audit Capability
Section titled “Part 41 — Gatekeeper Audit Capability”Gatekeeper can evaluate existing resources and report constraint violations depending on configuration.
This is valuable because admission control normally evaluates:
New or Updated Requestswhile audit-style functionality helps identify:
Existing Non-Compliant ResourcesCompliance Model
Section titled “Compliance Model”Policy ↓Existing Resources ↓Audit ↓Violations ↓RemediationPart 42 — Inspect Constraints
Section titled “Part 42 — Inspect Constraints”List Gatekeeper constraints using the relevant custom resource type.
For example:
kubectl get k8srequiredlabelsThen:
kubectl describe k8srequiredlabels require-owner-labelInspect:
Match Scope
Parameters
Violationsdepending on your environment and Gatekeeper version.
Part 43 — Inspect ConstraintTemplates
Section titled “Part 43 — Inspect ConstraintTemplates”Run:
kubectl get constrainttemplatesThen inspect:
kubectl describe constrainttemplate k8srequiredlabelsReview
Section titled “Review”Ask:
What Policy Does This Define?
What Parameters Exist?
Which Constraint Kind Does It Create?
What Rego Logic Is Evaluated?Part 44 — Rego Fundamentals
Section titled “Part 44 — Rego Fundamentals”At a beginner level, think of Rego as:
Input ↓Rules ↓DecisionFor Kubernetes Gatekeeper, input includes information about the admission request.
Conceptually:
input.review.objectrepresents the submitted Kubernetes resource.
Example
Section titled “Example”For a Deployment:
input.review.object.metadatarepresents metadata.
Likewise:
input.review.object.specrepresents its specification.
Part 45 — Rego Violation
Section titled “Part 45 — Rego Violation”A Gatekeeper rule typically produces a violation when policy conditions are not satisfied.
Conceptually:
IFRequired Label Missing
THENViolationThe violation can include a useful message.
Good Policy Message
Section titled “Good Policy Message”Deployment must contain owner label.Poor Policy Message
Section titled “Poor Policy Message”Denied.Developer-friendly feedback improves remediation speed.
Part 46 — Policy 04: Require Resource Configuration
Section titled “Part 46 — Policy 04: Require Resource Configuration”Now design a governance requirement:
Application containers must defineCPU and memory controls.Why This Matters
Section titled “Why This Matters”Resource controls support:
Scheduling
Availability
Capacity Management
Multi-Tenant StabilityUncontrolled workloads may contribute to:
Node Pressure
Resource Exhaustion
Application InstabilityPart 47 — Resource Policy Logic
Section titled “Part 47 — Resource Policy Logic”Your template would inspect:
spec.containers[].resourcesand require values such as:
requests.cpu
requests.memory
limits.cpu
limits.memoryPolicy Flow
Section titled “Policy Flow”Container ↓Resources Defined? ↓Yes → Allow
No → ViolationPart 48 — Test Missing Resource Controls
Section titled “Part 48 — Test Missing Resource Controls”Create:
no-resources.yamlwith a normal application container but no resource requests or limits.
Attempt deployment.
Then remediate with:
resources: requests: cpu: "100m" memory: "64Mi" limits: cpu: "250m" memory: "128Mi"Validate again.
Part 49 — Policy 05: Require Non-Root Execution
Section titled “Part 49 — Policy 05: Require Non-Root Execution”Security requirement:
Application workloadsshould run as non-rootwhere supported.A policy can inspect:
securityContextand enforce expected values.
Security Benefit
Section titled “Security Benefit”This reduces:
Unnecessary Container Privilegeand can limit some post-compromise behaviors.
Part 50 — Policy 06: Read-Only Root Filesystem
Section titled “Part 50 — Policy 06: Read-Only Root Filesystem”Another security standard may require:
readOnlyRootFilesystem: truewhere application design allows it.
Benefit
Section titled “Benefit”This can make it harder for an attacker to:
Modify Application Files
Drop Tools
Persist Changesinside the container filesystem.
Important
Section titled “Important”Some applications require writable paths.
The correct architecture may be:
Read-Only Root Filesystem +Explicit Writable Volumerather than disabling the control entirely.
Part 51 — Policy 07: Restrict Host Access
Section titled “Part 51 — Policy 07: Restrict Host Access”High-risk workload features include:
hostNetwork
hostPID
hostIPC
hostPathThese features can reduce isolation between container workloads and the Kubernetes node.
Security Model
Section titled “Security Model”Pod ↓Host Resource ↓Potential Increased Node ImpactPolicy can be used to prohibit or tightly govern these configurations.
Part 52 — Gatekeeper Policy Library Thinking
Section titled “Part 52 — Gatekeeper Policy Library Thinking”As your organization matures, you may create a policy catalog.
Example:
01 Required Labels
02 Approved Registries
03 No Privileged Containers
04 Non-Root Containers
05 Resource Requirements
06 Read-Only Filesystem
07 Restrict Host Networking
08 Restrict Host Paths
09 Approved Service Types
10 Required Security ContextPart 53 — Policy Ownership
Section titled “Part 53 — Policy Ownership”Every production policy should have:
Policy Owner
Business Requirement
Security Requirement
Technical Owner
Testing Evidence
Exception ProcessPart 54 — Policy Documentation Template
Section titled “Part 54 — Policy Documentation Template”Use:
Policy Name:
Purpose:
Security Requirement:
Affected Resources:
Affected Namespaces:
Expected Configuration:
Violation Condition:
Enforcement Mode:
Exception Process:
Owner:Part 55 — Test Multiple Violations
Section titled “Part 55 — Test Multiple Violations”Create a workload that intentionally contains several issues:
Missing Owner Label
Privileged Container
No Resource Limits
Unapproved ImageSubmit it in the training environment.
Observe which constraints are triggered.
Important Lesson
Section titled “Important Lesson”Real workloads may violate:
Multiple Controlssimultaneously.
The security platform should make remediation understandable.
Part 56 — Constraint Interaction
Section titled “Part 56 — Constraint Interaction”Multiple constraints may evaluate one resource.
Conceptually:
Deployment ↓Required Labels Constraint ↓Privileged Constraint ↓Registry Constraint ↓Resource ConstraintThe application must satisfy all relevant enforced requirements.
Part 57 — Policy Troubleshooting Workflow
Section titled “Part 57 — Policy Troubleshooting Workflow”If a constraint does not behave as expected:
01 Is Gatekeeper Healthy?
02 Does the ConstraintTemplate Exist?
03 Is the Template Ready?
04 Does the Constraint Exist?
05 Does Match Include the Resource?
06 Does the Rego Logic Handle the Resource?
07 Are Parameters Correct?
08 Is Namespace Scope Correct?
09 Is Enforcement Configured as Expected?
10 What Do Gatekeeper Logs Show?Part 58 — Inspect Gatekeeper Logs
Section titled “Part 58 — Inspect Gatekeeper Logs”First identify Gatekeeper Pods:
kubectl get pods -n gatekeeper-systemThen inspect appropriate logs:
kubectl logs -n gatekeeper-system <gatekeeper-pod-name>Use your environment’s actual component names.
Logs May Help Diagnose
Section titled “Logs May Help Diagnose”Template Errors
Rego Compilation Errors
Constraint Evaluation Problems
Webhook Issues
Configuration ProblemsPart 59 — Rego Syntax Error Exercise
Section titled “Part 59 — Rego Syntax Error Exercise”In a controlled lab, introduce a minor syntax error into a copied training ConstraintTemplate.
Attempt to apply or observe its status.
Then investigate:
ConstraintTemplate Status
Gatekeeper Logs
Error MessageCorrect it and verify recovery.
Lesson
Section titled “Lesson”Policy-as-code requires the same engineering discipline as application code:
Write
Validate
Test
Debug
VersionPart 60 — Incorrect Match Exercise
Section titled “Part 60 — Incorrect Match Exercise”Create a constraint intended for:
Deploymentbut accidentally configure:
Podas the match kind.
Test a Deployment.
Observe:
Policy Does Not ApplyThen correct it.
Security Lesson
Section titled “Security Lesson”A security policy that exists but does not match the intended resources provides:
False ConfidencePart 61 — Policy Coverage
Section titled “Part 61 — Policy Coverage”For every policy, ask:
Which Workloads Are Covered?
Which Workloads Are Not Covered?
Why?Coverage Matrix
Section titled “Coverage Matrix”| Policy | Pods | Deployments | Jobs | CronJobs |
|---|---|---|---|---|
| Required Labels | As designed | Yes | As designed | As designed |
| Privileged Containers | Yes | Depends on template | Depends | Depends |
| Registry Policy | Yes | Depends | Depends | Depends |
This helps identify gaps.
Part 62 — Generated Pods and Higher-Level Resources
Section titled “Part 62 — Generated Pods and Higher-Level Resources”Remember:
Deployment ↓ReplicaSet ↓PodIf a policy matches only:
Podyou must understand how admission behavior affects Pods created by controllers.
Similarly, a metadata requirement applied only to:
Deploymentmay not automatically require identical metadata on:
Pod Templateunless designed accordingly.
Part 63 — Policy Design Requires Kubernetes Knowledge
Section titled “Part 63 — Policy Design Requires Kubernetes Knowledge”This is why effective Gatekeeper engineering requires understanding:
Kubernetes Resource Relationshipsnot only Rego.
Part 64 — Gatekeeper and RBAC
Section titled “Part 64 — Gatekeeper and RBAC”RBAC controls:
Who Can Submit the Request?Gatekeeper controls:
Whether the Requested ConfigurationIs AcceptableCombined:
Identity ↓RBAC ↓Request Permitted ↓Gatekeeper ↓Configuration ValidatedPart 65 — Gatekeeper and NetworkPolicy
Section titled “Part 65 — Gatekeeper and NetworkPolicy”Gatekeeper can help enforce networking governance.
For example:
Production NamespacesMust Have NetworkPolicyor policies may restrict dangerous Service configurations according to organizational requirements.
Layered Model
Section titled “Layered Model”Gatekeeper ↓Require Network Security Controls
NetworkPolicy ↓Enforce Workload CommunicationPart 66 — Gatekeeper and Pod Security
Section titled “Part 66 — Gatekeeper and Pod Security”Gatekeeper can help enforce workload configuration requirements such as:
No Privileged Containers
No Host Networking
Non-Root
Restricted Capabilities
Read-Only FilesystemThese controls help implement Kubernetes workload-security baselines.
Part 67 — Gatekeeper and Supply Chain Security
Section titled “Part 67 — Gatekeeper and Supply Chain Security”Policy can restrict:
Container Image Sources
Image Tags
Approved Registries
Required Image PatternsThis reduces supply-chain risk.
Part 68 — Gatekeeper and Compliance
Section titled “Part 68 — Gatekeeper and Compliance”A compliance requirement may state:
Production containersmust not execute with privileged access.Translate:
Compliance Requirement ↓Technical Control ↓ConstraintTemplate ↓Constraint ↓Admission Enforcement ↓EvidencePart 69 — Compliance Evidence
Section titled “Part 69 — Compliance Evidence”Potential evidence includes:
ConstraintTemplate
Constraint
Violation Report
Denied Deployment Test
Compliant Deployment Test
Remediation RecordPart 70 — Policy Evidence Template
Section titled “Part 70 — Policy Evidence Template”Control:
Security Requirement:
ConstraintTemplate:
Constraint:
Scope:
Test Resource:
Expected Result:
Observed Result:
Evidence:
Status:Part 71 — Security Finding Exercise
Section titled “Part 71 — Security Finding Exercise”Suppose a namespace contains no policy enforcing workload privilege standards.
Document:
Finding:Kubernetes Workloads Lack Admission-BasedPrivilege Enforcement
Affected Environment:ghc-gatekeeper-lab
Observation:Workloads can be submitted withoutan admission policy preventingprivileged container configuration.
Threat Scenario:A privileged application containercould increase the impact of a workload compromise.
Business Impact:Compromise may affect workloadsor potentially increase node-level risk.
Risk:High
Recommendation:Implement tested admission policiesthat prevent unauthorized privileged workloads.Part 72 — Policy Violation Finding
Section titled “Part 72 — Policy Violation Finding”Example:
Finding:Deployment Missing Required Ownership Metadata
Affected Resource:missing-owner
Namespace:ghc-gatekeeper-lab
Policy:require-owner-label
Evidence:Gatekeeper identified the owner labelas missing.
Impact:Application ownership cannot be reliablyidentified during operations or incident response.
Risk:Medium
Recommendation:Add the required owner label and enforcemetadata standards through admission policy.Part 73 — Finding Template
Section titled “Part 73 — Finding Template”Use:
Finding:
Constraint:
Affected Resource:
Namespace:
Expected Configuration:
Observed Configuration:
Evidence:
Threat Scenario:
Business Impact:
Risk:
Recommendation:
Remediation:
Validation:Part 74 — Remediation Workflow
Section titled “Part 74 — Remediation Workflow”Use:
Violation ↓Identify Policy Requirement ↓Understand Application Need ↓Modify Resource ↓Resubmit ↓Validate Security ↓Validate ApplicationImportant
Section titled “Important”Do not treat:
Policy Passedas the only success condition.
Also verify:
Application Still WorksPart 75 — Policy Exception Governance
Section titled “Part 75 — Policy Exception Governance”Some workloads may require valid exceptions.
Examples might include specialized:
Networking Components
Storage Drivers
Security AgentsAn exception should include:
Requester
Resource
Policy
Justification
Risk
Compensating Controls
Approver
Expiration
Review DateBad Exception Model
Section titled “Bad Exception Model”Exclude kube-system foreverbecause something broke once.Better Model
Section titled “Better Model”Specific Workload ↓Specific Reason ↓Specific Exception ↓Time-Bound ReviewPart 76 — Policy Lifecycle
Section titled “Part 76 — Policy Lifecycle”Treat policies as software.
Requirement ↓Design ↓Code ↓Test ↓Peer Review ↓Deploy ↓Monitor ↓ImprovePart 77 — Version Control
Section titled “Part 77 — Version Control”Store policy definitions in:
GitBenefits include:
History
Review
Rollback
Approval
TraceabilityPart 78 — CI/CD Policy Testing
Section titled “Part 78 — CI/CD Policy Testing”A mature environment can evaluate policies before Kubernetes admission.
Conceptually:
Developer ↓Pull Request ↓Policy Tests ↓Manifest Validation ↓Merge ↓Deployment ↓GatekeeperThis creates:
Shift-Left +Admission EnforcementPart 79 — Defense in Depth
Section titled “Part 79 — Defense in Depth”Gatekeeper is not a complete security solution.
Combine it with:
RBAC
NetworkPolicy
Secrets Management
Image Scanning
Runtime Security
Audit Logging
Incident ResponseSecurity Stack
Section titled “Security Stack”Secure Source ↓Secure Build ↓Trusted Image ↓Gatekeeper ↓RBAC ↓NetworkPolicy ↓Runtime Detection ↓Incident ResponsePart 80 — Gatekeeper vs Runtime Security
Section titled “Part 80 — Gatekeeper vs Runtime Security”Gatekeeper asks:
Should this configurationbe deployed?Runtime security asks:
What is this workloaddoing after deployment?Example:
Gatekeeper ↓Blocks Privileged Podwhile:
Runtime Security ↓Detects Unexpected ShellBoth are needed.
Part 81 — Policy Metrics
Section titled “Part 81 — Policy Metrics”A mature organization may measure:
Total Constraints
Violations by Policy
Violations by Namespace
Denied Deployments
Exception Count
Remediation Time
Policy CoverageWhy Metrics Matter
Section titled “Why Metrics Matter”They can reveal:
Repeated Security Problems
Teams Needing Support
High-Risk Exceptions
Policy Adoption ProgressPart 82 — Practical Challenge 01
Section titled “Part 82 — Practical Challenge 01”Create a policy requirement:
Every Deploymentmust contain:environmentAccepted examples:
development
testing
productionTest:
Missing → Violation
Present → PassPart 83 — Practical Challenge 02
Section titled “Part 83 — Practical Challenge 02”Design a policy that prohibits:
hostNetwork: trueThreat model:
Pod ↓Host Network Namespace ↓Reduced Network IsolationDocument:
Security Requirement
Expected Match
Violation Message
Exception ConditionsPart 84 — Practical Challenge 03
Section titled “Part 84 — Practical Challenge 03”Design a policy that prevents:
latestcontainer image tags.
Test:
app:latestagainst:
app:v1.2.3Part 85 — Practical Challenge 04
Section titled “Part 85 — Practical Challenge 04”Create a resource-control policy requiring:
CPU Request
Memory Request
CPU Limit
Memory LimitTest:
No Resources → Violation
Complete Resources → PassPart 86 — Practical Challenge 05
Section titled “Part 86 — Practical Challenge 05”Create an enterprise policy rollout plan.
Use:
Stage 01Define Requirement
Stage 02Build ConstraintTemplate
Stage 03Unit / Lab Test
Stage 04Deploy in Observation Mode
Stage 05Review Existing Violations
Stage 06Remediate Workloads
Stage 07Enforce
Stage 08Monitor ExceptionsPart 87 — Troubleshooting Challenge
Section titled “Part 87 — Troubleshooting Challenge”Scenario:
You created a Constraintbut an insecure workloadis still accepted.Investigate:
Does ConstraintTemplate Exist?
Is It Valid?
Does Constraint Exist?
Does Match Include the Namespace?
Does Match Include the Kind?
Does Rego Inspect Correct Path?
Is Gatekeeper Healthy?
Is Another Exclusion Present?Part 88 — False Positive Challenge
Section titled “Part 88 — False Positive Challenge”Scenario:
A legitimate platform workloadis being blocked.Do not immediately disable the policy.
Investigate:
Is Workload Actually Compliant?
Is Policy Too Broad?
Does Platform Need an Exception?
Can Workload Be Hardened?
Can Policy Scope Be Improved?Part 89 — Evidence Collection
Section titled “Part 89 — Evidence Collection”Capture:
Gatekeeper Components
ConstraintTemplates
Constraints
Required Labels Test
Privileged Container Test
Compliant Resource Test
Non-Compliant Resource Test
Violation Evidence
Remediation
Post-Remediation ValidationLab Evidence Template
Section titled “Lab Evidence Template”Lab:OPA Gatekeeper
Date:
Cluster:
Namespace:
ConstraintTemplate 01:
Constraint 01:
Requirement:
Non-Compliant Test:
Result:
Compliant Test:
Result:
ConstraintTemplate 02:
Constraint 02:
Security Finding:
Remediation:
Validation:Part 90 — Final Gatekeeper Architecture
Section titled “Part 90 — Final Gatekeeper Architecture”You should now understand:
SECURITY REQUIREMENT ↓ConstraintTemplate ↓REGO POLICY ↓Constraint ↓MATCH SCOPE ↓Kubernetes Admission ↓ALLOW / DENYGatekeeper Review Framework
Section titled “Gatekeeper Review Framework”For every policy ask:
WHATis the requirement?
WHYis it required?
WHEREdoes it apply?
WHICHresources are evaluated?
HOWdoes the logic detect violation?
WHAThappens when it fails?
HOWis an exception managed?Lab Completion Checklist
Section titled “Lab Completion Checklist”Environment
Section titled “Environment”- Verified Kubernetes cluster
- Verified Gatekeeper installation
- Inspected Gatekeeper resources
- Created training namespace
Gatekeeper Fundamentals
Section titled “Gatekeeper Fundamentals”- Understood OPA
- Understood Gatekeeper
- Understood admission control
- Understood ConstraintTemplates
- Understood Constraints
- Understood basic Rego concepts
Required Labels
Section titled “Required Labels”- Created label ConstraintTemplate
- Created label Constraint
- Tested missing label
- Tested compliant label
- Understood metadata governance
Workload Security
Section titled “Workload Security”- Created privileged-container policy
- Tested privileged workload
- Tested non-privileged workload
- Considered missing securityContext behavior
- Understood policy completeness
Supply Chain
Section titled “Supply Chain”- Understood approved-registry policy
- Understood image-tag governance
- Understood parameterized policy design
Governance
Section titled “Governance”- Understood matching and scope
- Understood exclusions
- Understood staged enforcement
- Understood exception management
- Understood policy evidence
Troubleshooting
Section titled “Troubleshooting”- Reviewed ConstraintTemplates
- Reviewed Constraints
- Checked Gatekeeper logs
- Investigated policy mismatch
- Understood false positives
Enterprise Skills
Section titled “Enterprise Skills”- Created security finding
- Mapped policy to business requirement
- Understood policy lifecycle
- Understood Git-based policy management
- Understood compliance mapping
Skills You Practiced
Section titled “Skills You Practiced”You have now worked with:
Open Policy Agent
OPA Gatekeeper
Admission Control
ConstraintTemplates
Constraints
Rego Concepts
Policy-as-Code
Kubernetes Governance
Workload Security
Supply-Chain Governance
Compliance ValidationCareer Connection
Section titled “Career Connection”These skills are highly valuable for:
Kubernetes Security Engineer
Platform Security Engineer
DevSecOps Engineer
Cloud Security Engineer
Cloud Security Architect
Kubernetes Administrator
Security Consultant
Cloud Governance EngineerGatekeeper becomes especially useful in environments where:
Many Development Teams +Shared Kubernetes Platform +Central Security Standardsmust coexist.
Interview Questions
Section titled “Interview Questions”- What is Open Policy Agent?
- What is OPA Gatekeeper?
- How does Gatekeeper integrate with Kubernetes?
- What is admission control?
- What is a ConstraintTemplate?
- What is a Constraint?
- What is Rego?
- What does
input.review.objectrepresent? - How does Gatekeeper differ from RBAC?
- Can RBAC allow an action that Gatekeeper later denies?
- How is Gatekeeper different from Kyverno?
- What does a ConstraintTemplate define?
- What does a Constraint configure?
- Why are parameters useful in policy design?
- What is policy-as-code?
- Why should policies be stored in version control?
- Why require ownership labels?
- Why block privileged containers?
- Why should containers run as non-root?
- Why restrict host networking?
- Why restrict hostPath volumes?
- Why use approved registries?
- Why might organizations block
latestimage tags? - Why require CPU and memory resources?
- What happens if a policy match is incorrect?
- What is a false positive?
- Why should you test positive and negative cases?
- Why is policy scope important?
- Why can broad exclusions be dangerous?
- What is a policy exception?
- Why should exceptions expire?
- How can Gatekeeper support compliance?
- How can Gatekeeper support DevSecOps?
- How does Gatekeeper complement NetworkPolicy?
- How does Gatekeeper complement runtime security?
- How do you troubleshoot a Constraint that is not working?
- Why are Gatekeeper audit capabilities useful?
- How would you introduce a new policy into production?
- What evidence would you collect for compliance?
- How would you measure policy-program effectiveness?
Practical Readiness Milestone
Section titled “Practical Readiness Milestone”You should now be able to receive a requirement such as:
Production applicationsmust include owner metadataand must not run privileged.and translate it into:
Security Requirement ↓ConstraintTemplate ↓Policy Logic ↓Constraint ↓Resource Match ↓Admission Evaluation ↓Violation or ApprovalThen test:
Missing Owner ↓Deniedand:
Privileged Container ↓Deniedwhile:
Compliant Workload ↓AllowedSecurity Readiness Milestone
Section titled “Security Readiness Milestone”You should also understand the complete layered path:
Developer ↓Authentication ↓RBAC ↓Gatekeeper ↓NetworkPolicy ↓Workload RuntimeEach control answers a different question:
Authentication:Who are you?
RBAC:What are you allowed to do?
Gatekeeper:Is the requested configuration acceptable?
NetworkPolicy:Where can the workload communicate?
Runtime Security:What is the workload actually doing?Final Lab Mental Model
Section titled “Final Lab Mental Model”Remember:
POLICY REQUIREMENT ↓ConstraintTemplate ↓REGO LOGIC ↓Constraint ↓ADMISSION REQUEST ↓POLICY DECISION ↓ALLOW / DENYThe purpose of Gatekeeper is not simply to reject YAML.
The purpose is to turn:
Security Standards
Governance Requirements
Compliance Controlsinto:
Automated
Repeatable
Testable
Enforceable
Kubernetes GuardrailsLab Outcome
Section titled “Lab Outcome”Before this lab:
You understood thatKubernetes configurationscould be governed by policy.After this lab:
You worked with OPA Gatekeeper,
created reusable policy templates,
applied Constraints,
tested violations,
validated compliant workloads,
connected Rego logic with Kubernetes resources,
documented security findings,
and practiced enterprise policy governance.You have moved from:
Understanding Policy Enforcementto:
Building KubernetesPolicy-as-Code Guardrails.What’s Next?
Section titled “What’s Next?”➡️ Lab 06 — Runtime Security
In the next lab, you will move beyond deployment-time configuration controls.
You will answer:
What happens afterthe workload is running?You will work with concepts such as:
Runtime Events
Process Monitoring
Unexpected Shell Activity
Suspicious Commands
Container Behavior
Falco
Security Alerts
Threat Investigation
ContainmentThe progression becomes:
Lab 01 — Kubernetes Fundamentals ↓Understand Resources
Lab 02 — Kubernetes RBAC ↓Control Identity
Lab 03 — Kyverno ↓Enforce Kubernetes-Native Policy
Lab 04 — Network Policies ↓Control Communication
Lab 05 — OPA Gatekeeper ↓Enforce Advanced Governance
Lab 06 — Runtime Security ↓Detect Suspicious BehaviorYou are now moving from:
Preventive Kubernetes Securityinto:
Detective Kubernetes Security.