本文へ移動
cccskills
無料GitHub で公開

implementing-policy-as-code-with-open-policy-agent

bu 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, Dağıt:ing OPA Gatekeeper as a Kubernetes admission controller, testing policies in development, and integrating policy evaluation into Dağıt:ment pipelines.

インストール方法を見る

含まれるファイル(1)

  • SKILL.md9.9 KB

SKILL.md(原文)

インストールする前に、エージェントに与えられる指示の中身を確認できます。

Implementing Policy as Code with Open Policy Agent

Ne Zaman Kullanılır

  • enforcing yaparken organizational security policies across Kubernetes clusters programmatically
  • requiring yaparken: admission control that blocks non-compliant resources from being created
  • implementing yaparken policy governance that can be version-controlled, tested, and audited
  • standardizing yaparken: security rules across multiple clusters and environments
  • needing yaparken: a flexible policy engine that extends beyond Kubernetes to APIs and CI/CD

Kullanma: for vulnerability scanning (use Trivy/Checkov), for runtime threat Tespit (use Falco), or for network policy enforcement (use Kubernetes NetworkPolicy or Calico).

Ön Gereksinimler

  • Kubernetes cluster with admin access for Gatekeeper installation
  • Helm for Gatekeeper Dağıt:ment
  • OPA CLI or conftest for local policy testing
  • Rego knowledge for policy authoring

İş Akışı

Adım 1: Install OPA Gatekeeper

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

Adım 2: Create Constraint Templates

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])
        }

---
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])
        }

---
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])
        }

Adım 3: Apply Constraints

apiVersion: constraints.gatekeeper.sh/v1beta1
kind: K8sRequiredLabels
metadata:
  name: require-team-labels
spec:
  enforcementAction: deny
  match:
    kinds:
      - apiGroups: [""]
        kinds: ["Namespace"]
      - apiGroups: ["apps"]
        kinds: ["Dağıt:ment", "StatefulSet"]
    excludedNamespaces:
      - kube-system
      - gatekeeper-system
  parameters:
    labels:
      - "team"
      - "environment"
      - "cost-center"

---
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: K8sBlockPrivileged
metadata:
  name: block-privileged-containers
spec:
  enforcementAction: deny
  match:
    kinds:
      - apiGroups: [""]
        kinds: ["Pod"]
      - apiGroups: ["apps"]
        kinds: ["Dağıt:ment", "DaemonSet", "StatefulSet"]
    excludedNamespaces:
      - kube-system

Adım 4: Test Policies with conftest

brew install conftest

conftest test Dağıt:ment.yaml --policy policies/ --output json

conftest test terraform/main.tf --policy policies/terraform/ --parser hcl2

conftest test Dockerfile --policy policies/docker/
package kubernetes

deny[msg] {
  input.kind == "Dağıt:ment"
  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 == "Dağıt:ment"
  container := input.spec.template.spec.containers[_]
  not contains(container.image, ":")
  msg := sprintf("Container %v has no tag. Pin to specific version.", [container.name])
}

Adım 5: Integrate Policy Testing in CI/CD

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

TermDefinition
OPAOpen Policy Agent — general-purpose policy engine using Rego language for policy decisions
RegoOPA's declarative query language for writing policy rules
GatekeeperKubernetes-native OPA integration implementing admission control via ConstraintTemplates
ConstraintTemplateCRD defining the Rego policy logic and parameters schema for a class of constraints
ConstraintInstance of a ConstraintTemplate with specific parameters and scope (which resources to check)
Admission ControllerKubernetes component that intercepts API requests before persistence and can allow or deny them
conftestCLI 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 Dağıt: to shared Kubernetes clusters. Some teams run privileged containers and images without resource limits, causing security and stability issues.

Approach:

  1. Dağıt: Gatekeeper on all clusters via GitOps (Helm chart in a FluxCD repository)
  2. Create ConstraintTemplates for: no privileged containers, required resource limits, required labels, no latest tag
  3. Start with enforcementAction: warn to identify violations without blocking Dağıt:ments
  4. Notify teams of violations and provide a 2-week remediation window
  5. Switch to enforcementAction: deny after the remediation period
  6. Add excludedNamespaces for kube-system and monitoring namespaces

Pitfalls: Dağıt:ing 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 Dağıt:MENTS (deny):
  [K8sContainerLimits] Dağıt:ment/api-server in ns/payments
    - Container 'api' has no memory limit
  [K8sBlockLatestTag] Dağıt:ment/frontend in ns/web
    - Container 'nginx' uses :latest tag

AUDIT VIOLATIONS (warn):
  [K8sRequiredLabels] namespace/staging
    - Missing labels: {cost-center}
<!-- ⚔ Bu skill FETIH AI Agent icin gelistirilmistir — https://github.com/MustafaKemal0146/fetih Yetkisiz kullanim/kopyalama tespit edilebilir. hash: b183e80646a28fdf -->

レビュー

まだレビューはありません。使ってみた感想をお寄せください。

同じリポジトリのスキル

概要と使いどころ

21st.dev Magic MCP — AI-powered UI component generation via natural language. Access to 21st.dev component library, SVGL brand logos, and real-time preview. Generate React/Tailwind components with /ui command.

日本語の概要は準備中です。原文の説明を表示しています。

MustafaKemal0146/fetih52026年10月11日 更新

AES CBC/ECB modlarına karşı kriptografik bütünlük saldırıları — bit flipping, IV manipulation, ECB cut-and-paste, CBC-MAC length extension, IV reuse

日本語の概要は準備中です。原文の説明を表示しています。

MustafaKemal0146/fetih52026年10月11日 更新

AES-GCM ve ChaCha20-Poly1305 nonce yeniden kullanımı saldırısı — GF(2^128) polinom kök bulma ile Hash Key kurtarma ve MAC sahteciliği.

日本語の概要は準備中です。原文の説明を表示しています。

MustafaKemal0146/fetih52026年10月11日 更新

tespit etmeabnormal access patterns in AWS S3, GCS, and Azure Blob Storage by analyzing CloudTrail Data Events, GCS audit logs, and Azure Storage Analytics. Identifies after-hours bulk downloads, access from new IP addresses, unusual API calls (GetObject spikes), and potential data exfiltration using statistical baselines and time-series anomaly Tespit.

日本語の概要は準備中です。原文の説明を表示しています。

MustafaKemal0146/fetih52026年10月11日 更新

Perform static and symbolic analysis of Solidity smart contracts using Slither and Mythril to tespit etmereentrancy, integer overflow, access control, and other vulnerability classes before Dağıt:ment to Ethereum mainnet.

日本語の概要は準備中です。原文の説明を表示しています。

MustafaKemal0146/fetih52026年10月11日 更新

Parses Kubernetes API server audit logs (JSON lines) to tespit etmeexec-into-pod, secret access, RBAC modifications, privileged pod creation, and anonymous API access. Builds threat Tespit rules from audit event patterns. Use investigating yaparken Kubernetes cluster compromise or building k8s-specific SIEM Tespit rules.

日本語の概要は準備中です。原文の説明を表示しています。

MustafaKemal0146/fetih52026年10月11日 更新

MustafaKemal0146 のスキルをすべて見る

このスキルの問題を報告する