Files
computer/examples/cloud_api_examples.py
f-trycua 73c0f3e52e Add automatic CUA_API_KEY environment variable support for Computer and CloudProvider
Previously, users had to explicitly read the CUA_API_KEY environment variable
and pass it to the Computer/CloudProvider constructor. This change makes the
API key parameter optional and automatically reads from the CUA_API_KEY
environment variable if not provided.

Changes:
- CloudProvider.__init__: Made api_key parameter optional, reads from CUA_API_KEY env var
- Computer.__init__: Added fallback to CUA_API_KEY env var for api_key parameter
- Updated documentation examples to show simplified usage without explicit api_key
- Updated cloud_api_examples.py to demonstrate the new simpler pattern

This provides a cleaner API while maintaining backward compatibility with
explicit api_key parameter passing.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-19 19:35:32 +01:00

73 lines
2.2 KiB
Python

import asyncio
import os
from utils import load_dotenv_files
load_dotenv_files()
from computer.providers.cloud.provider import CloudProvider
async def main() -> None:
# CloudProvider will automatically read CUA_API_KEY from environment if not provided
# You can still pass api_key explicitly if needed: CloudProvider(api_key="your_key")
api_base = os.getenv("CUA_API_BASE")
if api_base:
print(f"Using API base: {api_base}")
provider = CloudProvider(verbose=True)
async with provider:
# List all VMs
vms = await provider.list_vms()
print(f"Found {len(vms)} VM(s)")
for vm in vms:
print(
f"name: {vm['name']}\n",
f"status: {vm['status']}\n", # pending, running, stopped, terminated, failed
f"api_url: {vm.get('api_url')}\n",
f"vnc_url: {vm.get('vnc_url')}\n",
)
# # --- Additional operations (commented out) ---
# # To stop a VM by name:
# name = "m-linux-96lcxd2c2k"
# resp = await provider.stop_vm(name)
# print(
# "stop_vm response:\n",
# f"name: {resp['name']}\n",
# f"status: {resp['status']}\n", # stopping
# )
# # To start a VM by name:
# name = "m-linux-96lcxd2c2k"
# resp = await provider.run_vm(name)
# print(
# "run_vm response:\n",
# f"name: {resp['name']}\n",
# f"status: {resp['status']}\n", # starting
# )
# # To restart a VM by name:
# name = "m-linux-96lcxd2c2k"
# resp = await provider.restart_vm(name)
# print(
# "restart_vm response:\n",
# f"name: {resp['name']}\n",
# f"status: {resp['status']}\n", # restarting
# )
# # To probe a VM's status via its public hostname (if you know the name):
# name = "m-linux-96lcxd2c2k"
# info = await provider.get_vm(name)
# print("get_vm info:\n",
# f"name: {info['name']}\n",
# f"status: {info['status']}\n", # running
# f"api_url: {info.get('api_url')}\n",
# f"os_type: {info.get('os_type')}\n",
# )
if __name__ == "__main__":
asyncio.run(main())