Skip to main content

Environment & Resource Management

This article describes how to manage CloudBase environments and their internal resources via Tencent Cloud APIs, including environment creation and billing, cloud function deployment, domain configuration, database management, and monitoring & logs.

Create Environment & Billing#

Create environments for new tenants and manage their billing and quotas.

Steps#

Step 1: Confirm Preconditions

Before creation, confirm account status and available resources via the following APIs:

Step 2: Call CreateEnv to Create Environment

Call the CreateEnv API. The API automatically places an order and deducts payment. Key parameters:

ParameterDescription
PackageIdPlan ID, e.g., baas_personal; can be obtained via DescribeBaasPackageList
AliasEnvironment alias
ResourcesResource types to enable in this batch, see table below
PeriodPurchase duration (months, default 1)
TagsEnvironment tags, used for permission isolation and resource grouping; recommended to tag by tenant ID or business line

Resources optional values:

ValueDescription
flexdbDocument database (NoSQL), compatible with MongoDB-style API
storageObject storage (Cloud Storage)
functionCloud functions (including HTTP cloud functions)

Select from the above types based on business needs; other resources (e.g., MySQL) can be enabled on demand after environment creation.

Step 3: Wait for Provisioning and Confirm Status

Environment provisioning is asynchronous. Poll DescribeEnvs until the environment status becomes available. After confirmation, you can further query usage and billing:

Quota Note: COS resources and cloud functions (non-Shanghai regions) have account-level or region-level quota limits. When planning to create a large number of environments in batch, it is recommended to contact the CloudBase team for quota evaluation in advance.

Environment Lifecycle API Reference#


Deploy Backend Services for Tenants#

Requests go through the HTTP Access Service unified entry point, which forwards to corresponding cloud functions based on routing. Supports REST APIs, WebSocket long connections, and container image deployment.

Complete call flow from getting environment info to externally accessible:

Steps#

Step 1: Create Log Configuration

  1. Call CreateLogset to create a log set, get the returned LogsetId
  2. Call CreateTopic to create a log topic, pass in LogsetId from the previous step, get the returned TopicId
  3. Create a log role (for log delivery): In the CAM Role Console, create a role, select Tencent Cloud Product Service, select scf and cls as the role carrier, associate a custom policy (only grant log write permissions to prevent cross-environment log privilege escalation), record the role name (e.g., SCF_CLSWriteOnly), to be used when configuring or creating functions later

When creating functions later, pass LogsetId / TopicId as ClsLogsetId / ClsTopicId, and the role name as Role.

Step 2: Package and Upload Code

Package the function directory as a ZIP and Base64 encode it, with a 50 MB limit. For larger files, upload to COS first, then reference via CosBucketName / CosObjectName / CosBucketRegion (bucket name does not include the -appid suffix, path starts with /).

Step 3: Create or Update Function

Call CreateFunction or UpdateFunctionCode. Required parameters: Type: 'HTTP', Namespace (CloudBase environment ID), Handler. Also pass the log configuration from Step 1: ClsLogsetId, ClsTopicId, and the log role name Role. WebSocket functions additionally require ProtocolType: 'WS'; see WebSocket Functions.

Step 4: Wait for Function to be Ready

Poll ListFunctions until Status = Active.

Step 5: Configure HTTP Access Service Route

Call CreateHTTPServiceRoute. This API requires EnvId and a Domain object; Domain contains domain configuration and Routes routing rules. Example structure:

{
"EnvId": "<env-id>",
"Domain": {
"Domain": "api.example.com",
"AccessType": "DIRECT",
"Protocol": "HTTP_AND_HTTPS",
"CertId": "<cert-id>",
"Enable": true,
"Routes": [
{
"Path": "/api/v1",
"UpstreamResourceType": "<upstream-resource-type>",
"UpstreamResourceName": "<resource-name>",
"EnableSafeDomain": false,
"EnablePathTransmission": false,
"Enable": true
}
]
}
}

Note: The Type numeric type in the old GW API (e.g., 6 in historical examples) has been changed to the UpstreamResourceType enum field in the new API; do not write magic numbers directly. Fill in the corresponding enum value based on the current upstream resource type. CloudBase Run services in official current examples use "CBR".

If you only need to create domain info first, you can pass Domain without Routes.

Step 6: Confirm Route is Effective

Call DescribeHTTPServiceRoute, pass EnvId, and optionally use Filters to query precisely by Domain, Path. Check the returned Domains[].Status and Domains[].DNSStatus:

  • Status = SUCCESS: Configuration has taken effect
  • DNSStatus = SUCCESS: DNS has taken effect
  • Status = PROCESSING: Still need to continue polling

After the API returns success, there may still be a short delay in route delivery. It is recommended to perform an actual HTTP/HTTPS probe.

(Optional) Incremental Route Maintenance

The above Cloud APIs can be invoked via the Management SDK commonService in a unified manner; you can also directly use the Tencent Cloud SDK 3.0 to call Cloud Function APIs, supporting Python, Java, PHP, Go, Node.js, .NET, C++, Ruby, and other languages.

Cloud Function API Reference#

Pass Namespace as the CloudBase environment ID to operate functions under the corresponding environment; see Cloud Function API Overview for complete parameters.

In addition, the following two parameters need to be passed when calling SCF Cloud Function APIs:

  • Stamp: Fixed value "MINI_QCBASE"
  • Role: Cloud Function execution role name
Security Notice

If you are a regular user (single-environment account), you can directly pass the default role TCB_QcsRole without additional configuration.

If you are a platform customer managing multiple small tenants via environment separation, using TCB_QcsRole poses a cross-environment privilege escalation risk. It is recommended to create an independent custom CAM role for each environment:

  1. Go to CAM Role Console to create a role;
  2. Select "Tencent Cloud Product Service" as the role carrier;
  3. Check SCF (Cloud Function) and CLS (Log Service) for service authorization;
  4. Associate a custom policy (only grant log write permissions to prevent cross-environment log privilege escalation);
  5. Record the role name (e.g., SCF_CLSWriteOnly), and pass it as the value of the Role parameter.

WebSocket Functions#

WebSocket functions require additional parameters when calling CreateFunction based on regular HTTP functions:

ProtocolType: 'WS',
ProtocolParams: {
WSParams: {
IdleTimeOut: 7200 // Connection idle timeout, 10-7200 seconds
}
},
Timeout: 7200 // Function timeout, must >= IdleTimeOut, 15-7200 seconds

Note: The function timeout must be >= the idle timeout, otherwise creation will fail.

Concurrency (WebSocket recommendation: session-based; regular HTTP: request-based):

InstanceConcurrencyConfig: {
DynamicEnabled: 'FALSE',
MaxConcurrency: 10,
Type: 'Session-Based', // WebSocket: Session-Based; HTTP: Request-Based
SessionConfig: {
SessionExpireTime: 7200,
IdleSessionExpireTime: 3600,
SessionDestroyStrategy: 'IdleDestroy',
SessionKeyType: 'Header',
SessionKey: 'x-ws-session'
},
InstanceIsolationEnabled: 'FALSE'
}

Container Image Deployment#

Image deployment is suitable for scenarios with complex dependencies, large size, or custom runtime requirements. You can also deploy via CLI.

Preconditions:

  1. Authorize image pull: Authorize the policy QcloudAccessForSCFRoleInPullImage for the Cloud Function role, one-time operation: Click to Authorize
  2. Prepare image repository: Create a repository in Tencent Cloud Container Registry TCR; refer to Get Access Credentials and Push Image
  3. Image requirements: Linux-based amd64 image, the container listens on port 9000

When building on Apple Silicon Mac or other ARM architecture machines, you must add --platform linux/amd64, otherwise the function will fail to start after deployment due to architecture mismatch:

docker build --platform linux/amd64 -t your-image-name .

During deployment, use Code.ImageConfig in CreateFunction instead of Code.ZipFile:

Code: {
ImageConfig: {
ImageType: 'personal', // Personal edition repository
ImageUri: 'ccr.ccs.tencentyun.com/your-ns/your-image:tag',
// RegistryId: '' // Enterprise edition repository needs to fill in
}
}

Reference: ImageConfig Parameter Description


Domains & Security Domains#

Bind custom domains and certificates for tenant environments' static hosting or HTTP access services; configure the frontend security domain whitelist that can initiate CloudBase requests.

Steps#

Step 1: Apply for SSL Certificate

Before binding an HTTPS domain, you need to apply for or upload a certificate in the SSL Certificate Console, and obtain the CertId.

Step 2: Bind Custom Domain

Select the corresponding API based on usage:

Step 3: Configure DNS CNAME

After creating the HTTP Access Service domain, you can get the CNAME target domain provided by CloudBase from the returned Domains[].Cname via DescribeHTTPServiceRoute; handle static hosting according to the corresponding API return result. If using Tencent Cloud DNSPod, you can operate via API:

  1. Query whether the CNAME record already exists: DescribeRecordFilterList
  2. Create record if it does not exist: CreateRecord, set Value to the CNAME target obtained in the previous step

After both domain binding and DNS resolution are complete, continue polling Domains[].DNSStatus until SUCCESS.

Step 4: Configure Security Domain (Optional)

Security domains control which frontend domains can initiate requests to CloudBase. Add the tenant's frontend domain to the whitelist:

Domain API Reference#


Database#

Each environment provides two types of database capabilities, with isolation between tenants by environment.

  • Document Database (FlexDB / NoSQL): Store by collection and document, compatible with MongoDB-style API, supports collection CRUD and index management. Enable by selecting flexdb in Resources when creating the environment.
  • Relational Database (MySQL): Supports standard SQL and DDL, table structure management; frontend can access via Web SDK with Supabase-style API.
  • Permissions & Security: Supports database-level ACL and table-level security rules to control read/write scope and row-level access.

Document Database#

Steps#

Step 1: Enable

Select flexdb in Resources when creating the environment to enable it together, no additional operations needed.

Step 2: Create Collection

Call CreateTable to create a collection, pass EnvId and the collection name.

Step 3: Manage Indexes and Permissions

  • Query or modify collection indexes: UpdateTable
  • Configure read/write permissions and security rules to control tenant data access scope

Document Database API Reference#

MySQL#

Steps#

Step 1: Enable MySQL

Call CreateMySQL to enable it. The API is asynchronous, poll for the result via the following APIs:

Step 2: Initialize Table Structure

After enablement is complete, execute DDL statements such as table creation and index creation via RunSql.

Step 3: Configure Account and Access Permissions

MySQL API Reference#

Lifecycle Management (tcb.tencentcloudapi.com):

Account Management (cynosdb.tencentcloudapi.com):

Connection & Cluster (cynosdb.tencentcloudapi.com):

Backup (cynosdb.tencentcloudapi.com):


Monitoring & Logs#

View monitoring curves and HTTP access service running status by environment, and search CLS logs for troubleshooting and usage analysis.

Steps#

Step 1: Configure Logs

Before searching logs, you need to complete log configuration and create a log role. If already configured, skip this step. See Deploy Backend Services - Step 1: Create Log Configuration.

  1. Call CreateLogset to create a log set, get LogsetId
  2. Call CreateTopic to create a log topic, get TopicId
  3. Create a log role (for log delivery): In the CAM Role Console, create a role, select Tencent Cloud Product Service, select scf and cls as the role carrier, associate a custom policy (only grant log write permissions to prevent cross-environment log privilege escalation), record the role name (e.g., SCF_CLSWriteOnly), to be used when configuring or creating functions later
  4. Pass ClsLogsetId, ClsTopicId, Role when creating functions

Step 2: Query Monitoring Data

Select the appropriate granularity as needed:

Step 3: Search Logs

Call SearchLog, pass:

  • TopicId: The log topic ID configured when creating the function
  • Time range
  • Query: Follow CLS syntax, e.g., SCF_FunctionName:function-name

Up to 100 entries are returned per request, pagination with cursors is supported (up to 10,000 entries).

Monitoring & Logs API Reference#

Log Role Permissions & Multi-tenancy Isolation#

Single-tenant scenario: You can use the preset policy QcloudCLSFullAccess, which grants read/write permissions for all CLS resources.

Multi-tenant scenario: The preset policy QcloudCLSFullAccess does not distinguish between log sets or log topics. When managing multiple tenant environments under the same account, roles in any environment can read and write logs of other environments, posing a cross-environment privilege escalation risk.

If you need log isolation between environments, you should use a custom policy:

Option 1: Shared Role + Write-only Permissions (Recommended, balances security and management cost)

All environments share one role, only granting log write permissions to prevent cross-environment log reading:

{
"version": "2.0",
"statement": [
{
"effect": "allow",
"action": ["cls:pushLog", "cls:UploadLog"],
"resource": "*"
},
{
"effect": "allow",
"action": ["cls:DescribeTopics", "cls:DescribeLogsets"],
"resource": "*"
}
]
}

DescribeTopics and DescribeLogsets are verification permissions required when deploying cloud functions, and only return metadata of log topics, not log content.

Option 2: Independent Role + Scoped Resources per Environment (Strictest Isolation)

Create an independent role for each environment, restrict to the specific TopicId in the policy via resource six-segment format:

{
"version": "2.0",
"statement": [
{
"effect": "allow",
"action": ["cls:pushLog", "cls:UploadLog"],
"resource": "qcs::cls:<region>::topic/<TopicId-of-this-environment>"
},
{
"effect": "allow",
"action": ["cls:DescribeTopics", "cls:DescribeLogsets"],
"resource": "*"
}
]
}
OptionApplicable ScenarioIsolation GranularityManagement Cost
QcloudCLSFullAccessSingle tenant, or all environments belong to the same userNo isolationLowest
Shared Role + Write-onlyMulti-tenant, need to prevent cross-environment log readingPrevent read, not prevent writeLow
Per-environment Independent Role + Scoped ResourcesMulti-tenant, need strict environment isolationBoth read and write isolatedHigher (can be automated)