deploy_with_aws_secrets.pyā¢4.55 kB
#!/usr/bin/env python3
"""
Deploy Docker with AWS Secrets Manager
Fetches credentials from AWS, then deploys Docker Compose
"""
import asyncio
import os
import sys
import subprocess
# Add src to path
sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'src'))
from postgres_mcp_allaccess.aws_secrets import get_postgres_connection_info
async def fetch_and_deploy():
"""Fetch credentials from AWS and deploy Docker"""
# Set AWS credentials from command line args
aws_access_key = os.getenv('AWS_ACCESS_KEY_ID')
aws_secret_key = os.getenv('AWS_SECRET_ACCESS_KEY')
aws_region = os.getenv('AWS_REGION', 'us-west-2')
if not aws_access_key or not aws_secret_key:
print("ERROR: AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY must be set")
print("Usage: AWS_ACCESS_KEY_ID=xxx AWS_SECRET_ACCESS_KEY=yyy python deploy_with_aws_secrets.py")
sys.exit(1)
print("š Fetching credentials from AWS Secrets Manager...")
print(f" Region: {aws_region}")
# Get AWS Secrets Manager secret names from environment variables
# These are pointers to secrets in AWS, not the actual credentials
host_secret = os.getenv('AWS_SECRET_NAME', 'postgres/dev/dev_pg')
password_secret = os.getenv('AWS_PASSWORD_SECRET_NAME', 'rds!db-ff86132a-172a-4b59-b666-5511e8cc7afa')
print(f" Host Secret: {host_secret}")
print(f" Password Secret: {password_secret}")
try:
conn_info = await get_postgres_connection_info(
host_secret_name=host_secret,
password_secret_name=password_secret,
force_refresh=False
)
if not conn_info:
print("ā Failed to fetch credentials from AWS Secrets")
sys.exit(1)
print(f"ā
Successfully fetched credentials")
print(f" Host: {conn_info['host']}")
print(f" Database: {conn_info['database']}")
print(f" User: {conn_info['user']}")
# Prepare environment variables for docker-compose
env = os.environ.copy()
env.update({
# PostgreSQL credentials (for PgBouncer and MCP)
'POSTGRES_DATABASE': conn_info['database'],
'POSTGRES_USER': conn_info['user'],
'POSTGRES_PASSWORD': conn_info['password'],
# Real PostgreSQL connection (for PgBouncer to connect to)
'POSTGRES_REAL_HOST': conn_info['host'],
'POSTGRES_REAL_PORT': str(conn_info['port']),
# AWS credentials (for MCP server password rotation)
'AWS_ACCESS_KEY_ID': aws_access_key,
'AWS_SECRET_ACCESS_KEY': aws_secret_key,
'AWS_REGION': aws_region,
# AWS Secrets Manager secret names (pointers, not actual secrets)
'AWS_SECRET_NAME': host_secret,
'AWS_PASSWORD_SECRET_NAME': password_secret,
# MCP configuration
'MCP_SSE_PORT': '3000',
'PGBOUNCER_ENABLED': 'true',
})
print("\nš³ Starting Docker Compose...")
print(" - MCP Server with embedded PgBouncer")
print(" - PgBouncer connects to: {0}:{1}".format(conn_info['host'], conn_info['port']))
# Run docker-compose
result = subprocess.run(
['docker-compose', 'up', '-d', '--build'],
env=env,
capture_output=True,
text=True
)
if result.returncode != 0:
print(f"ā Docker Compose failed:")
print(result.stderr)
sys.exit(1)
print("\nā
Docker Compose started successfully!")
print("\nš Services:")
print(" - MCP Server: http://localhost:3000/sse")
print(" - PgBouncer (embedded): localhost:6432")
print(" - Health Check: http://localhost:3000/health")
print("\nš Next steps:")
print(" 1. Check health: curl http://localhost:3000/health")
print(" 2. View logs: docker-compose logs -f")
print(" 3. Monitor PgBouncer: docker exec -it yt-postgres-mcp psql -h localhost -p 6432 -U {} -d pgbouncer -c 'SHOW POOLS'".format(conn_info['user']))
print("\nš Password Rotation:")
print(" - Automatic: MCP server detects auth failures and refreshes both MCP and PgBouncer passwords")
print(" - Manual refresh: Restart container if needed")
except Exception as e:
print(f"ā Error: {e}")
import traceback
traceback.print_exc()
sys.exit(1)
if __name__ == "__main__":
asyncio.run(fetch_and_deploy())