> ## Documentation Index
> Fetch the complete documentation index at: https://docs.kubiya.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Authentication

> Configure API authentication and connect to the Kubiya Control Plane

The Kubiya CLI authenticates with the Control Plane using API keys. This guide covers authentication setup, configuration management, and best practices.

## Quick Setup

### Get Your API Key

1. **Via Composer (Web UI)**
   * Navigate to [https://compose.kubiya.ai](https://compose.kubiya.ai)
   * Go to **Settings** → **API Keys**
   * Click **Generate New API Key**
   * Copy your key (it will only be shown once)

2. **Via API**
   ```bash theme={null}
   curl -X POST https://control-plane.kubiya.ai/api/v1/auth/keys \
     -H "Authorization: Bearer $EXISTING_TOKEN" \
     -d '{"name": "cli-key", "ttl": "365d"}'
   ```

### Configure the CLI

<Tabs>
  <Tab title="Environment Variable (Recommended)">
    ```bash theme={null}
    # Add to ~/.bashrc, ~/.zshrc, or ~/.profile
    export KUBIYA_API_KEY="kby_your_api_key_here"

    # Reload shell
    source ~/.bashrc
    ```
  </Tab>

  <Tab title="Config File">
    ```bash theme={null}
    # Create config directory
    mkdir -p ~/.kubiya

    # Create config file
    cat > ~/.kubiya/config.yaml <<EOF
    api_key: kby_your_api_key_here
    base_url: https://api.kubiya.ai/api/v1
    control_plane_url: https://control-plane.kubiya.ai
    EOF
    ```
  </Tab>

  <Tab title="Per-Command">
    ```bash theme={null}
    # Pass API key with command
    kubiya --api-key="kby_your_api_key_here" agent list
    ```
  </Tab>
</Tabs>

### Verify Authentication

```bash theme={null}
# Test connection
kubiya agent list

# Check authentication status
kubiya auth status
```

Expected output:

```
✅ Authenticated
Organization: your-org
User: you@company.com
Control Plane: https://control-plane.kubiya.ai
```

## Configuration Options

### Environment Variables

<ParamField path="KUBIYA_API_KEY" type="string" required>
  Your Kubiya API authentication key. Get this from the Composer UI or API.
</ParamField>

<ParamField path="KUBIYA_BASE_URL" type="string" default="https://api.kubiya.ai/api/v1">
  Base URL for Kubiya API endpoints
</ParamField>

<ParamField path="CONTROL_PLANE_URL" type="string" default="https://control-plane.kubiya.ai">
  Control Plane URL for worker registration and management
</ParamField>

<ParamField path="CONTROL_PLANE_GATEWAY_URL" type="string">
  Override for Control Plane URL (takes precedence over CONTROL\_PLANE\_URL)
</ParamField>

<ParamField path="KUBIYA_DEBUG" type="boolean" default="false">
  Enable debug logging for troubleshooting
</ParamField>

<ParamField path="KUBIYA_LOG_LEVEL" type="string" default="INFO">
  Set logging verbosity: DEBUG, INFO, WARN, ERROR
</ParamField>

### Configuration File

Create `~/.kubiya/config.yaml`:

```yaml theme={null}
# Authentication
api_key: kby_your_api_key_here

# Control Plane URLs
base_url: https://api.kubiya.ai/api/v1
control_plane_url: https://control-plane.kubiya.ai

# Optional: Override control plane URL
# control_plane_gateway_url: https://custom-cp.example.com

# Default settings
default_runner: production-runner
default_environment: production

# Debug options
debug: false
log_level: INFO

# Timeouts (in seconds)
timeout:
  api: 30
  workflow: 3600
```

### Priority Order

The CLI resolves configuration in this order (highest to lowest priority):

1. **Command-line flags** (`--api-key`, `--base-url`)
2. **Environment variables** (`KUBIYA_API_KEY`, `CONTROL_PLANE_URL`)
3. **Configuration file** (`~/.kubiya/config.yaml`)
4. **Default values**

Example:

```bash theme={null}
# Environment variable
export KUBIYA_API_KEY="key1"

# Override with command flag
kubiya --api-key="key2" agent list  # Uses "key2"
```

## Control Plane Connection

### Understanding the Control Plane

The **Control Plane** is the central management and orchestration layer that:

* Manages all platform resources (agents, teams, projects)
* Coordinates workflow execution via Temporal
* Handles worker registration and health monitoring
* Provides event streaming and session persistence
* Enforces policies and access control

```mermaid theme={null}
graph TB
    CLI[💻 CLI]
    CP[🎯 Control Plane]
    Temporal[⚡ Temporal Cloud]
    Worker[🔧 Workers]

    CLI -->|API Calls| CP
    CLI -->|Worker Commands| Worker
    CP -->|Orchestration| Temporal
    CP <-->|Heartbeat/Events| Worker
    Temporal -->|Task Distribution| Worker

    style CP fill:#4CAF50,color:#fff
    style CLI fill:#2196F3,color:#fff
    style Worker fill:#FF9800,color:#fff
```

### Control Plane Operations

#### Resource Management

```bash theme={null}
# List all agents
kubiya agent list

# Create a new agent
kubiya agent create --name "DevOps Agent" --desc "Handles automation tasks"

# List teams
kubiya team list

# List projects
kubiya project list

# List environments
kubiya environment list
```

#### Worker Registration

```bash theme={null}
# Start a worker (registers with control plane)
kubiya worker start --queue-id=my-queue --type=local

# Worker automatically:
# 1. Registers with control plane
# 2. Receives Temporal credentials
# 3. Starts polling for tasks
# 4. Sends health heartbeats
```

#### Workflow Execution

```bash theme={null}
# Execute workflow (control plane orchestrates)
kubiya workflow execute myorg/deployment.yaml

# Control plane:
# 1. Validates permissions
# 2. Creates Temporal workflow
# 3. Distributes to workers
# 4. Tracks execution
```

### Custom Control Plane

For on-premise or custom deployments:

```bash theme={null}
# Set custom control plane URL
export CONTROL_PLANE_GATEWAY_URL="https://control-plane.company.internal"

# Verify connection
kubiya auth status

# Start worker with custom control plane
kubiya worker start --queue-id=internal-queue --type=local
```

## Multi-Environment Configuration

### Using Environment-Specific Keys

<Tabs>
  <Tab title="Development">
    ```bash theme={null}
    # ~/.kubiya/dev.env
    export KUBIYA_API_KEY="kby_dev_key"
    export KUBIYA_BASE_URL="https://dev-api.kubiya.ai/api/v1"
    export CONTROL_PLANE_URL="https://dev-control-plane.kubiya.ai"
    export KUBIYA_DEBUG=true

    # Load with:
    source ~/.kubiya/dev.env
    ```
  </Tab>

  <Tab title="Staging">
    ```bash theme={null}
    # ~/.kubiya/staging.env
    export KUBIYA_API_KEY="kby_staging_key"
    export KUBIYA_BASE_URL="https://staging-api.kubiya.ai/api/v1"
    export CONTROL_PLANE_URL="https://staging-control-plane.kubiya.ai"
    export KUBIYA_LOG_LEVEL="INFO"

    # Load with:
    source ~/.kubiya/staging.env
    ```
  </Tab>

  <Tab title="Production">
    ```bash theme={null}
    # ~/.kubiya/prod.env
    export KUBIYA_API_KEY="kby_prod_key"
    export KUBIYA_BASE_URL="https://api.kubiya.ai/api/v1"
    export CONTROL_PLANE_URL="https://control-plane.kubiya.ai"
    export KUBIYA_LOG_LEVEL="WARN"

    # Load with:
    source ~/.kubiya/prod.env
    ```
  </Tab>
</Tabs>

### Environment Switcher Script

Create `~/.kubiya/switch-env.sh`:

```bash theme={null}
#!/bin/bash

ENV=$1

if [ -z "$ENV" ]; then
  echo "Usage: switch-env.sh [dev|staging|prod]"
  exit 1
fi

ENV_FILE="$HOME/.kubiya/${ENV}.env"

if [ ! -f "$ENV_FILE" ]; then
  echo "Environment file not found: $ENV_FILE"
  exit 1
fi

source "$ENV_FILE"
echo "✅ Switched to $ENV environment"
kubiya auth status
```

Usage:

```bash theme={null}
chmod +x ~/.kubiya/switch-env.sh
~/.kubiya/switch-env.sh dev
```

## Security Best Practices

### API Key Management

<Warning>
  Never commit API keys to version control or share them in plain text.
</Warning>

**Do:**

* ✅ Store keys in environment variables
* ✅ Use secrets management tools (Vault, AWS Secrets Manager)
* ✅ Rotate keys regularly
* ✅ Use short-lived keys for CI/CD
* ✅ Restrict key permissions to minimum required

**Don't:**

* ❌ Commit keys to Git repositories
* ❌ Share keys via email or chat
* ❌ Use the same key across environments
* ❌ Store keys in application code
* ❌ Use overly permissive keys

### Key Rotation

```bash theme={null}
# Generate new key (via Composer or API)
NEW_KEY="kby_new_key_here"

# Update environment
export KUBIYA_API_KEY="$NEW_KEY"

# Update config file
sed -i "s/api_key:.*/api_key: $NEW_KEY/" ~/.kubiya/config.yaml

# Test new key
kubiya auth status

# Revoke old key via Composer
```

### CI/CD Integration

Store keys as secrets in your CI/CD platform:

<Tabs>
  <Tab title="GitHub Actions">
    ```yaml theme={null}
    jobs:
      deploy:
        runs-on: ubuntu-latest
        steps:
          - name: Run Kubiya Command
            env:
              KUBIYA_API_KEY: ${{ secrets.KUBIYA_API_KEY }}
            run: |
              kubiya workflow execute deployment.yaml
    ```
  </Tab>

  <Tab title="GitLab CI">
    ```yaml theme={null}
    deploy:
      script:
        - kubiya workflow execute deployment.yaml
      variables:
        KUBIYA_API_KEY: $KUBIYA_API_KEY
    ```
  </Tab>

  <Tab title="Jenkins">
    ```groovy theme={null}
    pipeline {
      agent any
      environment {
        KUBIYA_API_KEY = credentials('kubiya-api-key')
      }
      stages {
        stage('Deploy') {
          steps {
            sh 'kubiya workflow execute deployment.yaml'
          }
        }
      }
    }
    ```
  </Tab>
</Tabs>

### Network Security

For restricted environments:

```bash theme={null}
# Whitelist these endpoints in your firewall
# - https://control-plane.kubiya.ai (Control Plane API)
# - https://api.kubiya.ai (Platform API)
# - Temporal Cloud endpoints (provided during worker setup)

# Test connectivity
curl -I https://control-plane.kubiya.ai/health
curl -I https://api.kubiya.ai/health
```

## Troubleshooting

### Authentication Failed

```bash theme={null}
# Check if API key is set
echo $KUBIYA_API_KEY

# Verify key format (should start with "kby_")
# Test authentication
kubiya auth status

# Enable debug logging
export KUBIYA_DEBUG=true
kubiya agent list
```

### Connection Refused

```bash theme={null}
# Check control plane URL
echo $CONTROL_PLANE_URL

# Test connectivity
curl -v https://control-plane.kubiya.ai/health

# Check for proxy settings
echo $HTTP_PROXY
echo $HTTPS_PROXY

# Try with custom DNS
ping control-plane.kubiya.ai
```

### SSL Certificate Errors

```bash theme={null}
# Update CA certificates
# Ubuntu/Debian
sudo apt-get update && sudo apt-get install ca-certificates

# macOS
brew install ca-certificates

# Verify certificates
openssl s_client -connect control-plane.kubiya.ai:443
```

### Invalid API Key Format

API keys must:

* Start with `kby_`
* Be alphanumeric with underscores
* Have minimum length requirements

```bash theme={null}
# Valid format
KUBIYA_API_KEY="kby_abc123def456..."

# Invalid formats
KUBIYA_API_KEY="abc123"  # Missing prefix
KUBIYA_API_KEY="kby-abc123"  # Wrong separator
```

## Command Reference

```bash theme={null}
# Check authentication status
kubiya auth status

# List available organizations
kubiya org list

# Switch organization (if you have access to multiple)
kubiya org use <org-id>

# Display current configuration
kubiya config show

# Validate configuration
kubiya config validate
```

## Next Steps

<CardGroup cols={2}>
  <Card title="Worker Management" icon="server" href="/cli/workers">
    Deploy and manage workers on your infrastructure
  </Card>

  <Card title="Control Plane Resources" icon="cube" href="/cli/core-resources">
    Learn to manage agents, teams, and other resources
  </Card>

  <Card title="Workflow Execution" icon="diagram-project" href="/cli/workflows">
    Execute automated workflows via the control plane
  </Card>

  <Card title="Environment Variables" icon="gear" href="/cli/environment-variables">
    Complete reference of all configuration options
  </Card>
</CardGroup>
