Secrets Service API Reference

Complete reference documentation for all classes, methods, and exceptions in the Kubiya Secrets service.

Classes

SecretService

Main service class for managing secrets securely.
class SecretService(BaseService):
    """Service for managing secrets"""

Methods

list() -> Union[List[Dict[str, Any]], str]
List all secrets available to the current user/organization. Parameters: None Returns:
  • Union[List[Dict[str, Any]], str]: List of secret metadata dictionaries or formatted string
Example:
try:
    secrets_list = client.secrets.list()
    
    if isinstance(secrets_list, list):
        print(f"Found {len(secrets_list)} secrets:")
        for secret in secrets_list:
            print(f"- {secret['secret_name']}: {secret.get('description', 'No description')}")
    else:
        print(f"Secrets list response: {secrets_list}")
        
except SecretError as e:
    print(f"Failed to list secrets: {e}")
get(name: str) -> Union[Dict[str, Any], str]
Get metadata and details for a specific secret (without the actual value). Parameters:
  • name (str): The name of the secret to retrieve
Returns:
  • Union[Dict[str, Any], str]: Secret metadata dictionary or formatted string
Example:
try:
    secret_info = client.secrets.get("database-password")
    
    if isinstance(secret_info, dict):
        print(f"Secret: {secret_info['name']}")
        print(f"Description: {secret_info.get('description', 'N/A')}")
        print(f"Created: {secret_info.get('created_at', 'Unknown')}")
        print(f"Last updated: {secret_info.get('updated_at', 'Unknown')}")
    else:
        print(f"Secret info: {secret_info}")
        
except SecretError as e:
    print(f"Failed to get secret info: {e}")
value(name: str) -> Union[str, Dict[str, str]]
Get the actual value of a secret. Parameters:
  • name (str): The name of the secret whose value to retrieve
Returns:
  • Union[str, Dict[str, str]]: The secret value as a string, or dictionary with value key
Raises:
  • SecretValidationError: If the secret name is empty or invalid
  • SecretError: If the secret doesn’t exist or cannot be retrieved
Example:
try:
    # Validate secret name first
    if not name or not isinstance(name, str):
        raise SecretValidationError("Secret name must be a non-empty string")
    
    secret_value = client.secrets.value("database-password")
    
    # Never log the actual value!
    print(f"Retrieved secret value (length: {len(secret_value)})")
    
    # Use the secret value in your application
    connection_string = f"postgresql://user:{secret_value}@host/db"
    
except SecretValidationError as e:
    print(f"Invalid secret name: {e}")
    
except SecretError as e:
    print(f"Failed to retrieve secret value: {e}")
    print(f"Secret name: {e.details.get('secret_name') if e.details else 'Unknown'}")
create(name: str, value: Optional[str] = None, description: Optional[str] = None, from_file: Optional[str] = None) -> Dict[str, Any]
Create a new secret with the specified name and value. Parameters:
  • name (str): The name for the new secret
  • value (Optional[str]): The secret value (mutually exclusive with from_file)
  • description (Optional[str]): Optional description for the secret
  • from_file (Optional[str]): Path to file containing the secret value (mutually exclusive with value)
Returns:
  • Dict[str, Any]: Creation response with success confirmation
Raises:
  • SecretValidationError: If validation fails (empty name, both value and from_file provided, or neither provided)
  • SecretError: If file doesn’t exist (when using from_file) or creation fails
Validation Rules:
  • Secret name must be provided and non-empty
  • Either value or from_file must be provided, but not both
  • If from_file is used, the file must exist and be readable
Example:
# Create secret with direct value
try:
    result = client.secrets.create(
        name="api-key",
        value="sk-1234567890abcdef",
        description="External service API key"
    )
    print(f"Secret created: {result['message']}")
    
except SecretValidationError as e:
    print(f"Validation error: {e}")
except SecretError as e:
    print(f"Creation failed: {e}")

# Create secret from file
import tempfile
from pathlib import Path

temp_file = Path(tempfile.mktemp())
try:
    # Write secret to temporary file
    temp_file.write_text("my-secret-database-password")
    
    result = client.secrets.create(
        name="db-password",
        description="Database connection password",
        from_file=str(temp_file)
    )
    print(f"Secret created from file: {result['message']}")
    
except SecretValidationError as e:
    print(f"Validation error: {e}")
except SecretError as e:
    print(f"Creation failed: {e}")
    if "File not found" in str(e):
        print("Check that the file path is correct and the file exists")
finally:
    # Clean up temporary file
    if temp_file.exists():
        temp_file.unlink()
update(name: str, value: Optional[str] = None, description: Optional[str] = None, from_file: Optional[str] = None) -> Dict[str, Any]
Update an existing secret’s value and/or description. Parameters:
  • name (str): The name of the secret to update
  • value (Optional[str]): The new secret value (mutually exclusive with from_file)
  • description (Optional[str]): The new description for the secret
  • from_file (Optional[str]): Path to file containing the new secret value (mutually exclusive with value)
Returns:
  • Dict[str, Any]: Update response with success confirmation
Raises:
  • SecretValidationError: If validation fails (both value and from_file provided, or neither provided)
  • SecretError: If file doesn’t exist (when using from_file), secret doesn’t exist, or update fails
Validation Rules:
  • Either value or from_file must be provided, but not both
  • If from_file is used, the file must exist and be readable
  • The secret must already exist
Example:
# Update secret with new value
try:
    result = client.secrets.update(
        name="api-key",
        value="sk-new-1234567890abcdef",
        description="Updated external service API key"
    )
    print(f"Secret updated: {result}")
    
except SecretValidationError as e:
    print(f"Validation error: {e}")
except SecretError as e:
    print(f"Update failed: {e}")

# Update secret from file
try:
    result = client.secrets.update(
        name="db-password",
        description="Rotated database password",
        from_file="/secure/new-db-password.txt"
    )
    print(f"Secret updated from file: {result}")
    
except SecretValidationError as e:
    print(f"Validation error: {e}")
    if "Cannot use both" in str(e):
        print("Use either 'value' or 'from_file', not both")
except SecretError as e:
    print(f"Update failed: {e}")
    if "File not found" in str(e):
        print("Check that the file path is correct and the file exists")
delete(name: str) -> Dict[str, Any]
Delete a secret permanently. Parameters:
  • name (str): The name of the secret to delete
Returns:
  • Dict[str, Any]: Deletion response with success confirmation
Raises:
  • SecretError: If the secret doesn’t exist or deletion fails
Example:
try:
    result = client.secrets.delete("old-api-key")
    print(f"Secret deleted: {result}")
    
except SecretError as e:
    print(f"Deletion failed: {e}")
    print(f"Secret name: {e.details.get('secret_name') if e.details else 'Unknown'}")
    
    # Handle common deletion scenarios
    if "not found" in str(e).lower():
        print("Secret may have already been deleted")
    elif "permission" in str(e).lower():
        print("Check that you have permission to delete this secret")

Exceptions

SecretError (Base Exception)

Base exception class for all secret-related errors.
class SecretError(KubiyaSDKError):
    """Exception for secret-related errors"""

Constructor

def __init__(self, message: str, secret_name: Optional[str] = None):

Attributes

  • secret_name (Optional[str]): Name of the secret that caused the error (if applicable)
  • details (Optional[Dict[str, Any]]): Additional error context including secret_name

Example

try:
    client.secrets.value("nonexistent-secret")
except SecretError as e:
    print(f"Secret operation failed: {e}")
    
    # Access error details
    if e.details and e.details.get('secret_name'):
        print(f"Failed secret: {e.details['secret_name']}")
    
    # Handle different types of secret errors
    error_message = str(e).lower()
    if "not found" in error_message:
        print("💡 Tip: Check that the secret name is correct")
    elif "permission" in error_message:
        print("💡 Tip: Verify you have access to this secret")
    elif "file not found" in error_message:
        print("💡 Tip: Check that the file path exists and is readable")

SecretValidationError

Specialized exception for secret validation failures.
class SecretValidationError(SecretError):
    """Exception raised when secret validation fails"""

Common Validation Scenarios

Empty Secret Name:
try:
    client.secrets.value("")  # Empty name
except SecretValidationError as e:
    print(f"Validation failed: {e}")
    # Handle: "Secret name is required"
Missing Secret Value:
try:
    client.secrets.create(name="my-secret")  # No value or from_file
except SecretValidationError as e:
    print(f"Validation failed: {e}")
    # Handle: "Secret value must be provided via value or from_file"
Conflicting Parameters:
try:
    client.secrets.create(
        name="my-secret",
        value="direct-value",
        from_file="/path/to/file"  # Both value and from_file provided
    )
except SecretValidationError as e:
    print(f"Validation failed: {e}")
    # Handle: "Cannot use both value and from_file"

Example

def create_secret_safely(name: str, value: str = None, from_file: str = None, description: str = None):
    """Create a secret with comprehensive validation error handling"""
    try:
        # Pre-validate inputs
        if not name or not isinstance(name, str):
            raise SecretValidationError("Secret name must be a non-empty string")
        
        if value and from_file:
            raise SecretValidationError("Cannot specify both value and from_file")
        
        if not value and not from_file:
            raise SecretValidationError("Must specify either value or from_file")
        
        # Create the secret
        return client.secrets.create(
            name=name,
            value=value,
            description=description,
            from_file=from_file
        )
        
    except SecretValidationError as e:
        print(f"Secret validation failed: {e}")
        
        # Provide helpful guidance based on error
        error_msg = str(e).lower()
        if "name" in error_msg:
            print("💡 Use a descriptive, non-empty secret name")
        elif "both value and from_file" in error_msg:
            print("💡 Choose either direct value or file input, not both")
        elif "must specify either" in error_msg:
            print("💡 Provide secret content via 'value' parameter or 'from_file' path")
        
        raise  # Re-raise for caller to handle
    except SecretError as e:
        print(f"Secret creation failed: {e}")
        raise

Usage Patterns

Safe Secret Retrieval

def get_secret_with_fallback(primary_name: str, fallback_name: str = None) -> str:
    """Get a secret with optional fallback"""
    try:
        return client.secrets.value(primary_name)
    except SecretError as e:
        if fallback_name:
            print(f"Primary secret '{primary_name}' failed, trying fallback...")
            try:
                return client.secrets.value(fallback_name)
            except SecretError:
                print(f"Both primary and fallback secrets failed")
                raise e
        else:
            raise e

Batch Secret Operations

def create_secrets_batch(secrets_data: List[Dict[str, str]]) -> Dict[str, bool]:
    """Create multiple secrets with error tracking"""
    results = {}
    
    for secret_info in secrets_data:
        name = secret_info.get('name')
        value = secret_info.get('value')
        description = secret_info.get('description')
        
        try:
            client.secrets.create(name=name, value=value, description=description)
            results[name] = True
            print(f"✅ Created secret: {name}")
            
        except (SecretError, SecretValidationError) as e:
            results[name] = False
            print(f"❌ Failed to create secret '{name}': {e}")
    
    return results

Secret Rotation Workflow

def rotate_secret_safely(name: str, new_value: str) -> bool:
    """Safely rotate a secret with backup"""
    try:
        # Get current value as backup
        current_value = client.secrets.value(name)
        
        # Update with new value
        client.secrets.update(name=name, value=new_value)
        print(f"✅ Secret '{name}' rotated successfully")
        
        return True
        
    except SecretError as e:
        print(f"❌ Secret rotation failed for '{name}': {e}")
        
        # If update failed but we have the current value, we could restore
        # (Implementation depends on your backup strategy)
        
        return False
This API reference provides complete documentation for all public interfaces in the Secrets service. Use the examples and error handling patterns to build secure and robust secret management workflows.