implementing-opa-gatekeeper-for-policy-enforcement▌
mukul975/Anthropic-Cybersecurity-Skills · updated May 25, 2026
MDX-style export adds YAML metadata + attribution linking explainx.ai and this canonical listing URL.
Enforce Kubernetes admission policies using OPA Gatekeeper with ConstraintTemplates, Rego rules, and the Gatekeeper policy library.
| name | implementing-opa-gatekeeper-for-policy-enforcement |
| description | Enforce Kubernetes admission policies using OPA Gatekeeper with ConstraintTemplates, Rego rules, and the Gatekeeper policy library. |
| domain | cybersecurity |
| subdomain | container-security |
| tags | - opa - gatekeeper - kubernetes - admission-control - policy-as-code - rego |
| version | '1.0' |
| author | mahipal |
| license | Apache-2.0 |
| nist_csf | - PR.PS-01 - PR.IR-01 - ID.AM-08 - DE.CM-01 |
Implementing OPA Gatekeeper for Policy Enforcement
Overview
OPA Gatekeeper is a Kubernetes admission controller that enforces policies written in Rego. It uses ConstraintTemplates (policy blueprints with Rego logic) and Constraints (instantiated policies with parameters) to validate, mutate, or deny Kubernetes resource requests at admission time.
When to Use
- When deploying or configuring implementing opa gatekeeper for policy enforcement capabilities in your environment
- When establishing security controls aligned to compliance requirements
- When building or improving security architecture for this domain
- When conducting security assessments that require this implementation
Prerequisites
- Kubernetes cluster v1.24+
- Helm 3
- kubectl with cluster-admin access
- Familiarity with Rego policy language
Installing Gatekeeper
# Install via Helm
helm repo add gatekeeper https://open-policy-agent.github.io/gatekeeper/charts
helm repo update
helm install gatekeeper gatekeeper/gatekeeper \
--namespace gatekeeper-system --create-namespace \
--set replicas=3 \
--set audit.replicas=1 \
--set audit.logLevel=INFO
# Verify
kubectl get pods -n gatekeeper-system
kubectl get crd | grep gatekeeper
Verify Installation
# Check webhook
kubectl get validatingwebhookconfigurations gatekeeper-validating-webhook-configuration
# Check CRDs
kubectl get crd constrainttemplates.templates.gatekeeper.sh
kubectl get crd configs.config.gatekeeper.sh
ConstraintTemplate Examples
1. Require Labels on Resources
# template-required-labels.yaml
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, "details": {"missing_labels": missing}}] {
provided := {label | input.review.object.metadata.labels[label]}
required := {label | label := input.parameters.labels[_]}
missing := required - provided
count(missing) > 0
msg := sprintf("Missing required labels: %v", [missing])
}
# constraint-require-team-label.yaml
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: K8sRequiredLabels
metadata:
name: require-team-label
spec:
match:
kinds:
- apiGroups: [""]
kinds: ["Namespace"]
- apiGroups: ["apps"]
kinds: ["Deployment"]
parameters:
labels:
- "team"
- "environment"
2. Block Privileged Containers
# template-block-privileged.yaml
apiVersion: templates.gatekeeper.sh/v1
kind: ConstraintTemplate
metadata:
name: k8sblockprivileged
spec:
crd:
spec:
names:
kind: K8sBlockPrivileged
targets:
- target: admission.k8s.gatekeeper.sh
rego: |
package k8sblockprivileged
violation[{"msg": msg}] {
container := input.review.object.spec.containers[_]
container.securityContext.privileged == true
msg := sprintf("Privileged container not allowed: %v", [container.name])
}
violation[{"msg": msg}] {
container := input.review.object.spec.initContainers[_]
container.securityContext.privileged == true
msg := sprintf("Privileged init container not allowed: %v", [container.name])
}
# constraint-block-privileged.yaml
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: K8sBlockPrivileged
metadata:
name: block-privileged-containers
spec:
match:
kinds:
- apiGroups: [""]
kinds: ["Pod"]
namespaces:
- "production"
- "staging"
3. Restrict Container Image Registries
# template-allowed-repos.yaml
apiVersion: templates.gatekeeper.sh/v1
kind: ConstraintTemplate
metadata:
name: k8sallowedrepos
spec:
crd:
spec:
names:
kind: K8sAllowedRepos
validation:
openAPIV3Schema:
type: object
properties:
repos:
type: array
items:
type: string
targets:
- target: admission.k8s.gatekeeper.sh
rego: |
package k8sallowedrepos
violation[{"msg": msg}] {
container := input.review.object.spec.containers[_]
not image_matches(container.image)
msg := sprintf("Container image %v is not from an allowed registry. Allowed: %v", [container.image, input.parameters.repos])
}
violation[{"msg": msg}] {
container := input.review.object.spec.initContainers[_]
not image_matches(container.image)
msg := sprintf("Init container image %v is not from an allowed registry. Allowed: %v", [container.image, input.parameters.repos])
}
image_matches(image) {
repo := input.parameters.repos[_]
startswith(image, repo)
}
# constraint-allowed-repos.yaml
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: K8sAllowedRepos
metadata:
name: restrict-image-repos
spec:
match:
kinds:
- apiGroups: [""]
kinds: ["Pod"]
parameters:
repos:
- "gcr.io/my-project/"
- "ghcr.io/my-org/"
- "registry.k8s.io/"
4. Enforce Resource Limits
# template-require-limits.yaml
apiVersion: templates.gatekeeper.sh/v1
kind: ConstraintTemplate
metadata:
name: k8srequirelimits
spec:
crd:
spec:
names:
kind: K8sRequireLimits
targets:
- target: admission.k8s.gatekeeper.sh
rego: |
package k8srequirelimits
violation[{"msg": msg}] {
container := input.review.object.spec.containers[_]
not container.resources.limits.cpu
msg := sprintf("Container %v has no CPU limit", [container.name])
}
violation[{"msg": msg}] {
container := input.review.object.spec.containers[_]
not container.resources.limits.memory
msg := sprintf("Container %v has no memory limit", [container.name])
}
5. Block Latest Image Tag
# template-block-latest-tag.yaml
apiVersion: templates.gatekeeper.sh/v1
kind: ConstraintTemplate
metadata:
name: k8sblocklatesttag
spec:
crd:
spec:
names:
kind: K8sBlockLatestTag
targets:
- target: admission.k8s.gatekeeper.sh
rego: |
package k8sblocklatesttag
violation[{"msg": msg}] {
container := input.review.object.spec.containers[_]
endswith(container.image, ":latest")
msg := sprintf("Container %v uses ':latest' tag. Use specific version tags.", [container.name])
}
violation[{"msg": msg}] {
container := input.review.object.spec.containers[_]
not contains(container.image, ":")
msg := sprintf("Container %v has no tag (defaults to latest). Use specific version tags.", [container.name])
}
6. Enforce Read-Only Root Filesystem
apiVersion: templates.gatekeeper.sh/v1
kind: ConstraintTemplate
metadata:
name: k8sreadonlyroot
spec:
crd:
spec:
names:
kind: K8sReadOnlyRoot
targets:
- target: admission.k8s.gatekeeper.sh
rego: |
package k8sreadonlyroot
violation[{"msg": msg}] {
container := input.review.object.spec.containers[_]
not container.securityContext.readOnlyRootFilesystem
msg := sprintf("Container %v must have readOnlyRootFilesystem set to true", [container.name])
}
Audit and Enforcement Modes
# Dry-run mode (audit only, don't block)
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: K8sBlockPrivileged
metadata:
name: block-privileged-dryrun
spec:
enforcementAction: dryrun # dryrun | deny | warn
match:
kinds:
- apiGroups: [""]
kinds: ["Pod"]
Check Audit Violations
# List all constraint violations
kubectl get k8sblockprivileged block-privileged-containers -o yaml | grep -A 20 violations
# Check all constraints audit status
kubectl get constraints -o json | jq '.items[] | {name: .metadata.name, violations: (.status.violations // [] | length)}'
Gatekeeper Config (Exempt Namespaces)
apiVersion: config.gatekeeper.sh/v1alpha1
kind: Config
metadata:
name: config
namespace: gatekeeper-system
spec:
match:
- excludedNamespaces:
- kube-system
- gatekeeper-system
- calico-system
processes:
- "*"
Monitoring
# Check Gatekeeper metrics
kubectl port-forward -n gatekeeper-system svc/gatekeeper-webhook-service 8443:443
# Prometheus metrics
kubectl get --raw /metrics | grep gatekeeper
Best Practices
- Start with dryrun - Deploy constraints in
dryrunmode first, review violations, then switch todeny - Use the policy library - Leverage https://github.com/open-policy-agent/gatekeeper-library for pre-built templates
- Exempt system namespaces - Always exclude kube-system and gatekeeper-system
- Version control policies - Store ConstraintTemplates and Constraints in Git
- Monitor audit results - Check constraint
.status.violationsregularly - Test Rego policies - Use
opa testor Rego Playground before deploying - Combine with admission webhooks - Layer Gatekeeper with Pod Security Admission for defense in depth
How to use implementing-opa-gatekeeper-for-policy-enforcement on Cursor
AI-first code editor with Composer
Prerequisites
Before installing skills in Cursor, ensure your development environment meets these requirements:
- ›Cursor installed and configured on your development machine
- ›Node.js version 16.0+ with npm package manager (verify with
node --version) - ›Active project directory or workspace where you want to add implementing-opa-gatekeeper-for-policy-enforcement
Execute installation command
Execute the skills CLI command in your project's root directory to begin installation:
The skills CLI fetches implementing-opa-gatekeeper-for-policy-enforcement from GitHub repository mukul975/Anthropic-Cybersecurity-Skills and configures it for Cursor.
Select Cursor when prompted
The CLI will show a list of available agents. Use arrow keys to navigate and space to select Cursor:
Verify installation
Confirm successful installation by checking the skill directory location:
Reload or restart Cursor to activate implementing-opa-gatekeeper-for-policy-enforcement. Access the skill through slash commands (e.g., /implementing-opa-gatekeeper-for-policy-enforcement) or your agent's skill management interface.
Security & Verification Notice
We perform automated surface-level scans (Gen AI Scanner, Socket, Snyk) during installation. These checks detect common vulnerabilities but do not guarantee complete security. Always review skill source code and verify the publisher's reputation before production use.
Skills execute code in your development environment. Always verify the publisher's identity, review recent commits, and test in isolated environments before production deployment.
List & Monetize Your Skill
Submit your Claude Code skill and start earning
Use Cases▌
Task Automation & Efficiency
Automate repetitive workflows and reduce manual effort
Example
Generate reports, summarize documents, draft communications
Save 3-5 hours per week on routine tasks
Knowledge Enhancement
Learn new skills, understand complex topics, get expert guidance
Example
Explain concepts, provide examples, suggest learning resources
Accelerate learning and skill development by 2x
Quality Improvement
Enhance output quality through reviews, suggestions, and refinements
Example
Review drafts, suggest improvements, catch errors
Improve work quality by 30-40% with less effort
Implementation Guide▌
Prerequisites
- ›Claude Desktop or compatible AI client with skill support
- ›Clear understanding of task or problem to solve
- ›Willingness to iterate and refine outputs
Time Estimate
15-45 minutes depending on use case complexity
Installation Steps
- 1.Install skill using provided installation command
- 2.Test with simple use case relevant to your work
- 3.Evaluate output quality and relevance
- 4.Iterate on prompts to improve results
- 5.Integrate into regular workflow if valuable
Common Pitfalls
- ⚠Expecting perfect results without iteration
- ⚠Not providing enough context in prompts
- ⚠Using skill for tasks outside its intended scope
- ⚠Accepting outputs without review and validation
Best Practices▌
✓ Do
- +Start with clear, specific prompts
- +Provide relevant context and constraints
- +Review and refine all outputs before using
- +Iterate to improve output quality
- +Document successful prompt patterns
✗ Don't
- −Don't use without understanding skill limitations
- −Don't skip validation of outputs
- −Don't share sensitive information in prompts
- −Don't expect skill to replace human judgment
💡 Pro Tips
- ★Be specific about desired format and style
- ★Ask for multiple options to choose from
- ★Request explanations to understand reasoning
- ★Combine AI efficiency with human expertise
When to Use This▌
✓ Use When
Use when skill capabilities match your task, clear ROI on time saved, and you can validate outputs. Best for repetitive tasks, learning, and quality improvement.
✗ Avoid When
Avoid when task requires deep expertise you can't validate, involves sensitive decisions, or when learning process is more valuable than speed of completion.
Learning Path▌
- 1Familiarize yourself with skill capabilities and limitations
- 2Start with low-risk, non-critical tasks
- 3Progress to more complex and valuable use cases
- 4Build expertise through regular use and experimentation
Discussion
Product Hunt–style comments (not star reviews)- No comments yet — start the thread.
Ratings
4.6★★★★★59 reviews- ★★★★★Ishan Farah· Dec 28, 2024
I recommend implementing-opa-gatekeeper-for-policy-enforcement for anyone iterating fast on agent tooling; clear intent and a small, reviewable surface area.
- ★★★★★Anika Farah· Dec 28, 2024
implementing-opa-gatekeeper-for-policy-enforcement fits our agent workflows well — practical, well scoped, and easy to wire into existing repos.
- ★★★★★Sofia Wang· Dec 8, 2024
implementing-opa-gatekeeper-for-policy-enforcement fits our agent workflows well — practical, well scoped, and easy to wire into existing repos.
- ★★★★★Maya Iyer· Dec 4, 2024
Registry listing for implementing-opa-gatekeeper-for-policy-enforcement matched our evaluation — installs cleanly and behaves as described in the markdown.
- ★★★★★Min Garcia· Nov 27, 2024
We added implementing-opa-gatekeeper-for-policy-enforcement from the explainx registry; install was straightforward and the SKILL.md answered most questions upfront.
- ★★★★★Maya Robinson· Nov 23, 2024
Solid pick for teams standardizing on skills: implementing-opa-gatekeeper-for-policy-enforcement is focused, and the summary matches what you get after install.
- ★★★★★Alexander Bansal· Nov 19, 2024
Useful defaults in implementing-opa-gatekeeper-for-policy-enforcement — fewer surprises than typical one-off scripts, and it plays nicely with `npx skills` flows.
- ★★★★★Maya Gupta· Nov 19, 2024
We added implementing-opa-gatekeeper-for-policy-enforcement from the explainx registry; install was straightforward and the SKILL.md answered most questions upfront.
- ★★★★★Jin Kim· Oct 18, 2024
Solid pick for teams standardizing on skills: implementing-opa-gatekeeper-for-policy-enforcement is focused, and the summary matches what you get after install.
- ★★★★★Maya Verma· Oct 14, 2024
We added implementing-opa-gatekeeper-for-policy-enforcement from the explainx registry; install was straightforward and the SKILL.md answered most questions upfront.
showing 1-10 of 59