jpskill.com
🛠️ 開発・MCP コミュニティ

policy-opa

Open Policy Agent (OPA)を活用し、インフラやアプリケーションにおけるセキュリティ・コンプライアンスポリシーの適用、Kubernetesのポリシー検証、CI/CDパイプラインへの統合などを実現し、組織のセキュリティ基準に沿った設定を維持するSkill。

📜 元の英語説明(参考)

Policy-as-code enforcement and compliance validation using Open Policy Agent (OPA). Use when: (1) Enforcing security and compliance policies across infrastructure and applications, (2) Validating Kubernetes admission control policies, (3) Implementing policy-as-code for compliance frameworks (SOC2, PCI-DSS, GDPR, HIPAA), (4) Testing and evaluating OPA Rego policies, (5) Integrating policy checks into CI/CD pipelines, (6) Auditing configuration drift against organizational security standards, (7) Implementing least-privilege access controls.

🇯🇵 日本人クリエイター向け解説

一言でいうと

Open Policy Agent (OPA)を活用し、インフラやアプリケーションにおけるセキュリティ・コンプライアンスポリシーの適用、Kubernetesのポリシー検証、CI/CDパイプラインへの統合などを実現し、組織のセキュリティ基準に沿った設定を維持するSkill。

※ jpskill.com 編集部が日本のビジネス現場向けに補足した解説です。Skill本体の挙動とは独立した参考情報です。

⚡ おすすめ: コマンド1行でインストール(60秒)

下記のコマンドをコピーしてターミナル(Mac/Linux)または PowerShell(Windows)に貼り付けてください。 ダウンロード → 解凍 → 配置まで全自動。

🍎 Mac / 🐧 Linux
mkdir -p ~/.claude/skills && cd ~/.claude/skills && curl -L -o policy-opa.zip https://jpskill.com/download/17033.zip && unzip -o policy-opa.zip && rm policy-opa.zip
🪟 Windows (PowerShell)
$d = "$env:USERPROFILE\.claude\skills"; ni -Force -ItemType Directory $d | Out-Null; iwr https://jpskill.com/download/17033.zip -OutFile "$d\policy-opa.zip"; Expand-Archive "$d\policy-opa.zip" -DestinationPath $d -Force; ri "$d\policy-opa.zip"

完了後、Claude Code を再起動 → 普通に「動画プロンプト作って」のように話しかけるだけで自動発動します。

💾 手動でダウンロードしたい(コマンドが難しい人向け)
  1. 1. 下の青いボタンを押して policy-opa.zip をダウンロード
  2. 2. ZIPファイルをダブルクリックで解凍 → policy-opa フォルダができる
  3. 3. そのフォルダを C:\Users\あなたの名前\.claude\skills\(Win)または ~/.claude/skills/(Mac)へ移動
  4. 4. Claude Code を再起動

⚠️ ダウンロード・利用は自己責任でお願いします。当サイトは内容・動作・安全性について責任を負いません。

🎯 このSkillでできること

下記の説明文を読むと、このSkillがあなたに何をしてくれるかが分かります。Claudeにこの分野の依頼をすると、自動で発動します。

📦 インストール方法 (3ステップ)

  1. 1. 上の「ダウンロード」ボタンを押して .skill ファイルを取得
  2. 2. ファイル名の拡張子を .skill から .zip に変えて展開(macは自動展開可)
  3. 3. 展開してできたフォルダを、ホームフォルダの .claude/skills/ に置く
    • · macOS / Linux: ~/.claude/skills/
    • · Windows: %USERPROFILE%\.claude\skills\

Claude Code を再起動すれば完了。「このSkillを使って…」と話しかけなくても、関連する依頼で自動的に呼び出されます。

詳しい使い方ガイドを見る →
最終更新
2026-05-18
取得日時
2026-05-18
同梱ファイル
14

📖 Skill本文(日本語訳)

※ 原文(英語/中国語)を Gemini で日本語化したものです。Claude 自身は原文を読みます。誤訳がある場合は原文をご確認ください。

Open Policy Agent を用いた Policy-as-Code

概要

このスキルは、コンプライアンス検証、セキュリティポリシーの適用、および構成監査のために、Open Policy Agent (OPA) を使用した policy-as-code の適用を可能にします。OPA は、クラウドネイティブ環境、Kubernetes、CI/CD パイプライン、および infrastructure-as-code 全体でポリシー評価を行うための統一されたフレームワークを提供します。

OPA を使用して、セキュリティ要件、コンプライアンス制御、および組織標準を、Rego で記述された実行可能なポリシーとしてコード化します。構成を自動的に検証し、構成ミスを防ぎ、継続的なコンプライアンスを維持します。

クイックスタート

OPA のインストール

# macOS
brew install opa

# Linux
curl -L -o opa https://openpolicyagent.org/downloads/latest/opa_linux_amd64
chmod +x opa

# インストール確認
opa version

基本的なポリシー評価

# 入力データに対してポリシーを評価する
opa eval --data policy.rego --input input.json 'data.example.allow'

# ユニットテストでポリシーをテストする
opa test policy.rego policy_test.rego --verbose

# ライブポリシー評価のために OPA サーバーを実行する
opa run --server --addr localhost:8181

コアワークフロー

ステップ 1: ポリシー要件の定義

適用するコンプライアンス要件とセキュリティ制御を特定します。

  • コンプライアンスフレームワーク (SOC2, PCI-DSS, GDPR, HIPAA, NIST)
  • Kubernetes セキュリティポリシー (pod security, RBAC, network policies)
  • Infrastructure-as-code ポリシー (Terraform, CloudFormation)
  • アプリケーションセキュリティポリシー (API 認証, データアクセス)
  • 組織のセキュリティ標準

ステップ 2: OPA Rego ポリシーの記述

Rego 言語でポリシーファイルを作成します。一般的なパターンについては、assets/ にある提供されたテンプレートを使用してください。

例: Kubernetes Pod Security Policy

package kubernetes.admission

import future.keywords.contains
import future.keywords.if

deny[msg] {
    input.request.kind.kind == "Pod"
    container := input.request.object.spec.containers[_]
    container.securityContext.privileged == true
    msg := sprintf("Privileged containers are not allowed: %v", [container.name])
}

deny[msg] {
    input.request.kind.kind == "Pod"
    container := input.request.object.spec.containers[_]
    not container.securityContext.runAsNonRoot
    msg := sprintf("Container must run as non-root: %v", [container.name])
}

例: コンプライアンス制御の検証 (SOC2)

package compliance.soc2

import future.keywords.if

# CC6.1: 論理的および物理的なアクセス制御
deny[msg] {
    input.kind == "Deployment"
    not input.spec.template.metadata.labels["data-classification"]
    msg := "SOC2 CC6.1: All deployments must have data-classification label"
}

# CC6.6: 転送中の暗号化
deny[msg] {
    input.kind == "Service"
    input.spec.type == "LoadBalancer"
    not input.metadata.annotations["service.beta.kubernetes.io/aws-load-balancer-ssl-cert"]
    msg := "SOC2 CC6.6: LoadBalancer services must use SSL/TLS encryption"
}

ステップ 3: ユニットテストによるポリシーのテスト

ポリシー検証のための包括的なテストを作成します。

package kubernetes.admission_test

import data.kubernetes.admission

test_deny_privileged_container {
    input := {
        "request": {
            "kind": {"kind": "Pod"},
            "object": {
                "spec": {
                    "containers": [{
                        "name": "nginx",
                        "securityContext": {"privileged": true}
                    }]
                }
            }
        }
    }
    count(admission.deny) > 0
}

test_allow_unprivileged_container {
    input := {
        "request": {
            "kind": {"kind": "Pod"},
            "object": {
                "spec": {
                    "containers": [{
                        "name": "nginx",
                        "securityContext": {"privileged": false, "runAsNonRoot": true}
                    }]
                }
            }
        }
    }
    count(admission.deny) == 0
}

テストの実行:

opa test . --verbose

ステップ 4: 構成に対するポリシーの評価

ポリシー検証には、バンドルされている評価スクリプトを使用します。

# 単一ファイルの評価
./scripts/evaluate_policy.py --policy policies/ --input config.yaml

# 構成ディレクトリの評価
./scripts/evaluate_policy.py --policy policies/ --input configs/ --recursive

# CI/CD 統合のための JSON 形式での結果の出力
./scripts/evaluate_policy.py --policy policies/ --input config.yaml --format json

または、OPA を直接使用します。

# フォーマットされた出力で評価する
opa eval --data policies/ --input config.yaml --format pretty 'data.compliance.violations'

# 複雑なポリシーのための評価のバンドル
opa eval --bundle policies.tar.gz --input config.yaml 'data'

ステップ 5: CI/CD パイプラインとの統合

ポリシー検証を CI/CD ワークフローに追加します。

GitHub Actions の例:

- name: Validate Policies
  uses: open-policy-agent/setup-opa@v2
  with:
    version: latest

- name: Run Policy Tests
  run: opa test policies/ --verbose

- name: Evaluate Configuration
  run: |
    opa eval --data policies/ --input deployments/ \
      --format pretty 'data.compliance.violations' > violations.json

    if [ $(jq 'length' violations.json) -gt 0 ]; then
      echo "Policy violations detected!"
      cat violations.json
      exit 1
    fi

GitLab CI の例:

policy-validation:
  image: openpolicyagent/opa:latest
  script:
    - opa test policies/ --verbose
    - opa eval --data policies/ --input configs/ --format pretty 'data.compliance.violations'
  artifacts:
    reports:
      junit: test-results.xml

ステップ 6: Kubernetes Admission Controller としてのデプロイ

OPA Gatekeeper を使用して、クラスターレベルでポリシーを適用します。


# OPA Gatekeeper のインストール
kubectl apply -f https://raw.githubusercontent.com/open-policy-agent/gatekeeper/master/deploy/gatekeeper.yaml

# 制約テンプレートの適用
kubectl apply -f assets/k8s-constraint-template.yaml

# 制約の適用
kubectl apply -f assets/k8s-constraint.yaml

# Admission Control のテスト
ku

(原文がここで切り詰められています)
📜 原文 SKILL.md(Claudeが読む英語/中国語)を展開

Policy-as-Code with Open Policy Agent

Overview

This skill enables policy-as-code enforcement using Open Policy Agent (OPA) for compliance validation, security policy enforcement, and configuration auditing. OPA provides a unified framework for policy evaluation across cloud-native environments, Kubernetes, CI/CD pipelines, and infrastructure-as-code.

Use OPA to codify security requirements, compliance controls, and organizational standards as executable policies written in Rego. Automatically validate configurations, prevent misconfigurations, and maintain continuous compliance.

Quick Start

Install OPA

# macOS
brew install opa

# Linux
curl -L -o opa https://openpolicyagent.org/downloads/latest/opa_linux_amd64
chmod +x opa

# Verify installation
opa version

Basic Policy Evaluation

# Evaluate a policy against input data
opa eval --data policy.rego --input input.json 'data.example.allow'

# Test policies with unit tests
opa test policy.rego policy_test.rego --verbose

# Run OPA server for live policy evaluation
opa run --server --addr localhost:8181

Core Workflow

Step 1: Define Policy Requirements

Identify compliance requirements and security controls to enforce:

  • Compliance frameworks (SOC2, PCI-DSS, GDPR, HIPAA, NIST)
  • Kubernetes security policies (pod security, RBAC, network policies)
  • Infrastructure-as-code policies (Terraform, CloudFormation)
  • Application security policies (API authorization, data access)
  • Organizational security standards

Step 2: Write OPA Rego Policies

Create policy files in Rego language. Use the provided templates in assets/ for common patterns:

Example: Kubernetes Pod Security Policy

package kubernetes.admission

import future.keywords.contains
import future.keywords.if

deny[msg] {
    input.request.kind.kind == "Pod"
    container := input.request.object.spec.containers[_]
    container.securityContext.privileged == true
    msg := sprintf("Privileged containers are not allowed: %v", [container.name])
}

deny[msg] {
    input.request.kind.kind == "Pod"
    container := input.request.object.spec.containers[_]
    not container.securityContext.runAsNonRoot
    msg := sprintf("Container must run as non-root: %v", [container.name])
}

Example: Compliance Control Validation (SOC2)

package compliance.soc2

import future.keywords.if

# CC6.1: Logical and physical access controls
deny[msg] {
    input.kind == "Deployment"
    not input.spec.template.metadata.labels["data-classification"]
    msg := "SOC2 CC6.1: All deployments must have data-classification label"
}

# CC6.6: Encryption in transit
deny[msg] {
    input.kind == "Service"
    input.spec.type == "LoadBalancer"
    not input.metadata.annotations["service.beta.kubernetes.io/aws-load-balancer-ssl-cert"]
    msg := "SOC2 CC6.6: LoadBalancer services must use SSL/TLS encryption"
}

Step 3: Test Policies with Unit Tests

Write comprehensive tests for policy validation:

package kubernetes.admission_test

import data.kubernetes.admission

test_deny_privileged_container {
    input := {
        "request": {
            "kind": {"kind": "Pod"},
            "object": {
                "spec": {
                    "containers": [{
                        "name": "nginx",
                        "securityContext": {"privileged": true}
                    }]
                }
            }
        }
    }
    count(admission.deny) > 0
}

test_allow_unprivileged_container {
    input := {
        "request": {
            "kind": {"kind": "Pod"},
            "object": {
                "spec": {
                    "containers": [{
                        "name": "nginx",
                        "securityContext": {"privileged": false, "runAsNonRoot": true}
                    }]
                }
            }
        }
    }
    count(admission.deny) == 0
}

Run tests:

opa test . --verbose

Step 4: Evaluate Policies Against Configuration

Use the bundled evaluation script for policy validation:

# Evaluate single file
./scripts/evaluate_policy.py --policy policies/ --input config.yaml

# Evaluate directory of configurations
./scripts/evaluate_policy.py --policy policies/ --input configs/ --recursive

# Output results in JSON format for CI/CD integration
./scripts/evaluate_policy.py --policy policies/ --input config.yaml --format json

Or use OPA directly:

# Evaluate with formatted output
opa eval --data policies/ --input config.yaml --format pretty 'data.compliance.violations'

# Bundle evaluation for complex policies
opa eval --bundle policies.tar.gz --input config.yaml 'data'

Step 5: Integrate with CI/CD Pipelines

Add policy validation to your CI/CD workflow:

GitHub Actions Example:

- name: Validate Policies
  uses: open-policy-agent/setup-opa@v2
  with:
    version: latest

- name: Run Policy Tests
  run: opa test policies/ --verbose

- name: Evaluate Configuration
  run: |
    opa eval --data policies/ --input deployments/ \
      --format pretty 'data.compliance.violations' > violations.json

    if [ $(jq 'length' violations.json) -gt 0 ]; then
      echo "Policy violations detected!"
      cat violations.json
      exit 1
    fi

GitLab CI Example:

policy-validation:
  image: openpolicyagent/opa:latest
  script:
    - opa test policies/ --verbose
    - opa eval --data policies/ --input configs/ --format pretty 'data.compliance.violations'
  artifacts:
    reports:
      junit: test-results.xml

Step 6: Deploy as Kubernetes Admission Controller

Enforce policies at cluster level using OPA Gatekeeper:

# Install OPA Gatekeeper
kubectl apply -f https://raw.githubusercontent.com/open-policy-agent/gatekeeper/master/deploy/gatekeeper.yaml

# Apply constraint template
kubectl apply -f assets/k8s-constraint-template.yaml

# Apply constraint
kubectl apply -f assets/k8s-constraint.yaml

# Test admission control
kubectl apply -f test-pod.yaml  # Should be denied if violates policy

Step 7: Monitor Policy Compliance

Generate compliance reports using the bundled reporting script:

# Generate compliance report
./scripts/generate_report.py --policy policies/ --audit-logs audit.json --output compliance-report.html

# Export violations for SIEM integration
./scripts/generate_report.py --policy policies/ --audit-logs audit.json --format json --output violations.json

Security Considerations

  • Policy Versioning: Store policies in version control with change tracking and approval workflows
  • Least Privilege: Grant minimal permissions for policy evaluation - OPA should run with read-only access to configurations
  • Sensitive Data: Avoid embedding secrets in policies - use external data sources or encrypted configs
  • Audit Logging: Log all policy evaluations, violations, and exceptions for compliance auditing
  • Policy Testing: Maintain comprehensive test coverage (>80%) for all policy rules
  • Separation of Duties: Separate policy authors from policy enforcers; require peer review for policy changes
  • Compliance Mapping: Map policies to specific compliance controls (SOC2 CC6.1, PCI-DSS 8.2.1) for audit traceability

Bundled Resources

Scripts (scripts/)

  • evaluate_policy.py - Evaluate OPA policies against configuration files with formatted output
  • generate_report.py - Generate compliance reports from policy evaluation results
  • test_policies.sh - Run OPA policy unit tests with coverage reporting

References (references/)

  • rego-patterns.md - Common Rego patterns for security and compliance policies
  • compliance-frameworks.md - Policy templates mapped to SOC2, PCI-DSS, GDPR, HIPAA controls
  • kubernetes-security.md - Kubernetes security policies and admission control patterns
  • iac-policies.md - Infrastructure-as-code policy validation for Terraform, CloudFormation

Assets (assets/)

  • k8s-pod-security.rego - Kubernetes pod security policy template
  • k8s-constraint-template.yaml - OPA Gatekeeper constraint template
  • k8s-constraint.yaml - Example Gatekeeper constraint configuration
  • soc2-compliance.rego - SOC2 compliance controls as OPA policies
  • pci-dss-compliance.rego - PCI-DSS requirements as OPA policies
  • gdpr-compliance.rego - GDPR data protection policies
  • terraform-security.rego - Terraform security best practices policies
  • ci-cd-pipeline.yaml - CI/CD integration examples (GitHub Actions, GitLab CI)

Common Patterns

Pattern 1: Kubernetes Admission Control

Enforce security policies at pod creation time:

package kubernetes.admission

deny[msg] {
    input.request.kind.kind == "Pod"
    not input.request.object.spec.securityContext.runAsNonRoot
    msg := "Pods must run as non-root user"
}

Pattern 2: Infrastructure-as-Code Validation

Validate Terraform configurations before apply:

package terraform.security

deny[msg] {
    resource := input.resource_changes[_]
    resource.type == "aws_s3_bucket"
    not resource.change.after.server_side_encryption_configuration
    msg := sprintf("S3 bucket %v must have encryption enabled", [resource.name])
}

Pattern 3: Compliance Framework Mapping

Map policies to specific compliance controls:

package compliance.soc2

# SOC2 CC6.1: Logical and physical access controls
cc6_1_violations[msg] {
    input.kind == "RoleBinding"
    input.roleRef.name == "cluster-admin"
    msg := sprintf("SOC2 CC6.1 VIOLATION: cluster-admin binding for %v", [input.metadata.name])
}

Pattern 4: Data Classification Enforcement

Enforce data handling policies based on classification:

package data.classification

deny[msg] {
    input.metadata.labels["data-classification"] == "restricted"
    input.spec.template.spec.volumes[_].hostPath
    msg := "Restricted data cannot use hostPath volumes"
}

Pattern 5: API Authorization Policies

Implement attribute-based access control (ABAC):

package api.authz

import future.keywords.if

allow if {
    input.method == "GET"
    input.path[0] == "public"
}

allow if {
    input.method == "GET"
    input.user.role == "admin"
}

allow if {
    input.method == "POST"
    input.user.role == "editor"
    input.resource.owner == input.user.id
}

Integration Points

  • CI/CD Pipelines: GitHub Actions, GitLab CI, Jenkins, CircleCI - validate policies before deployment
  • Kubernetes: OPA Gatekeeper admission controller for runtime policy enforcement
  • Terraform/IaC: Pre-deployment validation using conftest or OPA CLI
  • API Gateways: Kong, Envoy, NGINX - authorize requests using OPA policies
  • Monitoring/SIEM: Export policy violations to Splunk, ELK, Datadog for security monitoring
  • Compliance Tools: Integrate with compliance platforms for control validation and audit trails

Troubleshooting

Issue: Policy Evaluation Returns Unexpected Results

Solution:

  • Enable trace mode: opa eval --data policy.rego --input input.json --explain full 'data.example.allow'
  • Validate input data structure matches policy expectations
  • Check for typos in policy rules or variable names
  • Use opa fmt to format policies and catch syntax errors

Issue: Kubernetes Admission Control Not Blocking Violations

Solution:

  • Verify Gatekeeper is running: kubectl get pods -n gatekeeper-system
  • Check constraint status: kubectl get constraints
  • Review audit logs: kubectl logs -n gatekeeper-system -l control-plane=controller-manager
  • Ensure constraint template is properly defined and matches policy expectations

Issue: Policy Tests Failing

Solution:

  • Run tests with verbose output: opa test . --verbose
  • Check test input data matches expected format
  • Verify policy package names match between policy and test files
  • Use print() statements in Rego for debugging

Issue: Performance Degradation with Large Policy Sets

Solution:

  • Use policy bundles: opa build policies/ -o bundle.tar.gz
  • Enable partial evaluation for complex policies
  • Optimize policy rules to reduce computational complexity
  • Index data for faster lookups using input.key patterns
  • Consider splitting large policy sets into separate evaluation domains

References

同梱ファイル

※ ZIPに含まれるファイル一覧。`SKILL.md` 本体に加え、参考資料・サンプル・スクリプトが入っている場合があります。