- name
- custom-rego-policy-generator
- description
- Interactive Rego policy generator assistant. Analyzes requirements, recommends admission controllers (Gatekeeper/Kyverno/VAP), generates Rego code, validates with OPA, and creates RHACM-ready constraint files.
- allowed-tools
- ["Read","Write","Bash","AskUserQuestion"]
# Custom Rego Policy Generator
Interactive assistant for generating Kubernetes admission policies. This skill analyzes your requirements, recommends the best admission controller, and generates validated policies.
---
## Step 1: Understand the Requirement
When user provides a policy requirement, extract:
1. What action to take (block, allow, require, modify, generate)
2. What resource type (Pod, Deployment, Service, etc.)
3. What condition triggers the policy
4. Any parameters needed (thresholds, lists, patterns)
Example requirements:
- "Block pods without resource limits"
- "Require all deployments to have app and owner labels"
- "Prevent containers from running as root"
- "Ensure all ingress uses HTTPS"
---
## Step 2: Ask Clarifying Questions
Use AskUserQuestion to gather missing information:
Questions to ask:
- What Kubernetes version is your cluster running?
- Should the policy block violations or just report them? (enforcement mode)
- Are there namespaces that should be excluded?
- Do you need to modify resources or just validate them?
- Should this apply to all clusters or specific ones?
---
## Step 3: Analyze and Recommend Controller
Based on requirements, use `references/ADMISSION_CONTROLLER_COMPARISON.md` to recommend.
Decision Logic:
IF user needs mutation (modify resources):
RECOMMEND: Kyverno
REASON: Kyverno has mature mutation support, Gatekeeper mutation is alpha
IF user needs resource generation (auto-create ConfigMaps, NetworkPolicies):
RECOMMEND: Kyverno
REASON: Only Kyverno supports generation
IF user needs image signature verification:
RECOMMEND: Kyverno
REASON: Native Sigstore/Cosign support
IF Kubernetes version < 1.30 AND validation only:
RECOMMEND: Kyverno (easier) or Gatekeeper (more powerful)
REASON: ValidatingAdmissionPolicy requires v1.30+
IF Kubernetes version >= 1.30 AND validation only AND simple logic:
RECOMMEND: ValidatingAdmissionPolicy
REASON: Built-in, best performance, no external dependencies
IF complex logic OR cross-resource validation OR external data:
RECOMMEND: Gatekeeper
REASON: Rego is most powerful for complex scenarios
Present recommendation to user:
```
Requirement Analysis:
Policy Type: [Validation/Mutation/Generation]
Complexity: [Simple/Moderate/Complex]
Kubernetes Version: [version]
Special Features: [any special needs]
Recommended Controller: [Gatekeeper/Kyverno/ValidatingAdmissionPolicy]
Rationale:
- [Key reason 1]
- [Key reason 2]
Alternative Options:
- [Alternative]: [When to consider]
```
Ask user to confirm or select different controller.
---
## Step 4: Generate Policy (Controller-Specific)
Based on user selection:
- Gatekeeper: Continue to Step 5
- Kyverno: Use `references/KYVERNO_PATTERNS.md` and generate YAML policy
- ValidatingAdmissionPolicy: Use `references/VAP_PATTERNS.md` and generate CEL policy
---
## Step 5: Generate Rego Code (Gatekeeper)
Read `references/REGO_PATTERNS.md` for syntax and patterns.
Rego Requirements:
1. Use OPA v0.43.0+ syntax with `if` and `contains` keywords
2. Package name: lowercase, no hyphens
3. Always include namespace exclusion helper
4. Use clear violation messages with resource name/namespace
5. Access parameters via `input.parameters.*`
6. Access resource via `input.review.object`
Basic validation pattern:
```rego
package policynamehere
import future.keywords.if
import future.keywords.contains
violation contains {"msg": msg} if {
not is_excluded_namespace
# policy logic here
msg := sprintf("Violation message: %s/%s", [namespace, name])
}
is_excluded_namespace if {
excluded := {"kube-system", "kube-public", "gatekeeper-system"}
input.review.object.metadata.namespace == excluded[_]
}
is_excluded_namespace if {
startswith(input.review.object.metadata.namespace, "openshift-")
}
```
---
## Step 6: Validate with OPA
Save Rego to temp file and validate:
```bash
# Write Rego code
cat > /tmp/claude/policy.rego <<'EOF'
[GENERATED_REGO_CODE]
EOF
# Write test input
cat > /tmp/claude/input.json <<'EOF'
{
"review": {
"operation": "CREATE",
"object": {
"apiVersion": "v1",
"kind": "Pod",
"metadata": {
"name": "test-pod",
"namespace": "default"
},
"spec": {
"containers": [{"name": "app", "image": "nginx"}]
}
}
},
"parameters": {}
}
EOF
# Validate syntax and evaluate
opa eval -d /tmp/claude/policy.rego -i /tmp/claude/input.json "data.policynamehere.violation" --format pretty
```
If validation fails:
- Fix syntax errors
- Re-run validation
- Repeat until passes
If validation passes:
- Show user the results
- Explain what violations were found (or not found)
---
## Step 7: User Feedback on Rego
Present generated Rego to user with:
- Package name
- What it validates
- Parameters used
- OPA validation results
Ask user: "Does this look correct? Any changes needed?"
If user provides feedback:
1. Understand what needs to change
2. Modify the Rego code
3. Re-validate with OPA (Step 6)
4. Show updated code
5. Ask again until user confirms
If user confirms, proceed to Step 8.
---
## Step 8: Create Output Directory
```bash
TRACE_ID=$(python3 skills/custom-rego-policy-generator/scripts/get_trace_id.py 2>/dev/null || echo "no-trace")
OUTPUT_DIR="skills/custom-rego-policy-generator/assets/${TRACE_ID}"
mkdir -p ${OUTPUT_DIR}/{constraint-templates,constraints}
```
---
## Step 9: Generate ConstraintTemplate
Read `references/CONSTRAINTTEMPLATE_STRUCTURE.md` for structure.
Create `${OUTPUT_DIR}/constraint-templates/{policy-name}-template.yaml`:
```yaml
apiVersion: templates.gatekeeper.sh/v1
kind: ConstraintTemplate
metadata:
name: {templatenamenolowercase}
annotations:
description: "{user requirement}"
generated-by: "custom-rego-policy-generator"
spec:
crd:
spec:
names:
kind: {CamelCaseKind}
validation:
openAPIV3Schema:
type: object
properties:
{paramName}:
type: {string|integer|boolean|array}
description: "{param description}"
targets:
- target: admission.k8s.gatekeeper.sh
rego: |
{VALIDATED_REGO_CODE}
```
---
## Step 10: Generate Constraint
Create `${OUTPUT_DIR}/constraints/{policy-name}.yaml`:
```yaml
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: {CRDKind}
metadata:
name: {policy-name}
labels:
policy-type: custom
generated-by: custom-rego-policy-generator
spec:
enforcementAction: dryrun
match:
kinds:
- apiGroups: ["{apiGroup}"]
kinds: ["{Kind}"]
excludedNamespaces:
- kube-system
- kube-public
- kube-node-lease
- gatekeeper-system
- openshift-*
parameters:
{paramName}: {value}
```
Always start with `enforcementAction: dryrun` for audit mode.
---
## Step 11: Generate PolicyGenerator (for RHACM)
Read `references/POLICYGENERATOR_FORMAT.md` for structure.
Create `${OUTPUT_DIR}/policyGenerator.yaml`:
```yaml
apiVersion: policy.open-cluster-management.io/v1
kind: PolicyGenerator
metadata:
name: custom-{policy-name}
placementBindingDefaults:
name: {policy-name}-binding
policyDefaults:
namespace: policies
placement:
placementName: {policy-name}-placement
remediationAction: inform
informGatekeeperPolicies: false
pruneObjectBehavior: DeleteIfCreated
ignorePending: true
policies:
- name: policy-{policy-name}-template
manifests:
- path: constraint-templates/{policy-name}-template.yaml
remediationAction: enforce
- name: policy-{policy-name}-constraint
manifests:
- path: constraints/{policy-name}.yaml
dependencies:
- name: policy-{policy-name}-template
compliance: Compliant
```
Create `${OUTPUT_DIR}/kustomization.yaml`:
```yaml
apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization
generators:
- policyGenerator.yaml
```
---
## Step 12: Summary
Present final output to user:
```
Policy Generation Complete
Output Directory: skills/custom-rego-policy-generator/assets/{TRACE_ID}/
Generated Files:
constraint-templates/{policy-name}-template.yaml
constraints/{policy-name}.yaml
policyGenerator.yaml
kustomization.yaml
Deployment Options:
Direct to Cluster:
kubectl apply -f constraint-templates/
kubectl apply -f constraints/
Via RHACM PolicyGenerator:
kustomize build --enable-alpha-plugins . | kubectl apply -n policies -f -
Testing:
1. Policy starts in dryrun mode (audit only)
2. Check violations: kubectl get {constraintkind} -o yaml
3. To enforce: change enforcementAction to "deny"
```
---
## Step 13: Final Feedback
Ask user: "Any changes needed to the generated files?"
If user provides feedback:
1. Identify which file needs changes (Rego, constraint, policyGenerator)
2. Make the requested changes
3. Show updated file
4. Ask again until user confirms
If changes affect Rego logic:
- Return to Step 5, regenerate, revalidate, update all files
If changes affect constraint or policyGenerator:
- Edit the specific file directly
Once user confirms, generation is complete.
---
## Reference Files
references/ADMISSION_CONTROLLER_COMPARISON.md
- Feature comparison of Gatekeeper, Kyverno, VAP
- Decision tree for selecting controller
- Performance and security considerations
references/REGO_PATTERNS.md
- OPA syntax examples
- Validation and mutation patterns
- Helper functions
- Namespace exclusion patterns
references/CONSTRAINTTEMPLATE_STRUCTURE.md
- ConstraintTemplate anatomy
- Parameter schema definitions
- CRD naming conventions
references/POLICYGENERATOR_FORMAT.md
- RHACM PolicyGenerator structure
- Placement patterns
- Dependency chains
references/KYVERNO_PATTERNS.md
- Kyverno policy patterns
- Mutation and generation examples
references/VAP_PATTERNS.md
- ValidatingAdmissionPolicy patterns
- CEL expression examples
---
## Trigger Phrases
- "Create a policy that blocks..."
- "Generate a policy to prevent..."
- "I need a policy to require..."
- "Make a Gatekeeper policy for..."
- "Which admission controller should I use for..."
---
## When to Use This Skill
Use for:
- Custom policy requirements
- Natural language to Rego conversion
- Comparing admission controllers
- Generating validated Gatekeeper policies
Do NOT use for:
- NIST/BSI compliance -> use rhacm-unified-policy-agent
- Full gatekeeper-library deployment -> use gatekeeper-rhacm-integration
GitHubで見る