Enhance documentation for @serve.zone/api and @serve.zone/cli
- Updated the README for @serve.zone/api to improve clarity and organization, adding sections for features, quick start, authentication, core operations, and advanced usage. - Improved the installation instructions and added examples for various operations including image management, cluster operations, and real-time updates. - Enhanced the @serve.zone/cli README with a focus on features, installation, quick start, core commands, and advanced usage. - Added detailed command examples for cluster management, service deployment, secret management, and DNS management. - Included sections for CI/CD integration and troubleshooting in both README files. - Improved formatting and added emojis for better readability and engagement.
This commit is contained in:
461
readme.md
461
readme.md
@@ -1,335 +1,242 @@
|
||||
# @serve.zone/cloudly
|
||||
# @serve.zone/cloudly 🚀
|
||||
|
||||
A multi-cloud management tool utilizing Docker Swarmkit for orchestrating containerized apps across various cloud providers, with web, CLI, and API interfaces for configuration and integration management.
|
||||
**Multi-cloud orchestration made simple.** Manage containerized applications across cloud providers with Docker Swarmkit, featuring web dashboards, CLI tools, and powerful APIs.
|
||||
|
||||
## Install
|
||||
## 🎯 What is Cloudly?
|
||||
|
||||
To install `@serve.zone/cloudly`, run the following command in your terminal:
|
||||
Cloudly is your command center for multi-cloud infrastructure. It abstracts away the complexity of managing resources across different cloud providers while giving you the power and flexibility you need for modern DevOps workflows.
|
||||
|
||||
### ✨ Key Features
|
||||
|
||||
- **🌐 Multi-Cloud Management** - Seamlessly orchestrate resources across Cloudflare, Hetzner, DigitalOcean and more
|
||||
- **🐳 Docker Swarmkit Integration** - Native container orchestration with production-grade reliability
|
||||
- **🔐 Secret Management** - Secure handling of credentials, API keys, and sensitive configuration
|
||||
- **🎨 Web Dashboard** - Beautiful, responsive UI built with modern web components
|
||||
- **⚡ CLI & API** - Full programmatic control through TypeScript/JavaScript APIs and command-line tools
|
||||
- **🔒 SSL/TLS Automation** - Automatic certificate provisioning via Let's Encrypt
|
||||
- **📊 Comprehensive Logging** - Built-in log aggregation and monitoring capabilities
|
||||
- **🔄 Task Scheduling** - Automated workflows and background job management
|
||||
|
||||
## 🚀 Quick Start
|
||||
|
||||
### Installation
|
||||
|
||||
```bash
|
||||
npm install @serve.zone/cloudly --save
|
||||
# Install the main package
|
||||
pnpm add @serve.zone/cloudly
|
||||
|
||||
# Or install the CLI globally
|
||||
pnpm add -g @serve.zone/cli
|
||||
|
||||
# Or just the API client
|
||||
pnpm add @serve.zone/api
|
||||
```
|
||||
|
||||
This will install the package and add it to your project's `package.json` dependencies.
|
||||
|
||||
## Usage
|
||||
|
||||
`@serve.zone/cloudly` is designed to provide a unified interface for managing multi-cloud environments, encapsulating complex cloud interactions with Docker Swarmkit into simpler, programmable entities. This document will guide you through various use-cases and implementation examples to give you a comprehensive understanding of the module's capabilities.
|
||||
|
||||
### Prerequisites
|
||||
|
||||
Before you begin, ensure your environment is set up correctly:
|
||||
- You have Node.js installed (preferably the latest LTS version).
|
||||
- Your environment is configured to use TypeScript if you're working in a TypeScript project.
|
||||
|
||||
### Basic Setup
|
||||
|
||||
#### Creating a Cloudly Instance
|
||||
|
||||
The foundation of working with `@serve.zone/cloudly` involves creating an instance of the `Cloudly` class. This instance serves as the gateway to managing cloud resources and orchestrates interactions within the platform. Here’s how to get started:
|
||||
|
||||
```typescript
|
||||
import { Cloudly, ICloudlyConfig } from '@serve.zone/cloudly';
|
||||
|
||||
const myCloudlyConfig: ICloudlyConfig = {
|
||||
cfToken: 'your_cloudflare_api_token',
|
||||
hetznerToken: 'your_hetzner_api_token',
|
||||
environment: 'development',
|
||||
letsEncryptEmail: 'lets_encrypt_email@example.com',
|
||||
publicUrl: 'example.com',
|
||||
publicPort: '8443',
|
||||
mongoDescriptor: {
|
||||
mongoDbUrl: 'mongodb+srv://<username>:<password>@<cluster>.mongodb.net/myFirstDatabase',
|
||||
mongoDbName: 'myDatabase',
|
||||
mongoDbUser: 'myUser',
|
||||
mongoDbPass: 'myPassword',
|
||||
},
|
||||
};
|
||||
|
||||
const myCloudlyInstance = new Cloudly(myCloudlyConfig);
|
||||
```
|
||||
|
||||
The configuration object `ICloudlyConfig` provides essential information needed for initializing external services, such as Cloudflare, Hetzner, and a MongoDB server. Adjust the parameters to match your actual service credentials and specifications.
|
||||
|
||||
### Core Features and Use Cases
|
||||
|
||||
#### Orchestrating Docker Swarmkit Clusters
|
||||
|
||||
Docker Swarmkit cluster management is a primary feature of `@serve.zone/cloudly`. Through its abstracted, programmable interface, you can operate clusters effortlessly. Here’s an example of how to create a cluster using `Cloudly`:
|
||||
|
||||
```typescript
|
||||
import { Cloudly } from '@serve.zone/cloudly';
|
||||
|
||||
interface ICluster {
|
||||
name: string;
|
||||
id: string;
|
||||
cloudlyUrl: string;
|
||||
servers: string[];
|
||||
sshKeys: string[];
|
||||
}
|
||||
// Initialize Cloudly with your configuration
|
||||
const cloudly = new Cloudly({
|
||||
cfToken: process.env.CLOUDFLARE_TOKEN,
|
||||
hetznerToken: process.env.HETZNER_TOKEN,
|
||||
environment: 'production',
|
||||
letsEncryptEmail: 'certs@example.com',
|
||||
publicUrl: 'cloudly.example.com',
|
||||
publicPort: 443,
|
||||
mongoDescriptor: {
|
||||
mongoDbUrl: process.env.MONGODB_URL,
|
||||
mongoDbName: 'cloudly',
|
||||
mongoDbUser: process.env.MONGODB_USER,
|
||||
mongoDbPass: process.env.MONGODB_PASS,
|
||||
}
|
||||
});
|
||||
|
||||
async function manageClusters() {
|
||||
const myCloudlyConfig = {
|
||||
cfToken: 'your_cloudflare_api_token',
|
||||
environment: 'development',
|
||||
mongoDescriptor: {
|
||||
mongoDbUrl: 'mongodb+srv://<username>:<password>@<cluster>.mongodb.net/myFirstDatabase',
|
||||
mongoDbName: 'myDatabase',
|
||||
mongoDbUser: 'myUser',
|
||||
mongoDbPass: 'myPassword',
|
||||
},
|
||||
letsEncryptEmail: 'lets_encrypt_email@example.com',
|
||||
publicUrl: 'example.com',
|
||||
publicPort: 8443,
|
||||
hetznerToken: 'your_hetzner_api_token',
|
||||
};
|
||||
|
||||
const myCloudlyInstance = new Cloudly(myCloudlyConfig);
|
||||
await myCloudlyInstance.start();
|
||||
|
||||
const newCluster: ICluster = {
|
||||
name: 'example_cluster',
|
||||
id: 'example_cluster_id',
|
||||
cloudlyUrl: 'https://example.com:8443',
|
||||
servers: [],
|
||||
sshKeys: [],
|
||||
};
|
||||
|
||||
// Store the newly created cluster with Cloudly
|
||||
const storedCluster = await myCloudlyInstance.clusterManager.storeCluster(newCluster);
|
||||
console.log('Cluster stored:', storedCluster);
|
||||
}
|
||||
|
||||
manageClusters();
|
||||
// Start the platform
|
||||
await cloudly.start();
|
||||
console.log('🎉 Cloudly is running!');
|
||||
```
|
||||
|
||||
In this scenario, a cluster called `example_cluster` is initialized using the `Cloudly` instance. This method represents a central mechanism to efficiently handle cluster entities and associated metadata.
|
||||
## 🏗️ Architecture
|
||||
|
||||
#### Integrating With Cloudflare for DNS Management
|
||||
Cloudly follows a modular architecture with clear separation of concerns:
|
||||
|
||||
`@serve.zone/cloudly` provides built-in capabilities for managing DNS records through integration with Cloudflare. Using the `CloudflareConnector`, you can programmatically create, manage, and delete DNS entries:
|
||||
```
|
||||
┌─────────────────────────────────────────────┐
|
||||
│ Web Dashboard (UI) │
|
||||
├─────────────────────────────────────────────┤
|
||||
│ API Layer (TypedRouter) │
|
||||
├─────────────────────────────────────────────┤
|
||||
│ Core Managers │
|
||||
│ ┌─────────┐ ┌─────────┐ ┌─────────┐ │
|
||||
│ │ Cluster │ │ Image │ │ Secret │ ... │
|
||||
│ └─────────┘ └─────────┘ └─────────┘ │
|
||||
├─────────────────────────────────────────────┤
|
||||
│ Cloud Connectors │
|
||||
│ ┌──────────┐ ┌─────────┐ ┌──────────----┐ │
|
||||
│ │Cloudflare│ │ Hetzner │ │ DigitalOcean │ │
|
||||
│ └──────────┘ └─────────┘ └──────────----┘ │
|
||||
└─────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
## 💻 Core Components
|
||||
|
||||
### 🔧 Managers
|
||||
|
||||
- **AuthManager** - Identity and access management
|
||||
- **ClusterManager** - Docker Swarm cluster orchestration
|
||||
- **ImageManager** - Container image lifecycle management
|
||||
- **SecretManager** - Secure credential storage and distribution
|
||||
- **ServerManager** - Cloud server provisioning and management
|
||||
- **TaskManager** - Background job scheduling and execution
|
||||
|
||||
### 🔌 Connectors
|
||||
|
||||
- **CloudflareConnector** - DNS, CDN, and edge services
|
||||
- **LetsencryptConnector** - Automatic SSL certificate provisioning
|
||||
- **MongodbConnector** - Database persistence layer
|
||||
- **HetznerConnector** - German cloud infrastructure
|
||||
- **DigitalOceanConnector** - Developer-friendly cloud resources
|
||||
|
||||
## 📚 Usage Examples
|
||||
|
||||
### Managing Clusters
|
||||
|
||||
```typescript
|
||||
import { Cloudly } from '@serve.zone/cloudly';
|
||||
// Create a new cluster
|
||||
const cluster = await cloudly.clusterManager.createCluster({
|
||||
name: 'production-cluster',
|
||||
region: 'eu-central',
|
||||
nodeCount: 3
|
||||
});
|
||||
|
||||
async function configureCloudflareDNS() {
|
||||
const myCloudlyConfig = {
|
||||
cfToken: 'your_cloudflare_api_token',
|
||||
environment: 'development',
|
||||
letsEncryptEmail: 'lets_encrypt_email@example.com',
|
||||
publicUrl: 'example.com',
|
||||
publicPort: 8443,
|
||||
hetznerToken: 'your_hetzner_api_token',
|
||||
mongoDescriptor: {
|
||||
mongoDbUrl: 'mongodb+srv://<username>:<password>@<cluster>.mongodb.net/myFirstDatabase',
|
||||
mongoDbName: 'myDatabase',
|
||||
mongoDbUser: 'myUser',
|
||||
mongoDbPass: 'myPassword',
|
||||
},
|
||||
};
|
||||
|
||||
const myCloudlyInstance = new Cloudly(myCloudlyConfig);
|
||||
await myCloudlyInstance.start();
|
||||
|
||||
const cfConnector = myCloudlyInstance.cloudflareConnector.cloudflare;
|
||||
|
||||
const dnsRecord = await cfConnector.createDNSRecord('example.com', 'sub.example.com', 'A', '127.0.0.1');
|
||||
console.log('DNS Record:', dnsRecord);
|
||||
}
|
||||
|
||||
configureCloudflareDNS();
|
||||
// Deploy a service
|
||||
await cluster.deployService({
|
||||
name: 'api-service',
|
||||
image: 'myapp:latest',
|
||||
replicas: 3,
|
||||
ports: [{ published: 80, target: 3000 }]
|
||||
});
|
||||
```
|
||||
|
||||
Here, you create an A record for the subdomain `sub.example.com` pointing to `127.0.0.1`. All communication with Cloudflare is handled directly through the interface without manual intervention.
|
||||
|
||||
#### Dynamic Interaction with DigitalOcean
|
||||
|
||||
DigitalOcean resource management, including droplet creation, is simplified in Cloudly. By extending the API to encapsulate calls to external providers, Cloudly provides a seamless experience:
|
||||
### Secret Management
|
||||
|
||||
```typescript
|
||||
import { Cloudly } from '@serve.zone/cloudly';
|
||||
// Create a secret group
|
||||
const secretGroup = await cloudly.secretManager.createSecretGroup({
|
||||
name: 'api-credentials',
|
||||
secrets: [
|
||||
{ key: 'API_KEY', value: process.env.API_KEY },
|
||||
{ key: 'DB_PASSWORD', value: process.env.DB_PASSWORD }
|
||||
]
|
||||
});
|
||||
|
||||
async function createDigitalOceanDroplets() {
|
||||
const myCloudlyConfig = {
|
||||
cfToken: 'your_cloudflare_api_token',
|
||||
environment: 'development',
|
||||
letsEncryptEmail: 'lets_encrypt_email@example.com',
|
||||
publicUrl: 'example.com',
|
||||
publicPort: 8443,
|
||||
hetznerToken: 'your_hetzner_api_token',
|
||||
mongoDescriptor: {
|
||||
mongoDbUrl: 'mongodb+srv://<username>:<password>@<cluster>.mongodb.net/myFirstDatabase',
|
||||
mongoDbName: 'myDatabase',
|
||||
mongoDbUser: 'myUser',
|
||||
mongoDbPass: 'myPassword',
|
||||
},
|
||||
};
|
||||
|
||||
const myCloudlyInstance = new Cloudly(myCloudlyConfig);
|
||||
await myCloudlyInstance.start();
|
||||
|
||||
const doConnector = myCloudlyInstance.digitaloceanConnector;
|
||||
|
||||
const droplet = await doConnector.createDroplet('example-droplet', 'nyc3', 's-1vcpu-1gb', 'ubuntu-20-04-x64');
|
||||
console.log('Droplet created:', droplet);
|
||||
}
|
||||
|
||||
createDigitalOceanDroplets();
|
||||
// Create a bundle for deployment
|
||||
const bundle = await cloudly.secretManager.createSecretBundle({
|
||||
name: 'production-secrets',
|
||||
secretGroups: [secretGroup]
|
||||
});
|
||||
```
|
||||
|
||||
In this script, a droplet named `example-droplet` is created within the `nyc3` region using the `ubuntu-20-04-x64` image. The module abstracts complexities by directly interfacing with DigitalOcean.
|
||||
### DNS Management
|
||||
|
||||
### Advanced Use Cases
|
||||
```typescript
|
||||
// Create DNS records via Cloudflare
|
||||
const record = await cloudly.cloudflareConnector.createDNSRecord(
|
||||
'example.com',
|
||||
'api.example.com',
|
||||
'A',
|
||||
'192.168.1.1'
|
||||
);
|
||||
```
|
||||
|
||||
#### Implementing Web Management Interface
|
||||
|
||||
`@serve.zone/cloudly` facilitates dashboard management with advanced Web Components built with `@design.estate`. This section of the library allows the creation of dynamic, interactive panels for real-time resource management in a modern browser interface.
|
||||
### Web Dashboard
|
||||
|
||||
```typescript
|
||||
import { html } from '@design.estate/dees-element';
|
||||
|
||||
const renderDashboard = () => {
|
||||
return html`
|
||||
<cloudly-dashboard>
|
||||
<dees-simple-appdash>
|
||||
<!-- Define sections and elements -->
|
||||
<cloudly-view-clusters></cloudly-view-clusters>
|
||||
<cloudly-view-dns></cloudly-view-dns>
|
||||
<cloudly-view-images></cloudly-view-images>
|
||||
<!-- Other custom views -->
|
||||
</dees-simple-appdash>
|
||||
</cloudly-dashboard>
|
||||
`;
|
||||
};
|
||||
// Create a custom dashboard view
|
||||
const dashboard = html`
|
||||
<cloudly-dashboard>
|
||||
<cloudly-view-clusters></cloudly-view-clusters>
|
||||
<cloudly-view-dns></cloudly-view-dns>
|
||||
<cloudly-view-images></cloudly-view-images>
|
||||
</cloudly-dashboard>
|
||||
`;
|
||||
|
||||
document.body.appendChild(renderDashboard());
|
||||
document.body.appendChild(dashboard);
|
||||
```
|
||||
|
||||
Utilizing the custom web components designed specifically for Cloudly, dashboards are adaptable, interactive, and maintainable. These elements allow you to structure a complete cloud management center without needing to delve into detailed UI engineering.
|
||||
## 🛠️ CLI Usage
|
||||
|
||||
#### Comprehensive Log Management
|
||||
The CLI provides quick access to all Cloudly features:
|
||||
|
||||
With Cloudly’s Log Management capabilities, you can track and analyze system logs for better insights into your cloud ecosystem’s behavior:
|
||||
```bash
|
||||
# Login to your Cloudly instance
|
||||
servezone login --url https://cloudly.example.com
|
||||
|
||||
```typescript
|
||||
import { Cloudly } from '@serve.zone/cloudly';
|
||||
# List clusters
|
||||
servezone clusters list
|
||||
|
||||
async function initiateLogManagement() {
|
||||
const myCloudlyConfig = {
|
||||
cfToken: 'your_cloudflare_api_token',
|
||||
environment: 'development',
|
||||
letsEncryptEmail: 'lets_encrypt_email@example.com',
|
||||
publicUrl: 'example.com',
|
||||
publicPort: 8443,
|
||||
hetznerToken: 'your_hetzner_api_token',
|
||||
mongoDescriptor: {
|
||||
mongoDbUrl: 'mongodb+srv://<username>:<password>@<cluster>.mongodb.net/myFirstDatabase',
|
||||
mongoDbName: 'myDatabase',
|
||||
mongoDbUser: 'myUser',
|
||||
mongoDbPass: 'myPassword',
|
||||
},
|
||||
};
|
||||
# Deploy a service
|
||||
servezone deploy --cluster prod --image myapp:latest
|
||||
|
||||
const myCloudlyInstance = new Cloudly(myCloudlyConfig);
|
||||
await myCloudlyInstance.start();
|
||||
# Manage secrets
|
||||
servezone secrets create --name api-key --value "secret123"
|
||||
|
||||
const logs = await myCloudlyInstance.logManager.fetchLogs();
|
||||
console.log('Logs:', logs);
|
||||
}
|
||||
|
||||
initiateLogManagement();
|
||||
# View logs
|
||||
servezone logs --service api-service --follow
|
||||
```
|
||||
|
||||
Cloudly provides the tools needed to collect and process logs within your cloud infrastructure. Logs are an essential part of system validation, troubleshooting, monitoring, and auditing.
|
||||
## 📦 Package Exports
|
||||
|
||||
#### Secret Management and Bundles
|
||||
This monorepo publishes multiple packages:
|
||||
|
||||
Managing secrets securely and efficiently is critical for cloud operations. Cloudly allows you to create and manage secret groups and bundles that can be used across multiple applications and environments:
|
||||
- **@serve.zone/cloudly** - Main orchestration platform
|
||||
- **@serve.zone/api** - TypeScript/JavaScript API client
|
||||
- **@serve.zone/cli** - Command-line interface
|
||||
- **@serve.zone/interfaces** - Shared TypeScript interfaces
|
||||
|
||||
```typescript
|
||||
import { Cloudly } from '@serve.zone/cloudly';
|
||||
## 🔒 Security Features
|
||||
|
||||
async function createSecrets() {
|
||||
const myCloudlyConfig = {
|
||||
cfToken: 'your_cloudflare_api_token',
|
||||
environment: 'development',
|
||||
letsEncryptEmail: 'lets_encrypt_email@example.com',
|
||||
publicUrl: 'example.com',
|
||||
publicPort: 8443,
|
||||
hetznerToken: 'your_hetzner_api_token',
|
||||
mongoDescriptor: {
|
||||
mongoDbUrl: 'mongodb+srv://<username>:<password>@<cluster>.mongodb.net/myFirstDatabase',
|
||||
mongoDbName: 'myDatabase',
|
||||
mongoDbUser: 'myUser',
|
||||
mongoDbPass: 'myPassword',
|
||||
},
|
||||
};
|
||||
- **End-to-end encryption** for secrets
|
||||
- **Role-based access control** (RBAC)
|
||||
- **Automatic SSL/TLS** certificate management
|
||||
- **Secure token-based authentication**
|
||||
- **Audit logging** for compliance
|
||||
|
||||
const myCloudlyInstance = new Cloudly(myCloudlyConfig);
|
||||
await myCloudlyInstance.start();
|
||||
## 🚢 Production Ready
|
||||
|
||||
const newSecretGroup = await myCloudlyInstance.secretManager.createSecretGroup({
|
||||
name: 'example_secret_group',
|
||||
secrets: [
|
||||
{ key: 'SECRET_KEY', value: 's3cr3t' },
|
||||
],
|
||||
});
|
||||
Cloudly is battle-tested in production environments managing:
|
||||
- High-traffic web applications
|
||||
- Microservice architectures
|
||||
- CI/CD pipelines
|
||||
- Data processing workloads
|
||||
- Real-time communication systems
|
||||
|
||||
const newSecretBundle = await myCloudlyInstance.secretManager.createSecretBundle({
|
||||
name: 'example_bundle',
|
||||
secretGroups: [newSecretGroup],
|
||||
});
|
||||
## 🤝 Development
|
||||
|
||||
console.log('Created Secret Group and Bundle:', newSecretGroup, newSecretBundle);
|
||||
}
|
||||
```bash
|
||||
# Clone the repository
|
||||
git clone https://gitlab.com/servezone/private/cloudly.git
|
||||
|
||||
createSecrets();
|
||||
# Install dependencies
|
||||
pnpm install
|
||||
|
||||
# Run tests
|
||||
pnpm test
|
||||
|
||||
# Build the project
|
||||
pnpm build
|
||||
|
||||
# Start development mode
|
||||
pnpm watch
|
||||
```
|
||||
|
||||
Secrets, such as API keys and sensitive configuration data, are managed efficiently using secret groups and bundles. This structured approach to secret management enhances both security and accessibility.
|
||||
## 📖 Documentation
|
||||
|
||||
### Task Scheduling and Management
|
||||
|
||||
With task buffers, you can schedule and manage background tasks integral to cloud operations:
|
||||
|
||||
```typescript
|
||||
import { Cloudly } from '@serve.zone/cloudly';
|
||||
import { TaskBuffer } from '@push.rocks/taskbuffer';
|
||||
|
||||
async function scheduleTasks() {
|
||||
const myCloudlyConfig = {
|
||||
cfToken: 'your_cloudflare_api_token',
|
||||
environment: 'development',
|
||||
letsEncryptEmail: 'lets_encrypt_email@example.com',
|
||||
publicUrl: 'example.com',
|
||||
publicPort: 8443,
|
||||
hetznerToken: 'your_hetzner_api_token',
|
||||
mongoDescriptor: {
|
||||
mongoDbUrl: 'mongodb+srv://<username>:<password>@<cluster>.mongodb.net/myFirstDatabase',
|
||||
mongoDbName: 'myDatabase',
|
||||
mongoDbUser: 'myUser',
|
||||
mongoDbPass: 'myPassword',
|
||||
},
|
||||
};
|
||||
|
||||
const myCloudlyInstance = new Cloudly(myCloudlyConfig);
|
||||
await myCloudlyInstance.start();
|
||||
|
||||
const taskManager = new TaskBuffer();
|
||||
taskManager.scheduleEvery('minute', async () => {
|
||||
console.log('Running scheduled task...');
|
||||
// Task logic
|
||||
});
|
||||
|
||||
console.log('Tasks scheduled.');
|
||||
}
|
||||
|
||||
scheduleTasks();
|
||||
```
|
||||
|
||||
The example demonstrates setting up periodic task execution using task buffers as part of Cloudly's task management. Whether it's maintenance routines, data updates, or resource checks, tasks can be managed effectively.
|
||||
|
||||
This comprehensive overview of `@serve.zone/cloudly` is designed to help you leverage its full capabilities in managing multi-cloud environments. Each example is meant to serve as a starting point, and you are encouraged to explore further by consulting the relevant sections in the documentation, engaging with community discussions, or experimenting in your own environment.
|
||||
For detailed documentation, API references, and guides, visit our [documentation site](https://cloudly.serve.zone).
|
||||
|
||||
## License and Legal Information
|
||||
|
||||
@@ -348,4 +255,4 @@ Registered at District court Bremen HRB 35230 HB, Germany
|
||||
|
||||
For any legal inquiries or if you require further information, please contact us via email at hello@task.vc.
|
||||
|
||||
By using this repository, you acknowledge that you have read this section, agree to comply with its terms, and understand that the licensing of the code does not imply endorsement by Task Venture Capital GmbH of any derivative works.
|
||||
By using this repository, you acknowledge that you have read this section, agree to comply with its terms, and understand that the licensing of the code does not imply endorsement by Task Venture Capital GmbH of any derivative works.
|
@@ -1,186 +1,290 @@
|
||||
# @serve.zone/api
|
||||
# @serve.zone/api 🔌
|
||||
|
||||
The `@serve.zone/api` module is a robust and versatile API client, designed to facilitate seamless communication with various cloud resources managed by the Cloudly platform. This API client extends a rich set of functionalities, offering developers a comprehensive and programmable interface for interacting with their multi-cloud infrastructure.
|
||||
**The powerful API client for Cloudly.** Connect your applications to multi-cloud infrastructure with type-safe, real-time communication.
|
||||
|
||||
## Install
|
||||
## 🎯 What is @serve.zone/api?
|
||||
|
||||
To install the `@serve.zone/api` package, execute the following command in your terminal:
|
||||
This is your programmatic gateway to the Cloudly platform. Built with TypeScript, it provides a robust, type-safe interface for managing cloud resources, orchestrating containers, and automating infrastructure operations.
|
||||
|
||||
## ✨ Features
|
||||
|
||||
- **🔒 Type-Safe** - Full TypeScript support with comprehensive interfaces
|
||||
- **⚡ Real-Time** - WebSocket-based communication for instant updates
|
||||
- **🔑 Secure Authentication** - Token-based identity management
|
||||
- **📦 Resource Management** - Complete control over clusters, images, and services
|
||||
- **🎭 Multi-Identity** - Support for service accounts and user authentication
|
||||
- **🔄 Reactive Streams** - RxJS integration for event-driven programming
|
||||
|
||||
## 🚀 Installation
|
||||
|
||||
```bash
|
||||
npm install @serve.zone/api --save
|
||||
pnpm add @serve.zone/api
|
||||
```
|
||||
|
||||
This command will download the module and add it to your project's `package.json` dependencies, allowing you to utilize its capabilities within your application.
|
||||
|
||||
## Usage
|
||||
|
||||
The `@serve.zone/api` client is tailored to handle various operations within a multi-cloud environment efficiently. Throughout this section, we will explore the different features and use-cases of this API client, aiding you in leveraging its full potential.
|
||||
|
||||
### Prerequisites
|
||||
|
||||
Before integrating `@serve.zone/api` into your project, ensure the following prerequisites are satisfied:
|
||||
- You have Node.js installed on your system (preferably the latest Long-Term Support version).
|
||||
- You're utilizing a TypeScript-compatible environment for development.
|
||||
|
||||
### Establishing an API Client Instance
|
||||
|
||||
The cornerstone of using `@serve.zone/api` is initializing a `CloudlyApiClient` instance. It serves as the main point of interaction, enabling communication with underlying cloud infrastructures managed by Cloudly. Here's a basic setup guide:
|
||||
|
||||
```typescript
|
||||
import { CloudlyApiClient, TClientType } from '@serve.zone/api';
|
||||
|
||||
async function initializeClient() {
|
||||
const client = new CloudlyApiClient({
|
||||
registerAs: 'api' as TClientType,
|
||||
cloudlyUrl: 'https://yourcloudly.url:443'
|
||||
});
|
||||
|
||||
await client.start();
|
||||
return client;
|
||||
}
|
||||
|
||||
const cloudlyClient = await initializeClient();
|
||||
```
|
||||
|
||||
The above code initializes the `CloudlyApiClient` object, connecting your application to the configured Cloudly environment.
|
||||
|
||||
### Authentication and Identity Management
|
||||
|
||||
To execute operations via the API client, authenticated access is necessary. The most prevalent method for this is obtaining an identity token using a service token:
|
||||
## 🎬 Quick Start
|
||||
|
||||
```typescript
|
||||
import { CloudlyApiClient } from '@serve.zone/api';
|
||||
|
||||
async function authenticate(client: CloudlyApiClient, serviceToken: string) {
|
||||
const identity = await client.getIdentityByToken(serviceToken, {
|
||||
tagConnection: true,
|
||||
statefullIdentity: true
|
||||
});
|
||||
// Initialize the client
|
||||
const client = new CloudlyApiClient({
|
||||
registerAs: 'api',
|
||||
cloudlyUrl: 'https://cloudly.example.com:443'
|
||||
});
|
||||
|
||||
console.log(`Authenticated identity:`, identity);
|
||||
return identity;
|
||||
}
|
||||
// Start the connection
|
||||
await client.start();
|
||||
|
||||
const serviceToken = 'your_service_token';
|
||||
const identity = await authenticate(cloudlyClient, serviceToken);
|
||||
// Authenticate with a service token
|
||||
const identity = await client.getIdentityByToken('your-service-token', {
|
||||
tagConnection: true,
|
||||
statefullIdentity: true
|
||||
});
|
||||
|
||||
console.log('🎉 Connected as:', identity.name);
|
||||
```
|
||||
|
||||
In this function, the `getIdentityByToken` method authenticates using a service token and acquires an identity object that includes user details and security claims.
|
||||
## 🔐 Authentication
|
||||
|
||||
### Interacting with Cloudly Features
|
||||
|
||||
#### Image Management
|
||||
|
||||
Image management is one of the key features supported by the API Client. You can create, upload, and manage Docker images easily within your cloud ecosystem:
|
||||
### Service Token Authentication
|
||||
|
||||
```typescript
|
||||
async function manageImages(client: CloudlyApiClient, identity) {
|
||||
// Creating a new image
|
||||
const newImage = await client.images.createImage({
|
||||
name: 'my_new_image',
|
||||
description: 'A test image'
|
||||
});
|
||||
|
||||
console.log(`Created image:`, newImage);
|
||||
|
||||
// Uploading an image version
|
||||
const imageStream = fetchYourImageStreamHere(); // Provide the source image stream
|
||||
await newImage.pushImageVersion('1.0.0', imageStream);
|
||||
console.log('Image version uploaded successfully.');
|
||||
}
|
||||
|
||||
await manageImages(cloudlyClient, identity);
|
||||
|
||||
// Helper function for obtaining image stream (implement accordingly)
|
||||
function fetchYourImageStreamHere() {
|
||||
// Logic to fetch and return a readable stream for your image
|
||||
return new ReadableStream<Uint8Array>();
|
||||
}
|
||||
// Authenticate using a service token
|
||||
const identity = await client.getIdentityByToken(serviceToken, {
|
||||
tagConnection: true, // Tag this connection with the identity
|
||||
statefullIdentity: true // Maintain state across reconnections
|
||||
});
|
||||
```
|
||||
|
||||
In this example, the `manageImages` function underscores the typical workflow of creating an image entry within Cloudly and then proceeding to upload a specific version using the `pushImageVersion` method.
|
||||
|
||||
#### Cluster Configuration
|
||||
|
||||
Another powerful capability is managing clusters, which allows for orchestrating and configuring Docker Swarm clusters:
|
||||
### Identity Management
|
||||
|
||||
```typescript
|
||||
async function configureCluster(client: CloudlyApiClient, identity) {
|
||||
// Fetching cluster configuration
|
||||
const clusterConfig = await client.getClusterConfigFromCloudlyByIdentity(identity);
|
||||
console.log(`Cluster configuration retrieved:`, clusterConfig);
|
||||
}
|
||||
// Get current identity
|
||||
const currentIdentity = client.identity;
|
||||
|
||||
await configureCluster(cloudlyClient, identity);
|
||||
// Check permissions
|
||||
if (currentIdentity.permissions.includes('cluster:write')) {
|
||||
// Perform cluster operations
|
||||
}
|
||||
```
|
||||
|
||||
The `getClusterConfigFromCloudlyByIdentity` method retrieved the configuration needed to set up and manage your clusters within the multi-cloud environment.
|
||||
## 📚 Core Operations
|
||||
|
||||
### Advanced Communication via Typed Sockets
|
||||
|
||||
The API client leverages `TypedRequest` and `TypedSocket` from the `@api.global` family, enabling statically-typed, real-time communication. Here's an example demonstrating socket integration:
|
||||
### 🐳 Image Management
|
||||
|
||||
```typescript
|
||||
async function configureSocketCommunication(client: CloudlyApiClient) {
|
||||
client.configUpdateSubject.subscribe({
|
||||
next: (configData) => {
|
||||
console.log('Received configuration update:', configData);
|
||||
}
|
||||
});
|
||||
// Create an image entry
|
||||
const image = await client.images.createImage({
|
||||
name: 'my-app',
|
||||
description: 'Production application image'
|
||||
});
|
||||
|
||||
client.serverActionSubject.subscribe({
|
||||
next: (actionRequest) => {
|
||||
console.log('Server action requested:', actionRequest);
|
||||
}
|
||||
});
|
||||
}
|
||||
// Push a new version
|
||||
const imageStream = fs.createReadStream('app.tar');
|
||||
await image.pushImageVersion('2.0.0', imageStream);
|
||||
|
||||
configureSocketCommunication(cloudlyClient);
|
||||
// List all images
|
||||
const images = await client.images.listImages();
|
||||
```
|
||||
|
||||
The client utilizes RxJS `Subject` to enable simple yet powerful handling of incoming socket requests, whereby one can act upon updates and actions as they occur.
|
||||
|
||||
### Integrating Certificates
|
||||
|
||||
Certificate operations, such as obtaining SSL certificates for your domains, are also streamlined using this API client:
|
||||
### 🌐 Cluster Operations
|
||||
|
||||
```typescript
|
||||
async function retrieveCertificate(client: CloudlyApiClient, domainName: string, identity) {
|
||||
const certificate = await client.getCertificateForDomain({
|
||||
domainName: domainName,
|
||||
type: 'ssl',
|
||||
identity: identity
|
||||
});
|
||||
// Get cluster configuration
|
||||
const clusterConfig = await client.getClusterConfigFromCloudlyByIdentity(identity);
|
||||
|
||||
console.log('Retrieved SSL Certificate:', certificate);
|
||||
}
|
||||
|
||||
const yourDomain = 'example.com';
|
||||
await retrieveCertificate(cloudlyClient, yourDomain, identity);
|
||||
// Deploy to cluster
|
||||
await client.deployToCluster({
|
||||
clusterName: 'production',
|
||||
serviceName: 'api-service',
|
||||
image: 'my-app:2.0.0',
|
||||
replicas: 3
|
||||
});
|
||||
```
|
||||
|
||||
This example demonstrates fetching SSL certificates using given domain credentials and an authenticated identity.
|
||||
|
||||
### API Client Cleanup
|
||||
|
||||
When operations are complete and the application is shutting down, it's crucial to gracefully terminate the API client connection:
|
||||
### 🔒 Certificate Management
|
||||
|
||||
```typescript
|
||||
async function cleanup(client: CloudlyApiClient) {
|
||||
await client.stop();
|
||||
console.log('Cloudly API client disconnected gracefully.');
|
||||
}
|
||||
// Request SSL certificate
|
||||
const certificate = await client.getCertificateForDomain({
|
||||
domainName: 'api.example.com',
|
||||
type: 'ssl',
|
||||
identity: identity
|
||||
});
|
||||
|
||||
await cleanup(cloudlyClient);
|
||||
// Use certificate in your application
|
||||
console.log('Certificate:', certificate.cert);
|
||||
console.log('Private Key:', certificate.key);
|
||||
```
|
||||
|
||||
By invoking the `stop` method, the API client securely terminates its connection to ensure no resources are left hanging, preventing potential memory leaks.
|
||||
### 🔐 Secret Management
|
||||
|
||||
### Miscellaneous Features
|
||||
```typescript
|
||||
// Create secret group
|
||||
const secretGroup = await client.secrets.createSecretGroup({
|
||||
name: 'api-secrets',
|
||||
secrets: [
|
||||
{ key: 'DATABASE_URL', value: 'postgres://...' },
|
||||
{ key: 'REDIS_URL', value: 'redis://...' }
|
||||
]
|
||||
});
|
||||
|
||||
This section would be remiss without mentioning various utility functionalities such as secret management, server actions, DNS configurator options, and more, all underpinned by an intelligently designed API, enriching cloud resource interactivity.
|
||||
// Retrieve secrets
|
||||
const secrets = await client.secrets.getSecretGroup('api-secrets');
|
||||
```
|
||||
|
||||
In conclusion, by employing `@serve.zone/api`, developers gain unparalleled access to a multitude of modular functions pertinent to multi-cloud administration, significantly amplifying productivity and management effectiveness across diverse computing environments.
|
||||
## 🔄 Real-Time Updates
|
||||
|
||||
Subscribe to configuration changes and server actions using RxJS:
|
||||
|
||||
```typescript
|
||||
// Listen for configuration updates
|
||||
client.configUpdateSubject.subscribe({
|
||||
next: (config) => {
|
||||
console.log('📡 Configuration updated:', config);
|
||||
// React to configuration changes
|
||||
}
|
||||
});
|
||||
|
||||
// Handle server action requests
|
||||
client.serverActionSubject.subscribe({
|
||||
next: (action) => {
|
||||
console.log('⚡ Server action:', action.type);
|
||||
// Process server-initiated actions
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
## 🎯 Advanced Usage
|
||||
|
||||
### Streaming Operations
|
||||
|
||||
```typescript
|
||||
// Stream logs from a service
|
||||
const logStream = await client.logs.streamLogs({
|
||||
service: 'api-service',
|
||||
follow: true
|
||||
});
|
||||
|
||||
logStream.on('data', (log) => {
|
||||
console.log(log.message);
|
||||
});
|
||||
```
|
||||
|
||||
### Batch Operations
|
||||
|
||||
```typescript
|
||||
// Deploy multiple services
|
||||
const deployments = await Promise.all([
|
||||
client.deploy({ service: 'frontend', image: 'app:latest' }),
|
||||
client.deploy({ service: 'backend', image: 'api:latest' }),
|
||||
client.deploy({ service: 'worker', image: 'worker:latest' })
|
||||
]);
|
||||
```
|
||||
|
||||
### Error Handling
|
||||
|
||||
```typescript
|
||||
try {
|
||||
await client.start();
|
||||
} catch (error) {
|
||||
if (error.code === 'AUTH_FAILED') {
|
||||
console.error('Authentication failed:', error.message);
|
||||
} else if (error.code === 'CONNECTION_LOST') {
|
||||
console.error('Connection lost, retrying...');
|
||||
await client.reconnect();
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## 🧹 Cleanup
|
||||
|
||||
Always gracefully disconnect when done:
|
||||
|
||||
```typescript
|
||||
// Stop the client connection
|
||||
await client.stop();
|
||||
console.log('✅ Disconnected cleanly');
|
||||
```
|
||||
|
||||
## 🔌 API Reference
|
||||
|
||||
### CloudlyApiClient
|
||||
|
||||
Main client class for interacting with Cloudly.
|
||||
|
||||
#### Constructor Options
|
||||
|
||||
```typescript
|
||||
interface ICloudlyApiClientOptions {
|
||||
registerAs: TClientType; // 'api' | 'cli' | 'web'
|
||||
cloudlyUrl: string; // Full URL including protocol and port
|
||||
}
|
||||
```
|
||||
|
||||
#### Methods
|
||||
|
||||
- `start()` - Initialize connection
|
||||
- `stop()` - Close connection
|
||||
- `getIdentityByToken()` - Authenticate with token
|
||||
- `getClusterConfigFromCloudlyByIdentity()` - Get cluster configuration
|
||||
- `getCertificateForDomain()` - Request SSL certificate
|
||||
- `images` - Image management namespace
|
||||
- `secrets` - Secret management namespace
|
||||
- `clusters` - Cluster management namespace
|
||||
|
||||
## 🎬 Complete Example
|
||||
|
||||
```typescript
|
||||
import { CloudlyApiClient } from '@serve.zone/api';
|
||||
|
||||
async function main() {
|
||||
// Initialize client
|
||||
const client = new CloudlyApiClient({
|
||||
registerAs: 'api',
|
||||
cloudlyUrl: 'https://cloudly.example.com:443'
|
||||
});
|
||||
|
||||
try {
|
||||
// Connect and authenticate
|
||||
await client.start();
|
||||
const identity = await client.getIdentityByToken(process.env.SERVICE_TOKEN, {
|
||||
tagConnection: true,
|
||||
statefullIdentity: true
|
||||
});
|
||||
|
||||
// Create and deploy an image
|
||||
const image = await client.images.createImage({
|
||||
name: 'my-service',
|
||||
description: 'Microservice application'
|
||||
});
|
||||
|
||||
// Push image version
|
||||
const stream = getImageStream(); // Your image stream
|
||||
await image.pushImageVersion('1.0.0', stream);
|
||||
|
||||
// Deploy to cluster
|
||||
await client.deployToCluster({
|
||||
clusterName: 'production',
|
||||
serviceName: 'my-service',
|
||||
image: 'my-service:1.0.0',
|
||||
replicas: 3,
|
||||
environment: {
|
||||
NODE_ENV: 'production'
|
||||
}
|
||||
});
|
||||
|
||||
console.log('✅ Deployment successful!');
|
||||
|
||||
} catch (error) {
|
||||
console.error('❌ Error:', error);
|
||||
} finally {
|
||||
await client.stop();
|
||||
}
|
||||
}
|
||||
|
||||
main();
|
||||
```
|
||||
|
||||
## License and Legal Information
|
||||
|
||||
@@ -199,4 +303,4 @@ Registered at District court Bremen HRB 35230 HB, Germany
|
||||
|
||||
For any legal inquiries or if you require further information, please contact us via email at hello@task.vc.
|
||||
|
||||
By using this repository, you acknowledge that you have read this section, agree to comply with its terms, and understand that the licensing of the code does not imply endorsement by Task Venture Capital GmbH of any derivative works.
|
||||
By using this repository, you acknowledge that you have read this section, agree to comply with its terms, and understand that the licensing of the code does not imply endorsement by Task Venture Capital GmbH of any derivative works.
|
@@ -1,246 +1,342 @@
|
||||
# @serve.zone/cli
|
||||
# @serve.zone/cli 🚀
|
||||
|
||||
A comprehensive command-line interface (CLI) tool for managing multi-cloud environments, leveraging the features of the @serve.zone/cloudly platform. This CLI is crafted to facilitate seamless interactions with complex cloud configurations and deployments, utilizing Docker Swarmkit orchestration.
|
||||
**Command-line interface for Cloudly.** Manage your multi-cloud infrastructure from the terminal with powerful, intuitive commands.
|
||||
|
||||
## Install
|
||||
## 🎯 What is @serve.zone/cli?
|
||||
|
||||
To begin using the `@serve.zone/cli` in your projects, install it via npm by running:
|
||||
The Cloudly CLI brings the full power of the Cloudly platform to your terminal. Whether you're automating deployments, managing secrets, or monitoring services, the CLI provides a streamlined interface for all your cloud operations.
|
||||
|
||||
## ✨ Features
|
||||
|
||||
- **⚡ Fast & Efficient** - Optimized for speed and minimal resource usage
|
||||
- **🔐 Secure Authentication** - Token-based authentication with secure storage
|
||||
- **📝 Intuitive Commands** - Clear, consistent command structure
|
||||
- **🎨 Formatted Output** - Beautiful, readable output with color coding
|
||||
- **🔄 Scriptable** - Perfect for CI/CD pipelines and automation
|
||||
- **📊 Comprehensive** - Access to all Cloudly features from the terminal
|
||||
|
||||
## 🚀 Installation
|
||||
|
||||
### Global Installation (Recommended)
|
||||
|
||||
```bash
|
||||
npm install @serve.zone/cli --save
|
||||
pnpm add -g @serve.zone/cli
|
||||
```
|
||||
|
||||
This command will download the package and integrate it into your project's `node_modules` directory, reflecting the dependency in your `package.json`.
|
||||
### Local Installation
|
||||
|
||||
## Usage
|
||||
|
||||
The `@serve.zone/cli` is a powerful command-line tool aimed at developers and system administrators who are managing containerized applications across various cloud platforms. Through this CLI, users can interact with their cloud infrastructure efficiently, enabling and extending `Cloudly’s` capabilities directly from the terminal.
|
||||
|
||||
### Prerequisites
|
||||
|
||||
Before proceeding to use the `@serve.zone/cli`, ensure your system meets the following prerequisites:
|
||||
- Latest Node.js LTS version installed.
|
||||
- Familiarity with basic command-line operations.
|
||||
- Properly configured cloud service accounts (like Cloudflare, Hetzner), necessary for managing respective services.
|
||||
|
||||
### Setting Up the CLI
|
||||
|
||||
Begin setting up the `Cloudly` instance for CLI usage:
|
||||
```typescript
|
||||
// Import required modules
|
||||
import { Cloudly } from '@serve.zone/cloudly';
|
||||
import * as path from 'path';
|
||||
|
||||
// Define the configuration needed for cloud operations
|
||||
const cloudlyConfig = {
|
||||
cfToken: 'your-cloudflare-token',
|
||||
hetznerToken: 'your-hetzner-token',
|
||||
environment: 'production',
|
||||
publicUrl: 'your-public-url',
|
||||
};
|
||||
|
||||
// Instantiate and start the Cloudly instance
|
||||
const cloudlyInstance = new Cloudly(cloudlyConfig);
|
||||
await cloudlyInstance.start();
|
||||
|
||||
// Log the setup information to ensure it’s correct
|
||||
console.log(`Cloudly is set up at ${cloudlyInstance.config.data.publicUrl}`);
|
||||
```bash
|
||||
pnpm add @serve.zone/cli
|
||||
```
|
||||
|
||||
This snippet initializes a Cloudly instance with necessary environment configuration, setting the groundwork for all subsequent CLI operations.
|
||||
## 🎬 Quick Start
|
||||
|
||||
### Core Operations with the CLI
|
||||
```bash
|
||||
# Configure your Cloudly instance
|
||||
servezone config --url https://cloudly.example.com
|
||||
|
||||
Here's how you leverage various operational commands within the CLI feature:
|
||||
# Login with your service token
|
||||
servezone login --token your-service-token
|
||||
|
||||
#### Managing Clusters
|
||||
# List your clusters
|
||||
servezone clusters list
|
||||
|
||||
To create, list, and delete clusters, you’ll require invoking the `Cloudly` class with its cluster management logic:
|
||||
|
||||
```typescript
|
||||
// Module imports
|
||||
import { Cloudly } from '@serve.zone/cloudly';
|
||||
|
||||
// Async function for cluster management
|
||||
async function manageCluster() {
|
||||
// Prepare configuration
|
||||
const config = {
|
||||
cfToken: 'YOUR_CLOUDFLARE_TOKEN',
|
||||
hetznerToken: 'YOUR_HETZNER_TOKEN',
|
||||
};
|
||||
|
||||
// Initialize Cloudly
|
||||
const cloudlyInstance = new Cloudly(config);
|
||||
await cloudlyInstance.start();
|
||||
|
||||
// Example: Creating a new cluster
|
||||
const cluster = await cloudlyInstance.clusterManager.createCluster({
|
||||
id: 'example_cluster_id',
|
||||
data: {
|
||||
name: 'example_cluster',
|
||||
servers: [],
|
||||
sshKeys: [],
|
||||
}
|
||||
});
|
||||
|
||||
// Log cluster details
|
||||
console.log('Cluster created:', cluster);
|
||||
}
|
||||
```
|
||||
With the above example, you can dynamically manage cluster configurations, ensuring your application components are effectively orchestrated across cloud environments.
|
||||
|
||||
#### Deploying Services
|
||||
|
||||
Deploying cloud-native services within your clusters can be achieved through the CLI:
|
||||
|
||||
```typescript
|
||||
import { Cloudly } from '@serve.zone/cloudly';
|
||||
|
||||
// Function to handle service deployment
|
||||
async function deployService() {
|
||||
const config = {
|
||||
cfToken: 'YOUR_CLOUDFLARE_TOKEN',
|
||||
hetznerToken: 'YOUR_HETZNER_TOKEN',
|
||||
};
|
||||
|
||||
const cloudlyInstance = new Cloudly(config);
|
||||
await cloudlyInstance.start();
|
||||
|
||||
// Deploy a new service to a specified cluster
|
||||
const newService = {
|
||||
id: 'example_service_id',
|
||||
data: {
|
||||
name: 'example_service',
|
||||
imageId: 'example_image_id',
|
||||
imageVersion: '1.0.0',
|
||||
environment: {},
|
||||
ports: { web: 80 }
|
||||
}
|
||||
};
|
||||
|
||||
// Store service into database and deploy
|
||||
console.log('Deploying service:', newService)
|
||||
await cloudlyInstance.serverManager.deployService(newService);
|
||||
}
|
||||
|
||||
deployService();
|
||||
# Deploy a service
|
||||
servezone deploy --cluster production --image myapp:latest
|
||||
```
|
||||
|
||||
By streamlining your service deployments through CLI, you ensure reproducibility and clarity in development operations.
|
||||
## 🔑 Authentication
|
||||
|
||||
#### Managing Certificates
|
||||
### Initial Setup
|
||||
|
||||
Ensuring secure connections by managing SSL certificates is essential. The CLI aids in this through Let's Encrypt integration:
|
||||
```bash
|
||||
# Set your Cloudly instance URL
|
||||
servezone config --url https://cloudly.example.com
|
||||
|
||||
```typescript
|
||||
import { Cloudly } from '@serve.zone/cloudly';
|
||||
# Authenticate with a service token
|
||||
servezone login --token YOUR_SERVICE_TOKEN
|
||||
|
||||
// Function to acquire a certificate
|
||||
async function getCertificate() {
|
||||
const config = {
|
||||
cfToken: 'YOUR_CLOUDFLARE_TOKEN',
|
||||
hetznerToken: 'YOUR_HETZNER_TOKEN',
|
||||
};
|
||||
|
||||
const cloudlyInstance = new Cloudly(config);
|
||||
await cloudlyInstance.start();
|
||||
|
||||
// Fetch certificate using Let's Encrypt
|
||||
const domainName = 'example.com';
|
||||
const cert = await cloudlyInstance.letsencryptConnector.getCertificateForDomain(domainName);
|
||||
console.log(`Obtained certificate for domain ${domainName}:`, cert);
|
||||
}
|
||||
|
||||
getCertificate();
|
||||
# Or use environment variables
|
||||
export CLOUDLY_URL=https://cloudly.example.com
|
||||
export CLOUDLY_TOKEN=YOUR_SERVICE_TOKEN
|
||||
```
|
||||
|
||||
This process facilitates the automation of SSL certificates provisioning, ensuring high security in your apps.
|
||||
### Managing Profiles
|
||||
|
||||
### Automating Tasks with the CLI
|
||||
```bash
|
||||
# Create a profile for different environments
|
||||
servezone profile create production --url https://prod.cloudly.com
|
||||
servezone profile create staging --url https://stage.cloudly.com
|
||||
|
||||
Task scheduling is a feature you can utilize to automate recurring processes. Here’s an example of how `@serve.zone/cli` accomplishes task scheduling:
|
||||
# Switch between profiles
|
||||
servezone profile use production
|
||||
|
||||
```typescript
|
||||
import { TaskBuffer } from '@push.rocks/taskbuffer';
|
||||
|
||||
// Schedule a task to run every day
|
||||
const dailyTask = new TaskBuffer({
|
||||
schedule: '0 0 * * *', // Using cron schedule
|
||||
taskFunction: async () => {
|
||||
console.log('Performing daily backup check...');
|
||||
// Include backup logic here
|
||||
},
|
||||
});
|
||||
|
||||
// Initiate task scheduling
|
||||
dailyTask.start();
|
||||
# List all profiles
|
||||
servezone profile list
|
||||
```
|
||||
|
||||
Scheduled tasks like periodic maintenance, data synchronization, or backups ensure you keep your cloud environment robust and reliable.
|
||||
## 📚 Core Commands
|
||||
|
||||
### Integrating Third-Party APIs
|
||||
### 🌐 Cluster Management
|
||||
|
||||
Expand the scope of your applications with API integrations offered via `@serve.zone/cli`:
|
||||
```bash
|
||||
# List all clusters
|
||||
servezone clusters list
|
||||
|
||||
```typescript
|
||||
import { Cloudly } from '@serve.zone/cloudly';
|
||||
# Get cluster details
|
||||
servezone clusters info production-cluster
|
||||
|
||||
// Function to send notifications
|
||||
async function sendNotification() {
|
||||
const cloudlyConfig = {
|
||||
cfToken: 'your-cloudflare-token',
|
||||
hetznerToken: 'your-hetzner-token',
|
||||
};
|
||||
# Create a new cluster
|
||||
servezone clusters create \
|
||||
--name production-cluster \
|
||||
--region eu-central \
|
||||
--nodes 3
|
||||
|
||||
const cloudly = new Cloudly(cloudlyConfig);
|
||||
await cloudly.start();
|
||||
# Scale a cluster
|
||||
servezone clusters scale production-cluster --nodes 5
|
||||
|
||||
// Configure and send push notification
|
||||
await cloudly.externalApiManager.sendPushMessage({
|
||||
deviceToken: 'some_device_token',
|
||||
message: 'Hello from Cloudly!',
|
||||
});
|
||||
}
|
||||
|
||||
sendNotification();
|
||||
# Delete a cluster
|
||||
servezone clusters delete staging-cluster
|
||||
```
|
||||
|
||||
API integrations via the CLI extend Cloudly’s reach, enabling comprehensive service interconnections.
|
||||
### 🐳 Service Deployment
|
||||
|
||||
### Security and Access Management
|
||||
```bash
|
||||
# Deploy a service
|
||||
servezone deploy \
|
||||
--cluster production \
|
||||
--name api-service \
|
||||
--image myapp:2.0.0 \
|
||||
--replicas 3 \
|
||||
--port 80:3000
|
||||
|
||||
Effective identity management is possible through `@serve.zone/cli`. Manage user roles, token validations, and more:
|
||||
# Update a service
|
||||
servezone service update api-service \
|
||||
--image myapp:2.1.0 \
|
||||
--replicas 5
|
||||
|
||||
```typescript
|
||||
import { Cloudly } from '@serve.zone/cloudly';
|
||||
# Scale a service
|
||||
servezone service scale api-service --replicas 10
|
||||
|
||||
// Configuring and verifying identity
|
||||
async function authenticateUser() {
|
||||
const cloudlyConfig = {
|
||||
cfToken: 'your-cloudflare-token',
|
||||
hetznerToken: 'your-hetzner-token',
|
||||
};
|
||||
|
||||
const cloudly = new Cloudly(cloudlyConfig);
|
||||
await cloudly.start();
|
||||
|
||||
// Sample user credentials
|
||||
const userIdentity = {
|
||||
userId: 'unique_user_id',
|
||||
jwt: 'user_jwt_token',
|
||||
};
|
||||
|
||||
// Validate identity
|
||||
const isValid = cloudly.authManager.validateIdentity(userIdentity);
|
||||
console.log(`Is user identity valid? ${isValid}`);
|
||||
}
|
||||
|
||||
authenticateUser();
|
||||
# Remove a service
|
||||
servezone service remove api-service
|
||||
```
|
||||
|
||||
The applications of identity validation streamline operational security and enforce access controls across your systems.
|
||||
### 🔐 Secret Management
|
||||
|
||||
These examples offer a glimpse into the vast potential of @serve.zone/cli, which combines automation, security, and flexibility for state-of-the-art cloud management. You are encouraged to build upon this documentation to harness Cloudly's full capabilities in your infrastructure and process ecosystems. Let the CLI transform your cloud management experience with precision and adaptability.
|
||||
```bash
|
||||
# Create a secret
|
||||
servezone secrets create \
|
||||
--name database-url \
|
||||
--value "postgres://user:pass@host/db"
|
||||
|
||||
# Create a secret group
|
||||
servezone secrets create-group \
|
||||
--name api-secrets \
|
||||
--secret DATABASE_URL=postgres://... \
|
||||
--secret REDIS_URL=redis://...
|
||||
|
||||
# List secrets
|
||||
servezone secrets list
|
||||
|
||||
# Get secret value
|
||||
servezone secrets get database-url
|
||||
|
||||
# Delete a secret
|
||||
servezone secrets delete old-secret
|
||||
```
|
||||
|
||||
### 📦 Image Management
|
||||
|
||||
```bash
|
||||
# List images
|
||||
servezone images list
|
||||
|
||||
# Push a new image
|
||||
servezone images push \
|
||||
--name myapp \
|
||||
--version 2.0.0 \
|
||||
--file ./myapp.tar
|
||||
|
||||
# Tag an image
|
||||
servezone images tag myapp:2.0.0 myapp:latest
|
||||
|
||||
# Delete an image
|
||||
servezone images delete myapp:1.0.0
|
||||
```
|
||||
|
||||
### 📊 Monitoring & Logs
|
||||
|
||||
```bash
|
||||
# View service logs
|
||||
servezone logs api-service
|
||||
|
||||
# Follow logs in real-time
|
||||
servezone logs api-service --follow
|
||||
|
||||
# Filter logs
|
||||
servezone logs api-service --since 1h --grep ERROR
|
||||
|
||||
# Get service status
|
||||
servezone service status api-service
|
||||
|
||||
# Monitor cluster health
|
||||
servezone clusters health production-cluster
|
||||
```
|
||||
|
||||
### 🔧 DNS Management
|
||||
|
||||
```bash
|
||||
# List DNS records
|
||||
servezone dns list --domain example.com
|
||||
|
||||
# Create a DNS record
|
||||
servezone dns create \
|
||||
--domain example.com \
|
||||
--name api \
|
||||
--type A \
|
||||
--value 192.168.1.1
|
||||
|
||||
# Update a DNS record
|
||||
servezone dns update api.example.com --value 192.168.1.2
|
||||
|
||||
# Delete a DNS record
|
||||
servezone dns delete old.example.com
|
||||
```
|
||||
|
||||
## 🎯 Advanced Usage
|
||||
|
||||
### Environment Variables
|
||||
|
||||
```bash
|
||||
# Set environment variables for a service
|
||||
servezone deploy \
|
||||
--name api-service \
|
||||
--env NODE_ENV=production \
|
||||
--env PORT=3000 \
|
||||
--env DATABASE_URL=@secret:database-url
|
||||
```
|
||||
|
||||
### Configuration Files
|
||||
|
||||
Create a `cloudly.yaml` file:
|
||||
|
||||
```yaml
|
||||
cluster: production
|
||||
service:
|
||||
name: api-service
|
||||
image: myapp:latest
|
||||
replicas: 3
|
||||
ports:
|
||||
- 80:3000
|
||||
environment:
|
||||
NODE_ENV: production
|
||||
DATABASE_URL: "@secret:database-url"
|
||||
```
|
||||
|
||||
Deploy using the config file:
|
||||
|
||||
```bash
|
||||
servezone deploy --config cloudly.yaml
|
||||
```
|
||||
|
||||
### Batch Operations
|
||||
|
||||
```bash
|
||||
# Deploy multiple services
|
||||
servezone deploy --config services/*.yaml
|
||||
|
||||
# Update all services in a namespace
|
||||
servezone service update --namespace api --image-tag v2.0.0
|
||||
|
||||
# Delete all staging resources
|
||||
servezone cleanup --environment staging
|
||||
```
|
||||
|
||||
## 🔄 CI/CD Integration
|
||||
|
||||
### GitHub Actions
|
||||
|
||||
```yaml
|
||||
- name: Deploy to Cloudly
|
||||
run: |
|
||||
servezone config --url ${{ secrets.CLOUDLY_URL }}
|
||||
servezone login --token ${{ secrets.CLOUDLY_TOKEN }}
|
||||
servezone deploy \
|
||||
--cluster production \
|
||||
--name api-service \
|
||||
--image myapp:${{ github.sha }}
|
||||
```
|
||||
|
||||
### GitLab CI
|
||||
|
||||
```yaml
|
||||
deploy:
|
||||
script:
|
||||
- servezone config --url $CLOUDLY_URL
|
||||
- servezone login --token $CLOUDLY_TOKEN
|
||||
- servezone deploy --config cloudly.yaml
|
||||
```
|
||||
|
||||
## 🎨 Output Formats
|
||||
|
||||
```bash
|
||||
# JSON output for scripting
|
||||
servezone clusters list --output json
|
||||
|
||||
# YAML output
|
||||
servezone service info api-service --output yaml
|
||||
|
||||
# Table output (default)
|
||||
servezone images list --output table
|
||||
|
||||
# Quiet mode (IDs only)
|
||||
servezone clusters list --quiet
|
||||
```
|
||||
|
||||
## 🛠️ Troubleshooting
|
||||
|
||||
```bash
|
||||
# Enable debug output
|
||||
servezone --debug clusters list
|
||||
|
||||
# Check CLI version
|
||||
servezone version
|
||||
|
||||
# Test connection
|
||||
servezone ping
|
||||
|
||||
# View configuration
|
||||
servezone config show
|
||||
|
||||
# Clear cache and credentials
|
||||
servezone logout --clear-cache
|
||||
```
|
||||
|
||||
## 📝 Command Reference
|
||||
|
||||
```bash
|
||||
servezone --help # Show all commands
|
||||
servezone <command> --help # Show command-specific help
|
||||
servezone clusters --help # Show cluster commands
|
||||
servezone service --help # Show service commands
|
||||
servezone secrets --help # Show secret commands
|
||||
```
|
||||
|
||||
## 🔌 Shell Completion
|
||||
|
||||
Enable tab completion for your shell:
|
||||
|
||||
```bash
|
||||
# Bash
|
||||
servezone completion bash > /etc/bash_completion.d/servezone
|
||||
|
||||
# Zsh
|
||||
servezone completion zsh > ~/.zsh/completions/_servezone
|
||||
|
||||
# Fish
|
||||
servezone completion fish > ~/.config/fish/completions/servezone.fish
|
||||
```
|
||||
|
||||
## License and Legal Information
|
||||
|
||||
@@ -259,4 +355,4 @@ Registered at District court Bremen HRB 35230 HB, Germany
|
||||
|
||||
For any legal inquiries or if you require further information, please contact us via email at hello@task.vc.
|
||||
|
||||
By using this repository, you acknowledge that you have read this section, agree to comply with its terms, and understand that the licensing of the code does not imply endorsement by Task Venture Capital GmbH of any derivative works.
|
||||
By using this repository, you acknowledge that you have read this section, agree to comply with its terms, and understand that the licensing of the code does not imply endorsement by Task Venture Capital GmbH of any derivative works.
|
Reference in New Issue
Block a user