Skip to main content

Multi-Environment Token Management

Build a complete token management system to organize API keys across development, staging, and production environments with automated rotation and usage tracking.

What You’ll Build

By the end of this tutorial, you’ll have:
  • Environment-Specific Tokens - Separate tokens for dev, staging, and production
  • Automated Token Rotation - Scripts to rotate tokens on a schedule
  • Usage Monitoring - Track spending per environment
  • Budget Controls - Different credit limits per environment
  • Expiration Alerts - Notifications before tokens expire

Prerequisites

  • Python 3.8 or higher
  • Eden AI API key
  • Basic understanding of REST APIs and environment management

Problem Statement

As your Eden AI integration grows across environments, you need to:
  1. Separate concerns - Different tokens for different environments
  2. Control costs - Budget limits per environment
  3. Enhance security - Rotate tokens without downtime
  4. Track usage - Monitor which environment is spending what
  5. Prevent outages - Alert before tokens expire or run out of credits
This tutorial shows you how to build a Python-based token management system.

Architecture Overview

┌──────────────────────────────────────────────────────────┐
│               Token Management System                     │
│                                                           │
│  ┌─────────────┐   ┌──────────────┐   ┌──────────────┐ │
│  │  Token      │──▶│   Rotation   │──▶│   Monitor    │ │
│  │  Registry   │   │   Manager    │   │   & Alerts   │ │
│  └─────────────┘   └──────────────┘   └──────────────┘ │
│        │                   │                   │         │
└────────┼───────────────────┼───────────────────┼─────────┘
         │                   │                   │
         ▼                   ▼                   ▼
    ┌────────────────────────────────────────────────┐
    │           Eden AI Token API                    │
    └────────────────────────────────────────────────┘

Step 1: Create Environment-Specific Tokens

Create a token manager that organizes tokens by environment:

Step 2: Implement Token Rotation Script

Create a rotation system to periodically update tokens:

Step 3: Build Token Lifecycle Manager

Manage the complete lifecycle of environment tokens:

Step 4: Add Usage Monitoring Per Token

Integrate with cost monitoring to track per-token usage:

Step 5: Implement Automated Alerts for Token Expiry

Create an alert system for token health:

Step 6: Put It All Together

Create a complete management system:

Example: Setting Up Multi-Environment System

Complete example setting up dev, staging, and production:

Testing

Test your token management system:
# Set up environments
export EDENAI_API_KEY="your_main_api_key"
python setup_environments.py

# Run health check
python main.py

# Rotate a specific token
python -c "
from token_manager import TokenManager
from token_rotation import TokenRotationManager
import os

manager = TokenManager(os.getenv('EDENAI_API_KEY'))
rotation = TokenRotationManager(manager)

result = rotation.rotate_token('prod-web-app')
print(result['migration_steps'])
"

Production Considerations

Automated Rotation Schedule

Use cron for automated token rotation:
# Rotate tokens expiring in 7 days, every day at 2 AM
0 2 * * * /usr/bin/python3 /path/to/rotate_expiring.py >> /var/log/token_rotation.log 2>&1

Secure Token Storage

Store generated tokens securely:
import boto3
import json

def store_token_in_secrets_manager(token_name: str, token_value: str):
    """Store token in AWS Secrets Manager"""
    client = boto3.client('secretsmanager')

    secret_name = f"edenai/{token_name}"

    try:
        client.create_secret(
            Name=secret_name,
            SecretString=json.dumps({
                'token': token_value,
                'created_at': datetime.now().isoformat()
            })
        )
    except client.exceptions.ResourceExistsException:
        client.update_secret(
            SecretId=secret_name,
            SecretString=json.dumps({
                'token': token_value,
                'updated_at': datetime.now().isoformat()
            })
        )

Monitoring Integration

Integrate with monitoring systems:
import logging

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

def monitor_token_health():
    """Log token health to monitoring system"""
    alerts = TokenAlertSystem(manager)

    expiring = alerts.check_expiring_tokens()
    low_balance = alerts.check_low_balance_tokens()

    if expiring:
        logger.warning(f"{len(expiring)} tokens expiring soon")
        # Send to monitoring system (Datadog, New Relic, etc.)

    if low_balance:
        logger.warning(f"{len(low_balance)} tokens with low balance")
        # Send alert

Next Steps

Now that you have a complete multi-environment token management system:

Complete Example Output

When you run main.py:
🔐 Multi-Environment Token Management System

📊 Token Health Check
============================================================
Token Health Report
============================================================

⚠️  EXPIRING TOKENS:
------------------------------------------------------------
🟡 staging-web-app
   Expires in 12 days
🟡 staging-mobile-app
   Expires in 12 days

✓ All token balances adequate

============================================================

🗂️  Tokens by Environment

DEV:
  ✓ dev-web-app
  ✓ dev-mobile-app
  ✓ dev-testing

STAGING:
  ⚠️ staging-web-app
     Balance: $8.45
     Expires in: 12 days
  ✓ staging-mobile-app
     Balance: $42.10
     Expires in: 12 days

PROD:
  ✓ prod-web-app
     Balance: $478.90
     Expires in: 85 days
  ✓ prod-mobile-app
     Balance: $456.23
     Expires in: 85 days
  ✓ prod-api-gateway
     Balance: $892.34
     Expires in: 85 days

💰 Usage Report (Last 30 Days)
============================================================
Token Usage Report: 2024-01-01 to 2024-01-31
============================================================

Environment: DEV
  Tokens: 3
  Total Cost: $0.00
  Total Calls: 1,234
  Avg Cost/Call: $0.0000

Environment: STAGING
  Tokens: 2
  Total Cost: $3.89
  Total Calls: 456
  Avg Cost/Call: $0.0085

Environment: PROD
  Tokens: 3
  Total Cost: $127.11
  Total Calls: 8,921
  Avg Cost/Call: $0.0142

TOTAL COST (ALL ENVIRONMENTS): $131.00
============================================================

🔄 Rotation Status
⚠️  2 token(s) need rotation