implementing-policy-as-code-with-open-policy-agent▌
mukul975/Anthropic-Cybersecurity-Skills · updated May 25, 2026
MDX-style export adds YAML metadata + attribution linking explainx.ai and this canonical listing URL.
This skill covers implementing Open Policy Agent (OPA) and Gatekeeper for policy-as-code enforcement in Kubernetes and CI/CD pipelines. It addresses writing Rego policies, deploying OPA Gatekeeper as a Kubernetes admission controller, testing policies in development, and integrating policy evaluation into deployment pipelines.
| name | implementing-policy-as-code-with-open-policy-agent |
| description | 'This skill covers implementing Open Policy Agent (OPA) and Gatekeeper for policy-as-code enforcement in Kubernetes and CI/CD pipelines. It addresses writing Rego policies, deploying OPA Gatekeeper as a Kubernetes admission controller, testing policies in development, and integrating policy evaluation into deployment pipelines. ' |
| domain | cybersecurity |
| subdomain | devsecops |
| tags | - devsecops - cicd - opa - gatekeeper - policy-as-code - kubernetes - secure-sdlc |
| version | 1.0.0 |
| author | mahipal |
| license | Apache-2.0 |
| nist_ai_rmf | - GOVERN-1.1 - MEASURE-2.7 - MANAGE-3.1 |
| nist_csf | - PR.PS-01 - GV.SC-07 - ID.IM-04 - PR.PS-04 |
Implementing Policy as Code with Open Policy Agent
When to Use
- When enforcing organizational security policies across Kubernetes clusters programmatically
- When requiring admission control that blocks non-compliant resources from being created
- When implementing policy governance that can be version-controlled, tested, and audited
- When standardizing security rules across multiple clusters and environments
- When needing a flexible policy engine that extends beyond Kubernetes to APIs and CI/CD
Do not use for vulnerability scanning (use Trivy/Checkov), for runtime threat detection (use Falco), or for network policy enforcement (use Kubernetes NetworkPolicy or Calico).
Prerequisites
- Kubernetes cluster with admin access for Gatekeeper installation
- Helm for Gatekeeper deployment
- OPA CLI or conftest for local policy testing
- Rego knowledge for policy authoring
Workflow
Step 1: Install OPA Gatekeeper
# Install Gatekeeper via Helm
helm repo add gatekeeper https://open-policy-agent.github.io/gatekeeper/charts
helm install gatekeeper gatekeeper/gatekeeper \
--namespace gatekeeper-system --create-namespace \
--set replicas=3 \
--set audit.replicas=1 \
--set audit.writeToRAMDisk=true
Step 2: Create Constraint Templates
# templates/k8s-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}] {
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])
}
---
# templates/k8s-container-limits.yaml
apiVersion: templates.gatekeeper.sh/v1
kind: ConstraintTemplate
metadata:
name: k8scontainerlimits
spec:
crd:
spec:
names:
kind: K8sContainerLimits
validation:
openAPIV3Schema:
type: object
properties:
cpu:
type: string
memory:
type: string
targets:
- target: admission.k8s.gatekeeper.sh
rego: |
package k8scontainerlimits
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])
}
---
# templates/k8s-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])
}
Step 3: Apply Constraints
# constraints/require-labels.yaml
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: K8sRequiredLabels
metadata:
name: require-team-labels
spec:
enforcementAction: deny
match:
kinds:
- apiGroups: [""]
kinds: ["Namespace"]
- apiGroups: ["apps"]
kinds: ["Deployment", "StatefulSet"]
excludedNamespaces:
- kube-system
- gatekeeper-system
parameters:
labels:
- "team"
- "environment"
- "cost-center"
---
# constraints/block-privileged.yaml
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: K8sBlockPrivileged
metadata:
name: block-privileged-containers
spec:
enforcementAction: deny
match:
kinds:
- apiGroups: [""]
kinds: ["Pod"]
- apiGroups: ["apps"]
kinds: ["Deployment", "DaemonSet", "StatefulSet"]
excludedNamespaces:
- kube-system
Step 4: Test Policies with conftest
# Install conftest
brew install conftest
# Test Kubernetes manifests against OPA policies locally
conftest test deployment.yaml --policy policies/ --output json
# Test Terraform against OPA policies
conftest test terraform/main.tf --policy policies/terraform/ --parser hcl2
# Test Dockerfiles
conftest test Dockerfile --policy policies/docker/
# policies/kubernetes/deny_latest_tag.rego
package kubernetes
deny[msg] {
input.kind == "Deployment"
container := input.spec.template.spec.containers[_]
endswith(container.image, ":latest")
msg := sprintf("Container %v uses :latest tag. Pin to specific version.", [container.name])
}
deny[msg] {
input.kind == "Deployment"
container := input.spec.template.spec.containers[_]
not contains(container.image, ":")
msg := sprintf("Container %v has no tag. Pin to specific version.", [container.name])
}
Step 5: Integrate Policy Testing in CI/CD
# .github/workflows/policy-test.yml
name: Policy Validation
on:
pull_request:
paths: ['k8s/**', 'terraform/**', 'policies/**']
jobs:
conftest:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Install conftest
run: |
wget -q https://github.com/open-policy-agent/conftest/releases/download/v0.50.0/conftest_0.50.0_Linux_x86_64.tar.gz
tar xzf conftest_0.50.0_Linux_x86_64.tar.gz
sudo mv conftest /usr/local/bin/
- name: Test K8s manifests
run: conftest test k8s/**/*.yaml --policy policies/kubernetes/ --output json
- name: Test Terraform
run: conftest test terraform/*.tf --policy policies/terraform/ --parser hcl2
Key Concepts
| Term | Definition |
|---|---|
| OPA | Open Policy Agent — general-purpose policy engine using Rego language for policy decisions |
| Rego | OPA's declarative query language for writing policy rules |
| Gatekeeper | Kubernetes-native OPA integration implementing admission control via ConstraintTemplates |
| ConstraintTemplate | CRD defining the Rego policy logic and parameters schema for a class of constraints |
| Constraint | Instance of a ConstraintTemplate with specific parameters and scope (which resources to check) |
| Admission Controller | Kubernetes component that intercepts API requests before persistence and can allow or deny them |
| conftest | CLI tool for testing structured data (YAML, JSON, HCL) against OPA policies |
Tools & Systems
- Open Policy Agent (OPA): General-purpose policy engine for unified policy enforcement
- Gatekeeper: Kubernetes admission controller built on OPA with CRD-based configuration
- conftest: Testing framework for OPA policies against configuration files
- Kyverno: Alternative Kubernetes policy engine using YAML-based policies (no Rego required)
- Styra DAS: Commercial OPA management platform with policy authoring, testing, and distribution
Common Scenarios
Scenario: Enforcing Container Security Standards Across Clusters
Context: Multiple development teams deploy to shared Kubernetes clusters. Some teams run privileged containers and images without resource limits, causing security and stability issues.
Approach:
- Deploy Gatekeeper on all clusters via GitOps (Helm chart in a FluxCD repository)
- Create ConstraintTemplates for: no privileged containers, required resource limits, required labels, no latest tag
- Start with
enforcementAction: warnto identify violations without blocking deployments - Notify teams of violations and provide a 2-week remediation window
- Switch to
enforcementAction: denyafter the remediation period - Add
excludedNamespacesfor kube-system and monitoring namespaces
Pitfalls: Deploying Gatekeeper with deny mode immediately can break existing workloads. Always start with warn mode. Overly restrictive policies without exemptions for system namespaces can prevent cluster components from functioning.
Output Format
OPA Policy Evaluation Report
==============================
Cluster: production-east
Date: 2026-02-23
Gatekeeper Version: 3.16.0
CONSTRAINT SUMMARY:
K8sRequiredLabels: 12 violations (warn)
K8sBlockPrivileged: 0 violations (deny)
K8sContainerLimits: 8 violations (deny)
K8sBlockLatestTag: 3 violations (deny)
BLOCKED DEPLOYMENTS (deny):
[K8sContainerLimits] deployment/api-server in ns/payments
- Container 'api' has no memory limit
[K8sBlockLatestTag] deployment/frontend in ns/web
- Container 'nginx' uses :latest tag
AUDIT VIOLATIONS (warn):
[K8sRequiredLabels] namespace/staging
- Missing labels: {cost-center}
How to use implementing-policy-as-code-with-open-policy-agent 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-policy-as-code-with-open-policy-agent
Execute installation command
Execute the skills CLI command in your project's root directory to begin installation:
The skills CLI fetches implementing-policy-as-code-with-open-policy-agent 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-policy-as-code-with-open-policy-agent. Access the skill through slash commands (e.g., /implementing-policy-as-code-with-open-policy-agent) 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▌
Accelerate Code Development
Use skill to generate boilerplate code, refactor legacy code, and write tests faster
Example
Generate React component with TypeScript types, styled-components, and comprehensive test suite in minutes
Reduce development time by 40-60% for repetitive coding tasks
Code Review Automation
Systematically review code for bugs, security issues, and style violations
Example
Analyze pull requests for common anti-patterns, suggest performance improvements, flag security vulnerabilities
Catch 70%+ of code issues before human review, improve code quality
Debug Complex Issues
Trace errors through stack traces and identify root causes faster
Example
Analyze error logs, suggest probable causes, recommend fixes with code examples
Cut debugging time by 30-50%, especially for unfamiliar codebases
Learn New Technologies
Get explanations, examples, and best practices for unfamiliar frameworks
Example
Understand Next.js app router, learn Rust ownership, grasp Kubernetes concepts with practical examples
Accelerate learning curve by 2-3x, reduce onboarding time for new tech stacks
Implementation Guide▌
Prerequisites
- ›Claude Desktop or compatible AI client with skill installation support
- ›Basic understanding of programming concepts and version control (Git)
- ›Code editor or IDE for testing generated code (VS Code, JetBrains, etc.)
- ›Test environment separate from production for validating skill outputs
Time Estimate
15-30 minutes to install and see first useful output
Installation Steps
- 1.Install the skill using provided installation command
- 2.Verify skill is loaded in Claude Desktop (check ~/.claude/skills directory)
- 3.Test skill with simple prompt: 'Help me review this code snippet'
- 4.Gradually increase complexity: code generation → refactoring → architecture advice
- 5.Review all generated code before committing to repository
- 6.Iterate on prompts to improve output quality and relevance
- 7.Share effective prompts with team for consistency
Common Pitfalls
- ⚠Blindly trusting generated code without testing—always run tests and manual review
- ⚠Not providing enough context about your project structure and coding standards
- ⚠Expecting perfection on first generation—iteration and refinement are normal
- ⚠Sharing proprietary code or API keys in prompts—maintain confidentiality
- ⚠Over-relying on skill for critical security or business logic code
- ⚠Skipping documentation of why AI-generated code was chosen over alternatives
Best Practices▌
✓ Do
- +Always review and test AI-generated code before merging
- +Provide clear context: language, framework, coding standards, constraints
- +Use for boilerplate, tests, docs—areas where mistakes are easily caught
- +Iterate on prompts: start broad, refine with specific requirements
- +Combine AI suggestions with human judgment and domain expertise
- +Document successful prompt patterns for team reuse
- +Keep version control so you can rollback if needed
- +Use skill for learning and exploration, not production-critical features initially
✗ Don't
- −Don't commit AI code without thorough testing and review
- −Don't expose sensitive code, credentials, or proprietary algorithms
- −Don't use for security-critical code (auth, crypto, payments) without expert review
- −Don't skip peer review process just because AI generated it
- −Don't assume code follows your team's conventions—verify
- −Don't let junior developers skip learning fundamentals by relying solely on AI
- −Don't ignore compiler warnings or test failures in generated code
💡 Pro Tips
- ★Describe desired patterns explicitly: 'Use async/await, avoid callbacks'
- ★Ask for alternatives: 'Show 3 approaches to solve this, with tradeoffs'
- ★Request explanations: 'Explain why this approach is better than X'
- ★Use skill for 70% generation + 30% manual refinement for best results
- ★Build a prompt library for common patterns (API endpoints, components, tests)
- ★Pair program with AI: describe problem → review solution → iterate → refine
When to Use This▌
✓ Use When
Use coding skills for boilerplate generation, code reviews, refactoring legacy code, writing tests, learning new frameworks, and debugging non-critical issues. Best for repetitive tasks where errors are easy to catch.
✗ Avoid When
Avoid for production security features (auth, encryption, payment processing), complex business logic requiring deep domain knowledge, performance-critical algorithms, or when learning fundamentals is more valuable than speed.
Learning Path▌
- 1Start with simple tasks: generate functions, write tests, explain code
- 2Progress to code review: analyze PRs, suggest improvements
- 3Advanced: architectural decisions, refactoring strategies, performance optimization
- 4Expert: use for exploring new paradigms, researching best practices, mentoring juniors
Integration▌
- →VS Code
- →JetBrains IDEs
- →Cursor
- →GitHub Copilot
- →Git workflows
Discussion
Product Hunt–style comments (not star reviews)- No comments yet — start the thread.
Ratings
4.5★★★★★70 reviews- ★★★★★Layla Yang· Dec 28, 2024
We added implementing-policy-as-code-with-open-policy-agent from the explainx registry; install was straightforward and the SKILL.md answered most questions upfront.
- ★★★★★Zara Shah· Dec 28, 2024
Registry listing for implementing-policy-as-code-with-open-policy-agent matched our evaluation — installs cleanly and behaves as described in the markdown.
- ★★★★★Tariq Kapoor· Dec 20, 2024
Useful defaults in implementing-policy-as-code-with-open-policy-agent — fewer surprises than typical one-off scripts, and it plays nicely with `npx skills` flows.
- ★★★★★Zara Johnson· Dec 16, 2024
I recommend implementing-policy-as-code-with-open-policy-agent for anyone iterating fast on agent tooling; clear intent and a small, reviewable surface area.
- ★★★★★Amina Chawla· Dec 12, 2024
Useful defaults in implementing-policy-as-code-with-open-policy-agent — fewer surprises than typical one-off scripts, and it plays nicely with `npx skills` flows.
- ★★★★★Chaitanya Patil· Dec 4, 2024
Useful defaults in implementing-policy-as-code-with-open-policy-agent — fewer surprises than typical one-off scripts, and it plays nicely with `npx skills` flows.
- ★★★★★Piyush G· Nov 23, 2024
implementing-policy-as-code-with-open-policy-agent is among the better-maintained entries we tried; worth keeping pinned for repeat workflows.
- ★★★★★Zara Sethi· Nov 23, 2024
Solid pick for teams standardizing on skills: implementing-policy-as-code-with-open-policy-agent is focused, and the summary matches what you get after install.
- ★★★★★Evelyn Sanchez· Nov 19, 2024
implementing-policy-as-code-with-open-policy-agent reduced setup friction for our internal harness; good balance of opinion and flexibility.
- ★★★★★Zara Brown· Nov 19, 2024
implementing-policy-as-code-with-open-policy-agent fits our agent workflows well — practical, well scoped, and easy to wire into existing repos.
showing 1-10 of 70