#!/usr/bin/env python3 """ Deployment script for deploying the text-adventure app to Portainer. """ import requests import json import sys import os from pathlib import Path from dotenv import load_dotenv # Load environment variables from .env file load_dotenv() class PortainerDeployer: """Class to handle deployment to Portainer.""" def __init__(self, portainer_url, username, password): """Initialize the Portainer deployer. Args: portainer_url (str): URL of the Portainer instance (e.g., http://10.0.0.199:9000) username (str): Portainer username password (str): Portainer password """ self.portainer_url = portainer_url.rstrip('/') self.username = username self.password = password self.auth_token = None self.endpoint_id = None def authenticate(self): """Authenticate with Portainer and get JWT token. Returns: bool: True if authentication successful, False otherwise """ try: url = f"{self.portainer_url}/api/auth" payload = { "username": self.username, "password": self.password } response = requests.post(url, json=payload) response.raise_for_status() data = response.json() self.auth_token = data.get('jwt') if self.auth_token: print("✓ Successfully authenticated with Portainer") return True else: print("✗ Failed to get authentication token") return False except requests.exceptions.RequestException as e: print(f"✗ Error authenticating with Portainer: {e}") return False def get_endpoints(self): """Get list of Docker endpoints. Returns: list: List of endpoints or None if failed """ try: url = f"{self.portainer_url}/api/endpoints" headers = {"Authorization": f"Bearer {self.auth_token}"} response = requests.get(url, headers=headers) response.raise_for_status() endpoints = response.json() return endpoints except requests.exceptions.RequestException as e: print(f"✗ Error getting endpoints: {e}") return None def select_endpoint(self, endpoint_name=None): """Select a Docker endpoint to deploy to. Args: endpoint_name (str, optional): Name of specific endpoint to use Returns: str: Endpoint ID or None if failed """ endpoints = self.get_endpoints() if not endpoints: return None if endpoint_name: # Find specific endpoint by name for endpoint in endpoints: if endpoint.get('Name') == endpoint_name: self.endpoint_id = endpoint.get('Id') print(f"✓ Selected endpoint: {endpoint_name} (ID: {self.endpoint_id})") return self.endpoint_id print(f"✗ Endpoint '{endpoint_name}' not found") return None else: # Use first endpoint if no specific one requested if endpoints: endpoint = endpoints[0] self.endpoint_id = endpoint.get('Id') print(f"✓ Selected endpoint: {endpoint.get('Name')} (ID: {self.endpoint_id})") return self.endpoint_id else: print("✗ No endpoints found") return None def deploy_stack(self, stack_name, compose_file_path): """Deploy a Docker stack using a compose file. Args: stack_name (str): Name for the stack compose_file_path (str): Path to docker-compose.yml file Returns: bool: True if deployment successful, False otherwise """ try: if not self.endpoint_id: print("✗ No endpoint selected") return False # Read compose file if not os.path.exists(compose_file_path): print(f"✗ Compose file not found: {compose_file_path}") return False with open(compose_file_path, 'r') as f: compose_content = f.read() # Deploy stack url = f"{self.portainer_url}/api/stacks" headers = {"Authorization": f"Bearer {self.auth_token}"} params = { "type": 2, # Swarm stack "method": "string", "endpointId": self.endpoint_id } payload = { "name": stack_name, "StackFileContent": compose_content } response = requests.post(url, headers=headers, params=params, json=payload) if response.status_code == 200: print(f"✓ Stack '{stack_name}' deployed successfully") return True else: print(f"✗ Failed to deploy stack: {response.status_code} - {response.text}") return False except Exception as e: print(f"✗ Error deploying stack: {e}") return False def deploy_container(self, container_name, image_name, network_mode="default"): """Deploy a single container. Args: container_name (str): Name for the container image_name (str): Docker image to use network_mode (str): Network mode for the container Returns: bool: True if deployment successful, False otherwise """ try: if not self.endpoint_id: print("✗ No endpoint selected") return False # Deploy container url = f"{self.portainer_url}/api/endpoints/{self.endpoint_id}/docker/containers/create" headers = {"Authorization": f"Bearer {self.auth_token}"} # Container configuration payload = { "Image": image_name, "name": container_name, "HostConfig": { "NetworkMode": network_mode, "RestartPolicy": { "Name": "unless-stopped" } }, "Tty": True, "OpenStdin": True } # Create container response = requests.post(url, headers=headers, json=payload) if response.status_code == 201: container_data = response.json() container_id = container_data.get('Id') print(f"✓ Container '{container_name}' created successfully") # Start container start_url = f"{self.portainer_url}/api/endpoints/{self.endpoint_id}/docker/containers/{container_id}/start" start_response = requests.post(start_url, headers=headers) if start_response.status_code == 204: print(f"✓ Container '{container_name}' started successfully") return True else: print(f"✗ Failed to start container: {start_response.status_code}") return False else: print(f"✗ Failed to create container: {response.status_code} - {response.text}") return False except Exception as e: print(f"✗ Error deploying container: {e}") return False def main(): """Main function to deploy the application to Portainer.""" print("Deploying text-adventure app to Portainer...") print("=" * 50) # Configuration from .env file or environment variables PORTAINER_URL = os.environ.get('PORTAINER_URL', 'http://10.0.0.199:9000') PORTAINER_USERNAME = os.environ.get('PORTAINER_USERNAME', 'admin') PORTAINER_PASSWORD = os.environ.get('PORTAINER_PASSWORD', 'password') ENDPOINT_NAME = os.environ.get('PORTAINER_ENDPOINT', None) print(f"Using Portainer URL: {PORTAINER_URL}") print(f"Using Username: {PORTAINER_USERNAME}") # Create deployer instance deployer = PortainerDeployer(PORTAINER_URL, PORTAINER_USERNAME, PORTAINER_PASSWORD) # Authenticate if not deployer.authenticate(): sys.exit(1) # Select endpoint if not deployer.select_endpoint(ENDPOINT_NAME): sys.exit(1) # Deploy as container (simpler approach for this app) print("\nDeploying as container...") success = deployer.deploy_container( container_name="text-adventure-app", image_name="text-adventure:latest", network_mode="host" # Use host network to access LM Studio ) if success: print("\n✓ Deployment completed successfully!") print("You can now access your container through Portainer") else: print("\n✗ Deployment failed!") sys.exit(1) if __name__ == "__main__": main()