Skip to content

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 Communication

Now 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 resource
comply with our security policy?

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 Assessment

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 Configurations

Manual 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
Validate

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

The admission workflow looks like:

Developer
kubectl / CI/CD
Kubernetes API
Authentication
RBAC Authorization
Admission Review
OPA Gatekeeper
Constraint Evaluation
Allow / Deny
Kubernetes Resource

Gatekeeper policy is commonly built using two important objects:

ConstraintTemplate
Defines Policy Logic
Constraint
Applies the Policy

Think of it this way:

ConstraintTemplate
=
Reusable Rule Definition

while:

Constraint
=
Actual Security Requirement

You might create a template defining:

Resources must contain
specific labels.

Then create a constraint saying:

Every Deployment must contain
an owner label.

The same reusable template could later be used to require:

environment
cost-center
application-owner

depending on policy design.

OPA stands for:

Open Policy Agent

OPA is a general-purpose policy engine.

It evaluates:

Input Data
+
Policy
Decision

Conceptually:

Request
OPA
Policy Evaluation
Allow / Deny / Result

OPA is not limited to Kubernetes.

It can be used in broader authorization and policy scenarios.

Gatekeeper integrates OPA-style policy decisions with Kubernetes admission control.

Conceptually:

Kubernetes Resource
Admission Request
Gatekeeper
OPA Policy Evaluation
Admission Decision

Gatekeeper provides Kubernetes-oriented resources such as:

ConstraintTemplate
Constraint

that allow policy rules to be managed using Kubernetes APIs.

Think:

OPA
=
Policy Engine

and:

Gatekeeper
=
Kubernetes Policy Framework
Using OPA Concepts

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 better

or:

Gatekeeper is always better

Organizations choose based on factors such as:

Existing Skills
Governance Requirements
Policy Complexity
Platform Standards
Operational Model

Part 05 — Understand Admission Control Again

Section titled “Part 05 — Understand Admission Control Again”

A Kubernetes request may follow:

Request
Authentication
Authorization
Admission
Resource Created

RBAC may answer:

Yes, this developer
can create Deployments.

Gatekeeper may still answer:

No, this Deployment
violates security policy.
Developer
Has create Deployment permission
Submits privileged workload
Gatekeeper Policy
Denied

This demonstrates:

Permission
Security Compliance

You need:

Authorized Kubernetes Training Cluster
kubectl
OPA Gatekeeper Installed
Permission to Create:
Namespaces
Workloads
ConstraintTemplates
Constraints

If your training environment restricts cluster-scoped objects, study those sections conceptually or use a lab where Gatekeeper administration is allowed.

ConstraintTemplates and many Gatekeeper governance objects are cluster-scoped.

Do not perform these exercises in production without explicit authorization.

Use only:

Your Own Cluster
Training Cluster
Explicitly Authorized Environment

Admission controls can affect the ability to deploy workloads.

A policy mistake can cause:

Application Deployment Failure
Platform Component Failure
Operational Outage

Therefore always:

Scope Carefully
Test First
Validate Positive Cases
Validate Negative Cases
Plan Rollback

Run:

Terminal window
kubectl config current-context

Then:

Terminal window
kubectl cluster-info

Record:

Cluster:
Context:
Environment:

Before changing cluster policy, verify:

Correct Cluster
Correct Context
Authorized Environment

Part 07 — Verify Gatekeeper Installation

Section titled “Part 07 — Verify Gatekeeper Installation”

A common Gatekeeper installation uses the namespace:

gatekeeper-system

Check:

Terminal window
kubectl get pods -n gatekeeper-system

Then:

Terminal window
kubectl get deployments -n gatekeeper-system

You should see Gatekeeper components running.

Exact component names can vary by installed version and deployment method.

Confirm:

  • Gatekeeper namespace exists
  • Gatekeeper Pods are running
  • Gatekeeper components are healthy

Run:

Terminal window
kubectl api-resources | grep -i gatekeeper

You can also search for:

Terminal window
kubectl api-resources | grep -i constraint

You should identify resources related to Gatekeeper.

One important object is:

ConstraintTemplate

Create:

Terminal window
kubectl create namespace ghc-gatekeeper-lab

Verify:

Terminal window
kubectl get namespace ghc-gatekeeper-lab

Set the working namespace if desired:

Terminal window
kubectl config set-context --current --namespace=ghc-gatekeeper-lab

Create:

baseline-app.yaml

Add:

apiVersion: apps/v1
kind: Deployment
metadata:
name: baseline-app
namespace: ghc-gatekeeper-lab
spec:
replicas: 1
selector:
matchLabels:
app: baseline-app
template:
metadata:
labels:
app: baseline-app
spec:
containers:
- name: web
image: nginx

Apply:

Terminal window
kubectl apply -f baseline-app.yaml

Verify:

Terminal window
kubectl get deployment
kubectl get pods

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 Logic

A template normally defines:

Constraint Kind
Parameters
Rego Logic
ConstraintTemplate:
K8sRequiredLabels
Constraint:
ProductionOwnerLabels
Requirement:
Deployments must have owner label

You will build a reusable label policy.

Create:

required-labels-template.yaml

Add:

apiVersion: templates.gatekeeper.sh/v1
kind: ConstraintTemplate
metadata:
name: k8srequiredlabels
spec:
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:

Terminal window
kubectl apply -f required-labels-template.yaml

You created a new constraint type:

K8sRequiredLabels

Think:

ConstraintTemplate
Creates Reusable Policy Type

The key logic is conceptually:

For each required label
Check resource metadata
If missing
Return violation

Do not worry about becoming a Rego expert immediately.

At this stage focus on:

Input
Condition
Violation
INPUT
POLICY CONDITION
VIOLATION RESULT

Run:

Terminal window
kubectl get constrainttemplates

Then:

Terminal window
kubectl describe constrainttemplate k8srequiredlabels

Inspect YAML if required:

Terminal window
kubectl get constrainttemplate k8srequiredlabels -o yaml

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.yaml

Add:

apiVersion: constraints.gatekeeper.sh/v1beta1
kind: K8sRequiredLabels
metadata:
name: require-owner-label
spec:
match:
kinds:
- apiGroups:
- apps
kinds:
- Deployment
namespaces:
- ghc-gatekeeper-lab
parameters:
labels:
- owner

Apply:

Terminal window
kubectl apply -f require-owner-label.yaml

You now have:

Deployment
In ghc-gatekeeper-lab
Must Have:
owner

Part 16 — Test a Non-Compliant Deployment

Section titled “Part 16 — Test a Non-Compliant Deployment”

Create:

missing-owner.yaml

Add:

apiVersion: apps/v1
kind: Deployment
metadata:
name: missing-owner
namespace: ghc-gatekeeper-lab
spec:
replicas: 1
selector:
matchLabels:
app: missing-owner
template:
metadata:
labels:
app: missing-owner
spec:
containers:
- name: web
image: nginx

Try:

Terminal window
kubectl apply -f missing-owner.yaml

If enforcement is active, Gatekeeper should reject the resource.

Deployment Submitted
Constraint Evaluated
owner Missing
Violation
Denied

Create:

compliant-owner.yaml

Add:

apiVersion: apps/v1
kind: Deployment
metadata:
name: compliant-owner
namespace: ghc-gatekeeper-lab
labels:
owner: platform-team
spec:
replicas: 1
selector:
matchLabels:
app: compliant-owner
template:
metadata:
labels:
app: compliant-owner
spec:
containers:
- name: web
image: nginx

Apply:

Terminal window
kubectl apply -f compliant-owner.yaml

Expected:

Allowed

Always test:

Expected Failure
+
Expected Success

This confirms the policy does not simply:

Block Everything

Modify the Constraint parameters to require:

owner
environment

Conceptually:

parameters:
labels:
- owner
- environment

Now a Deployment must contain both.

Required metadata might include:

owner
application
environment
cost-center
data-classification

These labels can support:

Security
Operations
Cost Management
Incident Response
Compliance

Suppose security discovers:

Critical Vulnerability

in a running workload.

Without ownership metadata:

Security Team
Who Owns This?
Unknown
Response Delayed

With metadata:

Workload
owner=payments-team
Correct Team Identified

Governance 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 containers
must not run privileged.
Application Vulnerability
Container Compromise
Privileged Container
Increased Host-Level Risk

Part 21 — Create Privileged Container Template

Section titled “Part 21 — Create Privileged Container Template”

Create:

disallow-privileged-template.yaml

Add:

apiVersion: templates.gatekeeper.sh/v1
kind: ConstraintTemplate
metadata:
name: k8sdisallowprivileged
spec:
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:

Terminal window
kubectl apply -f disallow-privileged-template.yaml

Part 22 — Create the Privileged Constraint

Section titled “Part 22 — Create the Privileged Constraint”

Create:

disallow-privileged.yaml

Add:

apiVersion: constraints.gatekeeper.sh/v1beta1
kind: K8sDisallowPrivileged
metadata:
name: disallow-privileged
spec:
match:
kinds:
- apiGroups:
- ""
kinds:
- Pod
namespaces:
- ghc-gatekeeper-lab

Apply:

Terminal window
kubectl apply -f disallow-privileged.yaml

Create:

privileged-pod.yaml

Add:

apiVersion: v1
kind: Pod
metadata:
name: privileged-test
namespace: ghc-gatekeeper-lab
spec:
containers:
- name: web
image: nginx
securityContext:
privileged: true

Apply:

Terminal window
kubectl apply -f privileged-pod.yaml

Expected:

Denied

Capture:

Policy:
Resource:
Violation Message:
Expected State:
Observed State:

Create:

nonprivileged-pod.yaml

Add:

apiVersion: v1
kind: Pod
metadata:
name: nonprivileged-test
namespace: ghc-gatekeeper-lab
spec:
containers:
- name: web
image: nginx
securityContext:
privileged: false

Apply:

Terminal window
kubectl apply -f nonprivileged-pod.yaml

Expected:

Allowed

Part 25 — Think About Missing securityContext

Section titled “Part 25 — Think About Missing securityContext”

Now ask an important policy-testing question.

What happens if:

securityContext

is completely absent?

Does your policy:

Allow it?
Deny it?
Ignore it?

Test it.

This teaches a critical policy-engineering principle:

Policy Must Handle
Unexpected Input Shapes

A weak policy may block:

privileged: true

but allow:

Missing Security Configuration

even when your real security requirement says:

privileged must explicitly be false.

There is a difference between:

Block Known Bad

and:

Require Known Good

You can design:

Deny Lists

or:

Allow Requirements

Example deny approach:

If privileged=true
Reject

Example required-state approach:

securityContext.privileged
must equal false

The 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 Containers

A rule that only checks:

spec.containers

may not cover the entire Pod attack surface.

Policy quality depends on:

Complete Threat Model
+
Complete Resource Coverage

Part 29 — Policy 03: Approved Container Registries

Section titled “Part 29 — Policy 03: Approved Container Registries”

Now consider software supply-chain security.

Security requirement:

Production workloads
must use approved image sources.

Without restrictions:

Developer
Arbitrary Public Image
Production Cluster

Potential risks:

Malicious Image
Typosquatting
Compromised Publisher
Uncontrolled Base Image
Unknown Provenance
Trusted Registry
Approved Image
Kubernetes

Imagine your organization uses:

registry.example.internal

This 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.yaml

A 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 → Violation

The important learning point is not memorizing syntax.

It is understanding:

Policy Parameter
+
Container Image
Evaluation

Instead of hardcoding:

registry.example.internal

inside the template, design the template to accept:

Approved Registry

as a parameter.

Then the same template can support:

Development Registry
Production Registry
Security Registry

through different Constraints.

Reusable policy logic enables:

One Template
Many Governance Rules

This is one of Gatekeeper’s strengths.

Conceptually:

parameters:
allowedRegistry: "registry.example.internal/"

Then the policy compares:

Container Image

with the configured parameter.

Test two workloads.

Expected pass:

registry.example.internal/app:v1

Expected fail:

random-registry.example/app:v1

In your actual lab, use image references appropriate for testing without relying on inaccessible private images.

The important part is policy evaluation.

Security teams may also restrict:

latest

because mutable tags can create ambiguity.

Example:

app:latest

today may not refer to the same image tomorrow.

A more controlled deployment may use:

Explicit Version

or immutable image references.

Container images must not use
the latest tag.

This can be implemented as another policy-as-code requirement.

Constraints support matching behavior.

You should understand how to scope policies based on:

API Group
Kind
Namespace
Labels

You may want a policy to affect:

Deployments

but not:

ConfigMaps

Or:

production

but not:

development

Use:

Minimum Necessary Policy Scope

especially during initial testing.

Some environments contain workloads requiring special treatment.

Examples may include:

Platform Components
Security Agents
Networking Components
Monitoring Agents

Do not automatically exclude them forever.

Instead use:

Documented Exception
Specific Scope
Business Justification
Compensating Controls
Review

Avoid:

Exclude Half the Cluster

just because applications initially fail policy.

That creates:

Security Blind Spots
Identify Why Workload Fails
Remediate Where Possible
Create Narrow Exception if Required

Gatekeeper policies can be used in ways that support different governance phases depending on version and configuration.

Conceptually, you should understand:

Deny

versus:

Audit / Observe

style workflows.

Policy Development
Lab Testing
Audit / Observation
Violation Review
Workload Remediation
Enforcement

Suppose you create:

Require Resource Limits

and immediately enforce it cluster-wide.

You might discover that:

30% of production workloads
do not satisfy the policy.

The result could be:

Future Deployments Fail
Operational Impact

An observation phase helps teams understand impact first.

Gatekeeper can evaluate existing resources and report constraint violations depending on configuration.

This is valuable because admission control normally evaluates:

New or Updated Requests

while audit-style functionality helps identify:

Existing Non-Compliant Resources
Policy
Existing Resources
Audit
Violations
Remediation

List Gatekeeper constraints using the relevant custom resource type.

For example:

Terminal window
kubectl get k8srequiredlabels

Then:

Terminal window
kubectl describe k8srequiredlabels require-owner-label

Inspect:

Match Scope
Parameters
Violations

depending on your environment and Gatekeeper version.

Run:

Terminal window
kubectl get constrainttemplates

Then inspect:

Terminal window
kubectl describe constrainttemplate k8srequiredlabels

Ask:

What Policy Does This Define?
What Parameters Exist?
Which Constraint Kind Does It Create?
What Rego Logic Is Evaluated?

At a beginner level, think of Rego as:

Input
Rules
Decision

For Kubernetes Gatekeeper, input includes information about the admission request.

Conceptually:

input.review.object

represents the submitted Kubernetes resource.

For a Deployment:

input.review.object.metadata

represents metadata.

Likewise:

input.review.object.spec

represents its specification.

A Gatekeeper rule typically produces a violation when policy conditions are not satisfied.

Conceptually:

IF
Required Label Missing
THEN
Violation

The violation can include a useful message.

Deployment must contain owner label.
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 define
CPU and memory controls.

Resource controls support:

Scheduling
Availability
Capacity Management
Multi-Tenant Stability

Uncontrolled workloads may contribute to:

Node Pressure
Resource Exhaustion
Application Instability

Your template would inspect:

spec.containers[].resources

and require values such as:

requests.cpu
requests.memory
limits.cpu
limits.memory
Container
Resources Defined?
Yes → Allow
No → Violation

Part 48 — Test Missing Resource Controls

Section titled “Part 48 — Test Missing Resource Controls”

Create:

no-resources.yaml

with 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 workloads
should run as non-root
where supported.

A policy can inspect:

securityContext

and enforce expected values.

This reduces:

Unnecessary Container Privilege

and 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: true

where application design allows it.

This can make it harder for an attacker to:

Modify Application Files
Drop Tools
Persist Changes

inside the container filesystem.

Some applications require writable paths.

The correct architecture may be:

Read-Only Root Filesystem
+
Explicit Writable Volume

rather 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
hostPath

These features can reduce isolation between container workloads and the Kubernetes node.

Pod
Host Resource
Potential Increased Node Impact

Policy 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 Context

Every production policy should have:

Policy Owner
Business Requirement
Security Requirement
Technical Owner
Testing Evidence
Exception Process

Use:

Policy Name:
Purpose:
Security Requirement:
Affected Resources:
Affected Namespaces:
Expected Configuration:
Violation Condition:
Enforcement Mode:
Exception Process:
Owner:

Create a workload that intentionally contains several issues:

Missing Owner Label
Privileged Container
No Resource Limits
Unapproved Image

Submit it in the training environment.

Observe which constraints are triggered.

Real workloads may violate:

Multiple Controls

simultaneously.

The security platform should make remediation understandable.

Multiple constraints may evaluate one resource.

Conceptually:

Deployment
Required Labels Constraint
Privileged Constraint
Registry Constraint
Resource Constraint

The 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?

First identify Gatekeeper Pods:

Terminal window
kubectl get pods -n gatekeeper-system

Then inspect appropriate logs:

Terminal window
kubectl logs -n gatekeeper-system <gatekeeper-pod-name>

Use your environment’s actual component names.

Template Errors
Rego Compilation Errors
Constraint Evaluation Problems
Webhook Issues
Configuration Problems

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 Message

Correct it and verify recovery.

Policy-as-code requires the same engineering discipline as application code:

Write
Validate
Test
Debug
Version

Create a constraint intended for:

Deployment

but accidentally configure:

Pod

as the match kind.

Test a Deployment.

Observe:

Policy Does Not Apply

Then correct it.

A security policy that exists but does not match the intended resources provides:

False Confidence

For every policy, ask:

Which Workloads Are Covered?
Which Workloads Are Not Covered?
Why?
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
Pod

If a policy matches only:

Pod

you must understand how admission behavior affects Pods created by controllers.

Similarly, a metadata requirement applied only to:

Deployment

may not automatically require identical metadata on:

Pod Template

unless 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 Relationships

not only Rego.

RBAC controls:

Who Can Submit the Request?

Gatekeeper controls:

Whether the Requested Configuration
Is Acceptable

Combined:

Identity
RBAC
Request Permitted
Gatekeeper
Configuration Validated

Gatekeeper can help enforce networking governance.

For example:

Production Namespaces
Must Have NetworkPolicy

or policies may restrict dangerous Service configurations according to organizational requirements.

Gatekeeper
Require Network Security Controls
NetworkPolicy
Enforce Workload Communication

Gatekeeper can help enforce workload configuration requirements such as:

No Privileged Containers
No Host Networking
Non-Root
Restricted Capabilities
Read-Only Filesystem

These 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 Patterns

This reduces supply-chain risk.

A compliance requirement may state:

Production containers
must not execute with privileged access.

Translate:

Compliance Requirement
Technical Control
ConstraintTemplate
Constraint
Admission Enforcement
Evidence

Potential evidence includes:

ConstraintTemplate
Constraint
Violation Report
Denied Deployment Test
Compliant Deployment Test
Remediation Record
Control:
Security Requirement:
ConstraintTemplate:
Constraint:
Scope:
Test Resource:
Expected Result:
Observed Result:
Evidence:
Status:

Suppose a namespace contains no policy enforcing workload privilege standards.

Document:

Finding:
Kubernetes Workloads Lack Admission-Based
Privilege Enforcement
Affected Environment:
ghc-gatekeeper-lab
Observation:
Workloads can be submitted without
an admission policy preventing
privileged container configuration.
Threat Scenario:
A privileged application container
could increase the impact of a workload compromise.
Business Impact:
Compromise may affect workloads
or potentially increase node-level risk.
Risk:
High
Recommendation:
Implement tested admission policies
that prevent unauthorized privileged workloads.

Example:

Finding:
Deployment Missing Required Ownership Metadata
Affected Resource:
missing-owner
Namespace:
ghc-gatekeeper-lab
Policy:
require-owner-label
Evidence:
Gatekeeper identified the owner label
as missing.
Impact:
Application ownership cannot be reliably
identified during operations or incident response.
Risk:
Medium
Recommendation:
Add the required owner label and enforce
metadata standards through admission policy.

Use:

Finding:
Constraint:
Affected Resource:
Namespace:
Expected Configuration:
Observed Configuration:
Evidence:
Threat Scenario:
Business Impact:
Risk:
Recommendation:
Remediation:
Validation:

Use:

Violation
Identify Policy Requirement
Understand Application Need
Modify Resource
Resubmit
Validate Security
Validate Application

Do not treat:

Policy Passed

as the only success condition.

Also verify:

Application Still Works

Some workloads may require valid exceptions.

Examples might include specialized:

Networking Components
Storage Drivers
Security Agents

An exception should include:

Requester
Resource
Policy
Justification
Risk
Compensating Controls
Approver
Expiration
Review Date
Exclude kube-system forever
because something broke once.
Specific Workload
Specific Reason
Specific Exception
Time-Bound Review

Treat policies as software.

Requirement
Design
Code
Test
Peer Review
Deploy
Monitor
Improve

Store policy definitions in:

Git

Benefits include:

History
Review
Rollback
Approval
Traceability

A mature environment can evaluate policies before Kubernetes admission.

Conceptually:

Developer
Pull Request
Policy Tests
Manifest Validation
Merge
Deployment
Gatekeeper

This creates:

Shift-Left
+
Admission Enforcement

Gatekeeper is not a complete security solution.

Combine it with:

RBAC
NetworkPolicy
Secrets Management
Image Scanning
Runtime Security
Audit Logging
Incident Response
Secure Source
Secure Build
Trusted Image
Gatekeeper
RBAC
NetworkPolicy
Runtime Detection
Incident Response

Part 80 — Gatekeeper vs Runtime Security

Section titled “Part 80 — Gatekeeper vs Runtime Security”

Gatekeeper asks:

Should this configuration
be deployed?

Runtime security asks:

What is this workload
doing after deployment?

Example:

Gatekeeper
Blocks Privileged Pod

while:

Runtime Security
Detects Unexpected Shell

Both are needed.

A mature organization may measure:

Total Constraints
Violations by Policy
Violations by Namespace
Denied Deployments
Exception Count
Remediation Time
Policy Coverage

They can reveal:

Repeated Security Problems
Teams Needing Support
High-Risk Exceptions
Policy Adoption Progress

Create a policy requirement:

Every Deployment
must contain:
environment

Accepted examples:

development
testing
production

Test:

Missing → Violation
Present → Pass

Design a policy that prohibits:

hostNetwork: true

Threat model:

Pod
Host Network Namespace
Reduced Network Isolation

Document:

Security Requirement
Expected Match
Violation Message
Exception Conditions

Design a policy that prevents:

latest

container image tags.

Test:

app:latest

against:

app:v1.2.3

Create a resource-control policy requiring:

CPU Request
Memory Request
CPU Limit
Memory Limit

Test:

No Resources → Violation
Complete Resources → Pass

Create an enterprise policy rollout plan.

Use:

Stage 01
Define Requirement
Stage 02
Build ConstraintTemplate
Stage 03
Unit / Lab Test
Stage 04
Deploy in Observation Mode
Stage 05
Review Existing Violations
Stage 06
Remediate Workloads
Stage 07
Enforce
Stage 08
Monitor Exceptions

Scenario:

You created a Constraint
but an insecure workload
is 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?

Scenario:

A legitimate platform workload
is 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?

Capture:

Gatekeeper Components
ConstraintTemplates
Constraints
Required Labels Test
Privileged Container Test
Compliant Resource Test
Non-Compliant Resource Test
Violation Evidence
Remediation
Post-Remediation Validation
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:

You should now understand:

SECURITY REQUIREMENT
ConstraintTemplate
REGO POLICY
Constraint
MATCH SCOPE
Kubernetes Admission
ALLOW / DENY

For every policy ask:

WHAT
is the requirement?
WHY
is it required?
WHERE
does it apply?
WHICH
resources are evaluated?
HOW
does the logic detect violation?
WHAT
happens when it fails?
HOW
is an exception managed?
  • Verified Kubernetes cluster
  • Verified Gatekeeper installation
  • Inspected Gatekeeper resources
  • Created training namespace
  • Understood OPA
  • Understood Gatekeeper
  • Understood admission control
  • Understood ConstraintTemplates
  • Understood Constraints
  • Understood basic Rego concepts
  • Created label ConstraintTemplate
  • Created label Constraint
  • Tested missing label
  • Tested compliant label
  • Understood metadata governance
  • Created privileged-container policy
  • Tested privileged workload
  • Tested non-privileged workload
  • Considered missing securityContext behavior
  • Understood policy completeness
  • Understood approved-registry policy
  • Understood image-tag governance
  • Understood parameterized policy design
  • Understood matching and scope
  • Understood exclusions
  • Understood staged enforcement
  • Understood exception management
  • Understood policy evidence
  • Reviewed ConstraintTemplates
  • Reviewed Constraints
  • Checked Gatekeeper logs
  • Investigated policy mismatch
  • Understood false positives
  • Created security finding
  • Mapped policy to business requirement
  • Understood policy lifecycle
  • Understood Git-based policy management
  • Understood compliance mapping

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 Validation

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 Engineer

Gatekeeper becomes especially useful in environments where:

Many Development Teams
+
Shared Kubernetes Platform
+
Central Security Standards

must coexist.

  1. What is Open Policy Agent?
  2. What is OPA Gatekeeper?
  3. How does Gatekeeper integrate with Kubernetes?
  4. What is admission control?
  5. What is a ConstraintTemplate?
  6. What is a Constraint?
  7. What is Rego?
  8. What does input.review.object represent?
  9. How does Gatekeeper differ from RBAC?
  10. Can RBAC allow an action that Gatekeeper later denies?
  11. How is Gatekeeper different from Kyverno?
  12. What does a ConstraintTemplate define?
  13. What does a Constraint configure?
  14. Why are parameters useful in policy design?
  15. What is policy-as-code?
  16. Why should policies be stored in version control?
  17. Why require ownership labels?
  18. Why block privileged containers?
  19. Why should containers run as non-root?
  20. Why restrict host networking?
  21. Why restrict hostPath volumes?
  22. Why use approved registries?
  23. Why might organizations block latest image tags?
  24. Why require CPU and memory resources?
  25. What happens if a policy match is incorrect?
  26. What is a false positive?
  27. Why should you test positive and negative cases?
  28. Why is policy scope important?
  29. Why can broad exclusions be dangerous?
  30. What is a policy exception?
  31. Why should exceptions expire?
  32. How can Gatekeeper support compliance?
  33. How can Gatekeeper support DevSecOps?
  34. How does Gatekeeper complement NetworkPolicy?
  35. How does Gatekeeper complement runtime security?
  36. How do you troubleshoot a Constraint that is not working?
  37. Why are Gatekeeper audit capabilities useful?
  38. How would you introduce a new policy into production?
  39. What evidence would you collect for compliance?
  40. How would you measure policy-program effectiveness?

You should now be able to receive a requirement such as:

Production applications
must include owner metadata
and must not run privileged.

and translate it into:

Security Requirement
ConstraintTemplate
Policy Logic
Constraint
Resource Match
Admission Evaluation
Violation or Approval

Then test:

Missing Owner
Denied

and:

Privileged Container
Denied

while:

Compliant Workload
Allowed

You should also understand the complete layered path:

Developer
Authentication
RBAC
Gatekeeper
NetworkPolicy
Workload Runtime

Each 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?

Remember:

POLICY REQUIREMENT
ConstraintTemplate
REGO LOGIC
Constraint
ADMISSION REQUEST
POLICY DECISION
ALLOW / DENY

The purpose of Gatekeeper is not simply to reject YAML.

The purpose is to turn:

Security Standards
Governance Requirements
Compliance Controls

into:

Automated
Repeatable
Testable
Enforceable
Kubernetes Guardrails

Before this lab:

You understood that
Kubernetes configurations
could 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 Enforcement

to:

Building Kubernetes
Policy-as-Code Guardrails.

➡️ Lab 06 — Runtime Security

In the next lab, you will move beyond deployment-time configuration controls.

You will answer:

What happens after
the 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
Containment

The 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 Behavior

You are now moving from:

Preventive Kubernetes Security

into:

Detective Kubernetes Security.