# Skill: kubernetes

## Metadata

| Field | Value |
|-------|-------|
| **Name** | `kubernetes` |
| **Version** | `1.0.0` |
| **Package** | `oclawma-skill-kubernetes` |
| **Category** | `infrastructure` |
| **Author** | `OpenClaw Team` |
| **License** | `MIT` |
| **Python** | `>=3.9` |

## Description

Official Kubernetes skill for OCLAWMA providing comprehensive cluster management capabilities. This skill wraps kubectl and Helm commands into safe, easy-to-use tools with proper error handling and output formatting.

### Features

- **kubectl wrapper** - Execute any kubectl command with namespace and context support
- **Pod management** - List, describe, and get logs from pods
- **Deployment management** - Scale deployments, manage rollouts
- **Helm support** - Full Helm lifecycle (install, upgrade, uninstall, list)
- **Context switching** - Multi-cluster support
- **Resource metrics** - Pod and node resource usage (top)
- **Event monitoring** - Watch cluster events

## Installation

```bash
pip install oclawma-skill-kubernetes
```

Or install from source:

```bash
git clone https://github.com/openclaw/oclawma-skill-kubernetes.git
cd oclawma-skill-kubernetes
pip install -e .
```

### Prerequisites

- **kubectl** - Installed and configured (`kubectl version` should work)
- **Helm** (optional) - For Helm chart management (`helm version`)
- Valid **kubeconfig** - Default: `~/.kube/config` or `KUBECONFIG` env var

## Configuration

### Environment Variables

| Variable | Default | Description |
|----------|---------|-------------|
| `KUBECONFIG` | `~/.kube/config` | Path to kubeconfig file |
| `KUBECTL_NAMESPACE` | `default` | Default namespace for operations |
| `KUBECTL_CONTEXT` | (current context) | Default context to use |

### Example Setup

```bash
# Set default namespace for all operations
export KUBECTL_NAMESPACE=production

# Use specific kubeconfig
export KUBECONFIG=/path/to/config

# Set default context
export KUBECTL_CONTEXT=my-cluster
```

## Tools

### kubectl Wrapper

#### `kubectl`

Execute arbitrary kubectl commands with automatic namespace and context handling.

**Parameters:**

| Name | Type | Required | Default | Description |
|------|------|----------|---------|-------------|
| `command` | `string` | Yes | - | kubectl command arguments |
| `namespace` | `string` | No | - | Kubernetes namespace |
| `context` | `string` | No | - | Kubernetes context |
| `timeout` | `integer` | No | 60 | Timeout in seconds |

**Example:**
```python
# Get nodes
result = await registry.execute_tool(
    "kubernetes", "kubectl",
    command="get nodes -o wide"
)

# Get services in specific namespace
result = await registry.execute_tool(
    "kubernetes", "kubectl",
    command="get services",
    namespace="kube-system"
)
```

### Pod Management

#### `get_pods`

List pods with filtering options.

**Parameters:**

| Name | Type | Required | Default | Description |
|------|------|----------|---------|-------------|
| `namespace` | `string` | No | all | Namespace to list from |
| `selector` | `string` | No | - | Label selector (e.g., `app=nginx`) |
| `all_namespaces` | `boolean` | No | false | List from all namespaces |
| `output` | `string` | No | json | Output format (json, yaml, wide, name) |

**Example:**
```python
# Get all pods in default namespace
result = await registry.execute_tool("kubernetes", "get_pods")

# Get pods with label selector
result = await registry.execute_tool(
    "kubernetes", "get_pods",
    selector="app=web",
    output="wide"
)
```

#### `get_logs`

Retrieve pod logs with filtering options.

**Parameters:**

| Name | Type | Required | Default | Description |
|------|------|----------|---------|-------------|
| `pod` | `string` | Yes | - | Pod name or selector |
| `namespace` | `string` | No | default | Pod namespace |
| `container` | `string` | No | - | Container name (multi-container pods) |
| `follow` | `boolean` | No | false | Stream logs (blocks) |
| `tail` | `integer` | No | 100 | Lines from end |
| `previous` | `boolean` | No | false | Previous container instance |
| `timestamps` | `boolean` | No | true | Include timestamps |

**Example:**
```python
# Get last 50 lines of logs
result = await registry.execute_tool(
    "kubernetes", "get_logs",
    pod="my-app-xxx",
    tail=50
)

# Get logs from specific container
result = await registry.execute_tool(
    "kubernetes", "get_logs",
    pod="multi-container-pod",
    container="sidecar"
)
```

#### `describe_pod`

Get detailed pod information including events.

**Parameters:**

| Name | Type | Required | Default | Description |
|------|------|----------|---------|-------------|
| `pod` | `string` | Yes | - | Pod name |
| `namespace` | `string` | No | default | Pod namespace |
| `events` | `boolean` | No | true | Include recent events |

**Example:**
```python
result = await registry.execute_tool(
    "kubernetes", "describe_pod",
    pod="failing-pod",
    namespace="production"
)
```

#### `exec_command`

Execute a command inside a pod container.

**Parameters:**

| Name | Type | Required | Default | Description |
|------|------|----------|---------|-------------|
| `pod` | `string` | Yes | - | Pod name |
| `command` | `string` | Yes | - | Command to execute |
| `namespace` | `string` | No | default | Pod namespace |
| `container` | `string` | No | - | Container name |

**Example:**
```python
# Run command in pod
result = await registry.execute_tool(
    "kubernetes", "exec_command",
    pod="my-app-xxx",
    command="ls -la /app"
)

# Get environment variables
result = await registry.execute_tool(
    "kubernetes", "exec_command",
    pod="my-app-xxx",
    command="env | grep DATABASE"
)
```

### Deployment Management

#### `get_deployments`

List deployments.

**Parameters:**

| Name | Type | Required | Default | Description |
|------|------|----------|---------|-------------|
| `namespace` | `string` | No | - | Namespace |
| `all_namespaces` | `boolean` | No | false | All namespaces |
| `selector` | `string` | No | - | Label selector |
| `output` | `string` | No | json | Output format |

#### `scale_deployment`

Scale a deployment to specified number of replicas.

**Parameters:**

| Name | Type | Required | Default | Description |
|------|------|----------|---------|-------------|
| `name` | `string` | Yes | - | Deployment name |
| `replicas` | `integer` | Yes | - | Number of replicas |
| `namespace` | `string` | No | default | Namespace |
| `wait` | `boolean` | No | false | Wait for rollout to complete |

**Example:**
```python
# Scale to 5 replicas
result = await registry.execute_tool(
    "kubernetes", "scale_deployment",
    name="web-app",
    replicas=5,
    wait=True
)
```

#### `rollout_deployment`

Manage deployment rollouts (status, history, pause, resume, restart, undo).

**Parameters:**

| Name | Type | Required | Default | Description |
|------|------|----------|---------|-------------|
| `name` | `string` | Yes | - | Deployment name |
| `action` | `string` | Yes | - | status/history/pause/resume/restart/undo |
| `namespace` | `string` | No | default | Namespace |
| `revision` | `integer` | No | - | Revision for undo |

**Example:**
```python
# Check rollout status
result = await registry.execute_tool(
    "kubernetes", "rollout_deployment",
    name="web-app",
    action="status"
)

# Restart deployment
result = await registry.execute_tool(
    "kubernetes", "rollout_deployment",
    name="web-app",
    action="restart"
)

# Rollback to previous version
result = await registry.execute_tool(
    "kubernetes", "rollout_deployment",
    name="web-app",
    action="undo"
)
```

### Resource Management

#### `apply_manifest`

Apply a Kubernetes YAML manifest.

**Parameters:**

| Name | Type | Required | Default | Description |
|------|------|----------|---------|-------------|
| `manifest` | `string` | Yes | - | YAML content or file path |
| `namespace` | `string` | No | - | Target namespace |
| `dry_run` | `string` | No | - | Dry run mode (client/server) |

**Example:**
```python
# Apply from file
result = await registry.execute_tool(
    "kubernetes", "apply_manifest",
    manifest="/path/to/deployment.yaml"
)

# Apply YAML content directly
yaml_content = """
apiVersion: v1
kind: ConfigMap
metadata:
  name: my-config
data:
  key: value
"""
result = await registry.execute_tool(
    "kubernetes", "apply_manifest",
    manifest=yaml_content
)
```

#### `delete_resource`

Delete a Kubernetes resource.

**Parameters:**

| Name | Type | Required | Default | Description |
|------|------|----------|---------|-------------|
| `kind` | `string` | Yes | - | Resource kind (pod, deployment, etc.) |
| `name` | `string` | Yes | - | Resource name |
| `namespace` | `string` | No | default | Namespace |
| `force` | `boolean` | No | false | Force delete |

### Helm Support

#### `helm_list`

List Helm releases.

**Parameters:**

| Name | Type | Required | Default | Description |
|------|------|----------|---------|-------------|
| `namespace` | `string` | No | - | Filter by namespace |
| `all_namespaces` | `boolean` | No | false | All namespaces |
| `filter` | `string` | No | - | Filter by name |
| `output` | `string` | No | json | Output format |

#### `helm_install`

Install a Helm chart.

**Parameters:**

| Name | Type | Required | Default | Description |
|------|------|----------|---------|-------------|
| `name` | `string` | Yes | - | Release name |
| `chart` | `string` | Yes | - | Chart reference |
| `namespace` | `string` | No | default | Target namespace |
| `version` | `string` | No | - | Chart version |
| `values` | `object` | No | - | Values to override |
| `values_file` | `string` | No | - | Path to values.yaml |
| `create_namespace` | `boolean` | No | false | Create namespace |
| `dry_run` | `boolean` | No | false | Simulate installation |
| `wait` | `boolean` | No | false | Wait for readiness |

**Example:**
```python
# Install from Helm repository
result = await registry.execute_tool(
    "kubernetes", "helm_install",
    name="nginx",
    chart="oci://registry-1.docker.io/bitnamicharts/nginx",
    namespace="web",
    create_namespace=True,
    wait=True
)

# Install with custom values
result = await registry.execute_tool(
    "kubernetes", "helm_install",
    name="myapp",
    chart="./charts/myapp",
    values={
        "replicaCount": 3,
        "service.type": "LoadBalancer"
    }
)
```

#### `helm_upgrade`

Upgrade a Helm release.

**Parameters:**

| Name | Type | Required | Default | Description |
|------|------|----------|---------|-------------|
| `name` | `string` | Yes | - | Release name |
| `chart` | `string` | Yes | - | Chart reference |
| `namespace` | `string` | No | default | Namespace |
| `version` | `string` | No | - | Chart version |
| `values` | `object` | No | - | Values to override |
| `values_file` | `string` | No | - | Path to values.yaml |
| `install` | `boolean` | No | false | Install if not exists |
| `dry_run` | `boolean` | No | false | Simulate upgrade |
| `wait` | `boolean` | No | false | Wait for readiness |

#### `helm_uninstall`

Uninstall a Helm release.

**Parameters:**

| Name | Type | Required | Default | Description |
|------|------|----------|---------|-------------|
| `name` | `string` | Yes | - | Release name |
| `namespace` | `string` | No | default | Namespace |
| `keep_history` | `boolean` | No | false | Keep release history |
| `wait` | `boolean` | No | false | Wait for deletion |

#### `helm_status`

Get Helm release status.

**Parameters:**

| Name | Type | Required | Default | Description |
|------|------|----------|---------|-------------|
| `name` | `string` | Yes | - | Release name |
| `namespace` | `string` | No | default | Namespace |
| `revision` | `integer` | No | - | Specific revision |
| `show_resources` | `boolean` | No | false | Show created resources |

#### `helm_get_values`

Get Helm release values.

**Parameters:**

| Name | Type | Required | Default | Description |
|------|------|----------|---------|-------------|
| `name` | `string` | Yes | - | Release name |
| `namespace` | `string` | No | default | Namespace |
| `all` | `boolean` | No | false | Show all computed values |

### Context Management

#### `get_contexts`

List available Kubernetes contexts.

**Parameters:**

| Name | Type | Required | Default | Description |
|------|------|----------|---------|-------------|
| `current` | `boolean` | No | false | Show only current context |

**Example:**
```python
# List all contexts
result = await registry.execute_tool("kubernetes", "get_contexts")

# Show current context
result = await registry.execute_tool(
    "kubernetes", "get_contexts",
    current=True
)
```

#### `set_context`

Switch to a different Kubernetes context.

**Parameters:**

| Name | Type | Required | Default | Description |
|------|------|----------|---------|-------------|
| `context` | `string` | Yes | - | Context name |

### Monitoring

#### `get_events`

Get cluster events.

**Parameters:**

| Name | Type | Required | Default | Description |
|------|------|----------|---------|-------------|
| `namespace` | `string` | No | - | Filter by namespace |
| `all_namespaces` | `boolean` | No | false | All namespaces |
| `field_selector` | `string` | No | - | Field selector |
| `sort_by` | `string` | No | .lastTimestamp | Sort field |
| `limit` | `integer` | No | 50 | Max events to return |

**Example:**
```python
# Get recent warning events
result = await registry.execute_tool(
    "kubernetes", "get_events",
    field_selector="type=Warning",
    limit=20
)
```

#### `top_pods`

Show pod resource usage (CPU/memory).

**Parameters:**

| Name | Type | Required | Default | Description |
|------|------|----------|---------|-------------|
| `namespace` | `string` | No | - | Filter by namespace |
| `all_namespaces` | `boolean` | No | false | All namespaces |
| `selector` | `string` | No | - | Label selector |
| `containers` | `boolean` | No | false | Container-level metrics |

#### `top_nodes`

Show node resource usage.

**Parameters:**

| Name | Type | Required | Default | Description |
|------|------|----------|---------|-------------|
| `selector` | `string` | No | - | Label selector |

### Utilities

#### `port_forward`

Forward local port to a pod or service.

**Parameters:**

| Name | Type | Required | Default | Description |
|------|------|----------|---------|-------------|
| `resource` | `string` | Yes | - | Resource (pod/name or svc/name) |
| `local_port` | `integer` | Yes | - | Local port number |
| `remote_port` | `integer` | Yes | - | Remote port number |
| `namespace` | `string` | No | default | Namespace |
| `background` | `boolean` | No | false | Run in background |

**Example:**
```python
# Forward to pod
result = await registry.execute_tool(
    "kubernetes", "port_forward",
    resource="pod/my-app-xxx",
    local_port=8080,
    remote_port=80,
    background=True
)

# Forward to service
result = await registry.execute_tool(
    "kubernetes", "port_forward",
    resource="svc/my-service",
    local_port=5432,
    remote_port=5432
)
```

## Error Handling

All tools return a standardized result dictionary:

```python
{
    "success": bool,           # True if operation succeeded
    "output": str,             # Command output on success
    "error": str | None,       # Error message on failure
    "exit_code": int | None,   # Process exit code
    "truncated": bool          # True if output was truncated
}
```

### Common Errors

- **kubectl not found** - Install kubectl and ensure it's in PATH
- **Helm not found** - Install Helm for Helm operations (optional)
- **Connection refused** - Check kubeconfig and cluster connectivity
- **Not authorized** - Verify RBAC permissions
- **Resource not found** - Check namespace and resource name

## Dependencies

- `oclawma>=0.1.0` - Core OCLAWMA framework
- `pyyaml>=6.0` - YAML parsing for manifests

## Testing

```bash
# Run test suite
pytest tests/ -v

# Test with specific kubeconfig
KUBECONFIG=/path/to/test-config pytest tests/
```

## Development

```bash
# Clone repository
git clone https://github.com/openclaw/oclawma-skill-kubernetes.git
cd oclawma-skill-kubernetes

# Create virtual environment
python -m venv venv
source venv/bin/activate

# Install in development mode
pip install -e ".[dev]"

# Run tests
pytest

# Run linting
black src tests
ruff check src tests
mypy src
```

## License

MIT License - see LICENSE file for details.

## Contributing

Contributions are welcome! Please:
1. Fork the repository
2. Create a feature branch
3. Make your changes
4. Add tests
5. Submit a pull request
