Back to skills
SkillHub ClubRun DevOpsFull StackDevOpsSecurity

k8s-security

Audit Kubernetes RBAC, enforce policies, and manage secrets. Use for security reviews, permission audits, policy enforcement with Kyverno/Gatekeeper, and secret management.

Packaged view

This page reorganizes the original catalog entry around fit, installability, and workflow context first. The original raw source lives below.

Stars
847
Hot score
99
Updated
March 20, 2026
Overall rating
C4.4
Composite score
4.4
Best-practice grade
B77.6

Install command

npx @skill-hub/cli install rohitg00-kubectl-mcp-server-k8s-security

Repository

rohitg00/kubectl-mcp-server

Skill path: kubernetes-skills/claude/k8s-security

Audit Kubernetes RBAC, enforce policies, and manage secrets. Use for security reviews, permission audits, policy enforcement with Kyverno/Gatekeeper, and secret management.

Open repository

Best for

Primary workflow: Run DevOps.

Technical facets: Full Stack, DevOps, Security.

Target audience: everyone.

License: Apache-2.0.

Original source

Catalog source: SkillHub Club.

Repository owner: rohitg00.

This is still a mirrored public skill entry. Review the repository before installing into production workflows.

What it helps with

  • Install k8s-security into Claude Code, Codex CLI, Gemini CLI, or OpenCode workflows
  • Review https://github.com/rohitg00/kubectl-mcp-server before adding k8s-security to shared team environments
  • Use k8s-security for development workflows

Works across

Claude CodeCodex CLIGemini CLIOpenCode

Favorites: 0.

Sub-skills: 0.

Aggregator: No.

Original source / Raw SKILL.md

---
name: k8s-security
description: Audit Kubernetes RBAC, enforce policies, and manage secrets. Use for security reviews, permission audits, policy enforcement with Kyverno/Gatekeeper, and secret management.
license: Apache-2.0
metadata:
  author: rohitg00
  version: "1.0.0"
  tools: 10
  category: security
---

# Kubernetes Security

Security auditing, RBAC management, and policy enforcement using kubectl-mcp-server tools.

## When to Apply

Use this skill when:
- User mentions: "security", "RBAC", "permissions", "policy", "audit", "secrets"
- Operations: security review, permission check, policy enforcement
- Keywords: "who can", "access control", "compliance", "vulnerable"

## Priority Rules

| Priority | Rule | Impact | Tools |
|----------|------|--------|-------|
| 1 | Check cluster-admin bindings first | CRITICAL | `get_cluster_role_bindings` |
| 2 | Audit secrets access permissions | CRITICAL | Review role rules |
| 3 | Verify network isolation | HIGH | `get_network_policies` |
| 4 | Check policy compliance | HIGH | `kyverno_*`, `gatekeeper_*` |
| 5 | Review pod security contexts | MEDIUM | `describe_pod` |

## Quick Reference

| Task | Tool | Example |
|------|------|---------|
| List roles | `get_roles` | `get_roles(namespace)` |
| Cluster roles | `get_cluster_roles` | `get_cluster_roles()` |
| Role bindings | `get_role_bindings` | `get_role_bindings(namespace)` |
| Service accounts | `get_service_accounts` | `get_service_accounts(namespace)` |
| Kyverno policies | `kyverno_clusterpolicies_list_tool` | `kyverno_clusterpolicies_list_tool()` |

## RBAC Auditing

### List Roles and Bindings

```python
get_roles(namespace)
get_cluster_roles()
get_role_bindings(namespace)
get_cluster_role_bindings()
```

### Check Service Account Permissions

```python
get_service_accounts(namespace)
```

### Common RBAC Patterns

| Pattern | Risk Level | Check |
|---------|-----------|-------|
| cluster-admin binding | Critical | `get_cluster_role_bindings()` |
| Wildcard verbs (*) | High | Review role rules |
| secrets access | High | Check get/list on secrets |
| pod/exec | High | Allows container access |

See [RBAC-PATTERNS.md](RBAC-PATTERNS.md) for detailed patterns and remediation.

## Policy Enforcement

### Kyverno Policies

```python
kyverno_policies_list_tool(namespace)
kyverno_clusterpolicies_list_tool()
kyverno_policy_get_tool(name, namespace)
```

### OPA Gatekeeper

```python
gatekeeper_constraints_list_tool()
gatekeeper_constraint_get_tool(kind, name)
gatekeeper_templates_list_tool()
```

### Common Policies to Enforce

| Policy | Purpose |
|--------|---------|
| Disallow privileged | Prevent root containers |
| Require resource limits | Prevent resource exhaustion |
| Restrict host namespaces | Isolate from node |
| Require labels | Ensure metadata |
| Allowed registries | Control image sources |

## Secret Management

### List Secrets

```python
get_secrets(namespace)
```

### Secret Best Practices

1. Use external secret managers (Vault, AWS SM)
2. Encrypt secrets at rest (EncryptionConfiguration)
3. Limit secret access via RBAC
4. Rotate secrets regularly

## Network Policies

### List Policies

```python
get_network_policies(namespace)
```

### Cilium Network Policies

```python
cilium_policies_list_tool(namespace)
cilium_policy_get_tool(name, namespace)
```

### Default Deny Template

```yaml
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: default-deny-all
spec:
  podSelector: {}
  policyTypes:
  - Ingress
  - Egress
```

## Security Scanning Workflow

1. **RBAC Audit**
   ```python
   get_cluster_role_bindings()
   get_roles(namespace)
   ```

2. **Policy Compliance**
   ```python
   kyverno_clusterpolicies_list_tool()
   gatekeeper_constraints_list_tool()
   ```

3. **Network Isolation**
   ```python
   get_network_policies(namespace)
   cilium_endpoints_list_tool(namespace)
   ```

4. **Pod Security**
   ```python
   get_pods(namespace)
   describe_pod(name, namespace)
   ```

## Multi-Cluster Security

Audit across clusters:

```python
get_cluster_role_bindings(context="production")
get_cluster_role_bindings(context="staging")
```

## Automated Audit Script

For comprehensive security audit, see [scripts/audit-rbac.py](scripts/audit-rbac.py).

## Related Tools

- RBAC: `get_roles`, `get_cluster_roles`, `get_role_bindings`
- Policy: `kyverno_*`, `gatekeeper_*`
- Network: `get_network_policies`, `cilium_policies_*`
- Istio: `istio_authorizationpolicies_list_tool`, `istio_peerauthentications_list_tool`

## Related Skills

- [k8s-policy](../k8s-policy/SKILL.md) - Policy management
- [k8s-cilium](../k8s-cilium/SKILL.md) - Cilium network security


---

## Referenced Files

> The following files are referenced in this skill and included for context.

### RBAC-PATTERNS.md

```markdown
# RBAC Patterns and Anti-Patterns

Security patterns for Kubernetes RBAC configuration.

## Dangerous Patterns (Anti-Patterns)

### 1. Cluster-Admin for Everyone

```yaml
# DANGEROUS: Gives full cluster access
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  name: admin-everyone
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: cluster-admin
subjects:
- kind: Group
  name: system:authenticated
```

**Detection:**
```
get_cluster_role_bindings()
# Look for cluster-admin bindings to groups/users
```

### 2. Wildcard Verbs

```yaml
# DANGEROUS: Allows all actions
rules:
- apiGroups: ["*"]
  resources: ["*"]
  verbs: ["*"]
```

**Detection:**
```
get_cluster_roles()
get_roles(namespace)
# Check for * in verbs
```

### 3. Secrets Access

```yaml
# RISKY: Can read all secrets
rules:
- apiGroups: [""]
  resources: ["secrets"]
  verbs: ["get", "list"]
```

**Detection:**
```
get_cluster_roles()
# Check for secrets access
```

### 4. Pod Exec Access

```yaml
# RISKY: Can execute in containers
rules:
- apiGroups: [""]
  resources: ["pods/exec"]
  verbs: ["create"]
```

## Secure Patterns

### 1. Read-Only Viewer

```yaml
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  name: namespace-viewer
rules:
- apiGroups: ["", "apps", "batch"]
  resources: ["pods", "deployments", "jobs", "services"]
  verbs: ["get", "list", "watch"]
```

### 2. Developer Role

```yaml
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  name: developer
rules:
# Read most resources
- apiGroups: ["", "apps"]
  resources: ["pods", "deployments", "services", "configmaps"]
  verbs: ["get", "list", "watch"]
# Manage deployments
- apiGroups: ["apps"]
  resources: ["deployments"]
  verbs: ["create", "update", "patch", "delete"]
# Read logs
- apiGroups: [""]
  resources: ["pods/log"]
  verbs: ["get"]
# Port-forward for debugging
- apiGroups: [""]
  resources: ["pods/portforward"]
  verbs: ["create"]
```

### 3. CI/CD Service Account

```yaml
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  name: ci-deployer
rules:
- apiGroups: ["apps"]
  resources: ["deployments"]
  verbs: ["get", "list", "update", "patch"]
- apiGroups: [""]
  resources: ["configmaps", "secrets"]
  verbs: ["get", "create", "update"]
  resourceNames: ["app-config", "app-secrets"]  # Specific resources only
```

### 4. Namespace Admin (Not Cluster)

```yaml
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: namespace-admin
  namespace: my-namespace
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: admin  # Built-in admin (not cluster-admin)
subjects:
- kind: User
  name: team-lead
```

## Audit Checklist

### Using MCP Tools

```python
# 1. Check cluster-admin bindings
get_cluster_role_bindings()
# Flag: Any non-system bindings to cluster-admin

# 2. Review cluster roles
get_cluster_roles()
# Flag: Custom roles with wildcard access

# 3. Check namespace roles
for ns in namespaces:
    get_roles(namespace=ns)
    get_role_bindings(namespace=ns)
# Flag: Overly permissive custom roles

# 4. Review service accounts
get_service_accounts(namespace)
# Flag: Default SA used by workloads
```

### What to Look For

| Finding | Risk | Remediation |
|---------|------|-------------|
| cluster-admin to users | Critical | Create scoped roles |
| * verbs | High | Specify exact verbs |
| secrets access | High | Limit to specific secrets |
| pods/exec | Medium | Restrict to specific namespaces |
| Default SA with roles | Medium | Create dedicated SAs |

## Best Practices

1. **Principle of Least Privilege**
   - Only grant what's needed
   - Use namespace roles, not cluster roles

2. **Dedicated Service Accounts**
   - Don't use default SA
   - One SA per workload type

3. **Resource Names**
   - Limit to specific resources when possible
   - `resourceNames: ["specific-secret"]`

4. **Audit Regularly**
   - Review bindings monthly
   - Check for orphaned roles

5. **Namespace Isolation**
   - Different teams = different namespaces
   - RoleBindings per namespace

```

### scripts/audit-rbac.py

```python
#!/usr/bin/env python3
"""
RBAC Audit Script
Analyzes RBAC configuration for security issues.

Usage within Claude Code:
    This script is called by the k8s-security skill to audit
    RBAC configuration and find potential security issues.
"""

import json
import sys
from typing import Any


def audit_rbac(context: str = "") -> dict[str, Any]:
    """
    Audit RBAC configuration for security issues.

    Args:
        context: Optional kubeconfig context

    Returns:
        Dictionary with audit findings
    """
    audit = {
        "context": context or "current",
        "critical": [],
        "high": [],
        "medium": [],
        "low": [],
        "checks_to_run": []
    }

    # Define checks to run with MCP tools
    audit["checks_to_run"] = [
        {
            "name": "cluster_admin_bindings",
            "tool": "get_cluster_role_bindings",
            "severity": "critical",
            "description": "Check for non-system cluster-admin bindings",
            "look_for": "roleRef.name == 'cluster-admin' AND subject not in system:*"
        },
        {
            "name": "wildcard_roles",
            "tool": "get_cluster_roles",
            "severity": "high",
            "description": "Check for roles with wildcard permissions",
            "look_for": "rules with '*' in verbs, resources, or apiGroups"
        },
        {
            "name": "secrets_access",
            "tool": "get_cluster_roles",
            "severity": "high",
            "description": "Check for roles with secrets access",
            "look_for": "rules with resources=['secrets'] and verbs=['get','list']"
        },
        {
            "name": "pod_exec_access",
            "tool": "get_cluster_roles",
            "severity": "medium",
            "description": "Check for roles with pod/exec access",
            "look_for": "rules with resources=['pods/exec'] and verbs=['create']"
        },
        {
            "name": "namespace_admin_bindings",
            "tool": "get_role_bindings",
            "severity": "medium",
            "description": "Check namespace-level admin bindings",
            "params": {"all_namespaces": True}
        }
    ]

    return audit


def analyze_cluster_role_binding(binding: dict) -> dict[str, Any] | None:
    """
    Analyze a ClusterRoleBinding for security issues.

    Args:
        binding: ClusterRoleBinding data

    Returns:
        Finding if issue detected, None otherwise
    """
    role_ref = binding.get("roleRef", {})
    subjects = binding.get("subjects", [])

    # Check for cluster-admin bindings
    if role_ref.get("name") == "cluster-admin":
        non_system_subjects = [
            s for s in subjects
            if not s.get("name", "").startswith("system:")
        ]

        if non_system_subjects:
            return {
                "severity": "critical",
                "type": "cluster_admin_binding",
                "binding": binding.get("metadata", {}).get("name"),
                "subjects": non_system_subjects,
                "recommendation": "Remove cluster-admin binding, create scoped role instead"
            }

    return None


def analyze_cluster_role(role: dict) -> list[dict[str, Any]]:
    """
    Analyze a ClusterRole for security issues.

    Args:
        role: ClusterRole data

    Returns:
        List of findings
    """
    findings = []
    rules = role.get("rules", [])
    role_name = role.get("metadata", {}).get("name", "unknown")

    for rule in rules:
        verbs = rule.get("verbs", [])
        resources = rule.get("resources", [])
        api_groups = rule.get("apiGroups", [])

        # Check for wildcard verbs
        if "*" in verbs:
            findings.append({
                "severity": "high",
                "type": "wildcard_verbs",
                "role": role_name,
                "rule": rule,
                "recommendation": "Specify exact verbs needed"
            })

        # Check for wildcard resources
        if "*" in resources:
            findings.append({
                "severity": "high",
                "type": "wildcard_resources",
                "role": role_name,
                "rule": rule,
                "recommendation": "Specify exact resources needed"
            })

        # Check for secrets access
        if "secrets" in resources and any(v in verbs for v in ["get", "list", "*"]):
            findings.append({
                "severity": "high",
                "type": "secrets_access",
                "role": role_name,
                "rule": rule,
                "recommendation": "Limit secrets access to specific names using resourceNames"
            })

        # Check for pod/exec access
        if "pods/exec" in resources and any(v in verbs for v in ["create", "*"]):
            findings.append({
                "severity": "medium",
                "type": "pod_exec_access",
                "role": role_name,
                "rule": rule,
                "recommendation": "Restrict pod/exec to specific namespaces"
            })

    return findings


def generate_report(findings: list[dict[str, Any]]) -> str:
    """
    Generate human-readable audit report.

    Args:
        findings: List of findings

    Returns:
        Formatted report string
    """
    report = ["# RBAC Security Audit Report\n"]

    by_severity = {
        "critical": [],
        "high": [],
        "medium": [],
        "low": []
    }

    for finding in findings:
        severity = finding.get("severity", "low")
        by_severity[severity].append(finding)

    for severity in ["critical", "high", "medium", "low"]:
        items = by_severity[severity]
        if items:
            report.append(f"\n## {severity.upper()} ({len(items)} findings)\n")
            for item in items:
                report.append(f"- **{item['type']}**: {item.get('role', item.get('binding', 'N/A'))}")
                report.append(f"  - Recommendation: {item['recommendation']}")

    if not any(by_severity.values()):
        report.append("\nNo security issues found.")

    return "\n".join(report)


if __name__ == "__main__":
    context = sys.argv[1] if len(sys.argv) > 1 else ""

    result = audit_rbac(context)
    print(json.dumps(result, indent=2))

```

### ../k8s-policy/SKILL.md

```markdown
---
name: k8s-policy
description: Kubernetes policy management with Kyverno and Gatekeeper. Use when enforcing security policies, validating resources, or auditing policy compliance.
license: Apache-2.0
metadata:
  author: rohitg00
  version: "1.0.0"
  tools: 6
  category: security
---

# Kubernetes Policy Management

Manage policies using kubectl-mcp-server's Kyverno and Gatekeeper tools.

## When to Apply

Use this skill when:
- User mentions: "Kyverno", "Gatekeeper", "OPA", "policy", "compliance"
- Operations: enforcing policies, checking violations, policy audit
- Keywords: "require labels", "block privileged", "validate", "enforce"

## Priority Rules

| Priority | Rule | Impact | Tools |
|----------|------|--------|-------|
| 1 | Detect policy engine first | CRITICAL | `kyverno_detect_tool`, `gatekeeper_detect_tool` |
| 2 | Use Audit mode before Enforce | HIGH | validationFailureAction |
| 3 | Check policy reports for violations | HIGH | `kyverno_clusterpolicyreports_list_tool` |
| 4 | Review constraint templates | MEDIUM | `gatekeeper_constrainttemplates_list_tool` |

## Quick Reference

| Task | Tool | Example |
|------|------|---------|
| List Kyverno cluster policies | `kyverno_clusterpolicies_list_tool` | `kyverno_clusterpolicies_list_tool()` |
| Get Kyverno policy | `kyverno_clusterpolicy_get_tool` | `kyverno_clusterpolicy_get_tool(name)` |
| List Gatekeeper constraints | `gatekeeper_constraints_list_tool` | `gatekeeper_constraints_list_tool()` |
| Get constraint | `gatekeeper_constraint_get_tool` | `gatekeeper_constraint_get_tool(kind, name)` |

## Kyverno

### Detect Installation

```python
kyverno_detect_tool()
```

### List Policies

```python
kyverno_clusterpolicies_list_tool()

kyverno_policies_list_tool(namespace="default")
```

### Get Policy Details

```python
kyverno_clusterpolicy_get_tool(name="require-labels")
kyverno_policy_get_tool(name="require-resources", namespace="default")
```

### Policy Reports

```python
kyverno_clusterpolicyreports_list_tool()

kyverno_policyreports_list_tool(namespace="default")
```

### Common Kyverno Policies

```python
kubectl_apply(manifest="""
apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata:
  name: require-labels
spec:
  validationFailureAction: Enforce
  rules:
  - name: require-app-label
    match:
      resources:
        kinds:
        - Pod
    validate:
      message: "Label 'app' is required"
      pattern:
        metadata:
          labels:
            app: "?*"
""")

kubectl_apply(manifest="""
apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata:
  name: require-limits
spec:
  validationFailureAction: Enforce
  rules:
  - name: require-cpu-memory
    match:
      resources:
        kinds:
        - Pod
    validate:
      message: "CPU and memory limits required"
      pattern:
        spec:
          containers:
          - resources:
              limits:
                cpu: "?*"
                memory: "?*"
""")
```

## Gatekeeper (OPA)

### Detect Installation

```python
gatekeeper_detect_tool()
```

### List Constraints

```python
gatekeeper_constraints_list_tool()

gatekeeper_constrainttemplates_list_tool()
```

### Get Constraint Details

```python
gatekeeper_constraint_get_tool(
    kind="K8sRequiredLabels",
    name="require-app-label"
)

gatekeeper_constrainttemplate_get_tool(name="k8srequiredlabels")
```

### Common Gatekeeper Policies

```python
kubectl_apply(manifest="""
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 labels: %v", [missing])
      }
""")

kubectl_apply(manifest="""
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: K8sRequiredLabels
metadata:
  name: require-app-label
spec:
  match:
    kinds:
    - apiGroups: [""]
      kinds: ["Pod"]
  parameters:
    labels: ["app", "env"]
""")
```

## Policy Audit Workflow

```python
kyverno_detect_tool()
kyverno_clusterpolicies_list_tool()
kyverno_clusterpolicyreports_list_tool()
```

## Prerequisites

- **Kyverno**: Required for Kyverno tools
  ```bash
  kubectl create -f https://github.com/kyverno/kyverno/releases/latest/download/install.yaml
  ```
- **Gatekeeper**: Required for Gatekeeper tools
  ```bash
  kubectl apply -f https://raw.githubusercontent.com/open-policy-agent/gatekeeper/master/deploy/gatekeeper.yaml
  ```

## Related Skills

- [k8s-security](../k8s-security/SKILL.md) - RBAC and security
- [k8s-operations](../k8s-operations/SKILL.md) - Apply policies

```

### ../k8s-cilium/SKILL.md

```markdown
---
name: k8s-cilium
description: Cilium and Hubble network observability for Kubernetes. Use when managing network policies, observing traffic flows, or troubleshooting connectivity with eBPF-based networking.
license: Apache-2.0
metadata:
  author: rohitg00
  version: "1.0.0"
  tools: 8
  category: networking
---

# Cilium & Hubble Network Observability

Manage eBPF-based networking using kubectl-mcp-server's Cilium tools (8 tools).

## When to Apply

Use this skill when:
- User mentions: "Cilium", "Hubble", "eBPF", "network policy", "flow"
- Operations: network policy management, traffic observation, L7 filtering
- Keywords: "network security", "traffic flow", "dropped packets", "connectivity"

## Priority Rules

| Priority | Rule | Impact | Tools |
|----------|------|--------|-------|
| 1 | Detect Cilium installation first | CRITICAL | `cilium_detect_tool` |
| 2 | Check agent status for health | HIGH | `cilium_status_tool` |
| 3 | Use Hubble for flow debugging | HIGH | `hubble_flows_query_tool` |
| 4 | Start with default deny | MEDIUM | CiliumNetworkPolicy |

## Quick Reference

| Task | Tool | Example |
|------|------|---------|
| Detect Cilium | `cilium_detect_tool` | `cilium_detect_tool()` |
| Agent status | `cilium_status_tool` | `cilium_status_tool()` |
| List policies | `cilium_policies_list_tool` | `cilium_policies_list_tool(namespace)` |
| Query flows | `hubble_flows_query_tool` | `hubble_flows_query_tool(namespace)` |

## Check Installation

```python
cilium_detect_tool()
```

## Cilium Status

```python
cilium_status_tool()
```

## Network Policies

### List Policies

```python
cilium_policies_list_tool(namespace="default")
```

### Get Policy Details

```python
cilium_policy_get_tool(name="allow-web", namespace="default")
```

### Create Cilium Network Policy

```python
kubectl_apply(manifest="""
apiVersion: cilium.io/v2
kind: CiliumNetworkPolicy
metadata:
  name: allow-web
  namespace: default
spec:
  endpointSelector:
    matchLabels:
      app: web
  ingress:
  - fromEndpoints:
    - matchLabels:
        app: frontend
    toPorts:
    - ports:
      - port: "80"
        protocol: TCP
  egress:
  - toEndpoints:
    - matchLabels:
        app: database
    toPorts:
    - ports:
      - port: "5432"
        protocol: TCP
""")
```

## Endpoints

```python
cilium_endpoints_list_tool(namespace="default")
```

## Identities

```python
cilium_identities_list_tool()
```

## Nodes

```python
cilium_nodes_list_tool()
```

## Hubble Flow Observability

```python
hubble_flows_query_tool(
    namespace="default",
    pod="my-pod",
    last="5m"
)

hubble_flows_query_tool(
    namespace="default",
    verdict="DROPPED"
)

hubble_flows_query_tool(
    namespace="default",
    type="l7"
)
```

## Create L7 Policy

```python
kubectl_apply(manifest="""
apiVersion: cilium.io/v2
kind: CiliumNetworkPolicy
metadata:
  name: api-policy
  namespace: default
spec:
  endpointSelector:
    matchLabels:
      app: api
  ingress:
  - fromEndpoints:
    - matchLabels:
        app: frontend
    toPorts:
    - ports:
      - port: "8080"
        protocol: TCP
      rules:
        http:
        - method: GET
          path: "/api/v1/.*"
        - method: POST
          path: "/api/v1/users"
""")
```

## Cluster Mesh

```python
kubectl_apply(manifest="""
apiVersion: cilium.io/v2
kind: CiliumClusterwideNetworkPolicy
metadata:
  name: allow-cross-cluster
spec:
  endpointSelector:
    matchLabels:
      app: shared-service
  ingress:
  - fromEntities:
    - cluster
    - remote-node
""")
```

## Troubleshooting Workflows

### Pod Can't Reach Service

```python
cilium_status_tool()
cilium_endpoints_list_tool(namespace)
cilium_policies_list_tool(namespace)
hubble_flows_query_tool(namespace, pod, verdict="DROPPED")
```

### Policy Not Working

```python
cilium_policy_get_tool(name, namespace)
cilium_endpoints_list_tool(namespace)
hubble_flows_query_tool(namespace)
```

### Network Performance Issues

```python
cilium_status_tool()
cilium_nodes_list_tool()
hubble_flows_query_tool(namespace, type="l7")
```

## Best Practices

1. **Start with default deny**: Create baseline deny-all policy
2. **Use labels consistently**: Policies rely on label selectors
3. **Monitor with Hubble**: Observe flows before/after policy changes
4. **Test in staging**: Verify policies don't break connectivity

## Prerequisites

- **Cilium**: Required for all Cilium tools
  ```bash
  cilium install
  ```

## Related Skills

- [k8s-networking](../k8s-networking/SKILL.md) - Standard K8s networking
- [k8s-security](../k8s-security/SKILL.md) - Security policies
- [k8s-service-mesh](../k8s-service-mesh/SKILL.md) - Istio service mesh

```