Skip to main content

Environment and Resource Management

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

CloudBase Management API Overview

All CloudBase management APIs are available in the CloudBase API Overview, with multi-language SDK support including Python, Java, Go, Node.js, PHP, .NET, C++, and Ruby.

Create Environment and Billing

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

Steps

Step 1: Verify prerequisites

Before creating, confirm your account status and available resources with the following APIs:

Step 2: Call CreateEnv to create an environment

Call CreateEnv. The API automatically places an order and charges the account. Key parameters:

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

Available values for Resources:

ValueDescription
flexdbDocument database (NoSQL)
storageObject storage (Cloud Storage)
functionCloud Function (including HTTP cloud functions)
postgresqlPostgreSQL database (relational database, supports SQL)

Select the types you need. Other resources (such as MySQL) can be enabled on demand after the environment is created.

Step 3: Wait for provisioning and confirm status

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

Quota notes: Both COS resources and Cloud Functions (in non-Shanghai regions) have account-level or region-level quota limits. If you plan to create a large number of environments in batch, we recommend a quota assessment with the CloudBase team in advance.

Environment Lifecycle API Reference

High-volume scenarios: Environment Pool API

If your platform needs to create CloudBase environments rapidly at scale (e.g., SaaS multi-tenant, C-end platforms with large user bases) and has high throughput or response-time requirements for environment provisioning, we offer an Environment Pool API. It supports pre-creating a pool of environments and allocating them on demand, enabling fast provisioning of massive numbers of CloudBase environments.

This capability requires allowlisting — please apply via the CloudBase Help Center or contact your account manager.


Deploy Backend Services for Tenants

Requests go through a unified HTTP Access Service entry and are routed to the corresponding cloud function. REST APIs, WebSocket long connections, and container image deployment are all supported.

The complete flow from fetching environment info to being externally accessible:

Steps

Step 1: Create log configuration

  1. Call CreateLogset to create a log set and obtain the returned LogsetId
  2. Call CreateTopic to create a log topic, passing the LogsetId from the previous step, and obtain the returned TopicId
  3. Create a log role (for log delivery): in the CAM role console create a role, select Tencent Cloud Product Service, choose scf and cls as the role carriers, attach a custom policy (grant write-only permission on logs to prevent cross-environment log privilege escalation), record the role name (e.g. SCF_CLSWriteOnly), and use it later during configuration or function creation

Later, when creating functions, pass LogsetId / TopicId as ClsLogsetId / ClsTopicId and use the role name as Role.

Step 2: Package and upload code

Zip the function directory and Base64-encode it, with an upper limit of 50 MB. If your package exceeds that, upload it to COS first and reference it via CosBucketName / CosObjectName / CosBucketRegion (the bucket name does not include the -appid suffix, and the path starts with /).

Step 3: Create or update the function

Call CreateFunction or UpdateFunctionCode. Required parameters: Type: 'HTTP', Namespace (the 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 until the function is ready

Poll ListFunctions until Status = Active.

Step 5: Configure the HTTP Access Service route

Call CreateHTTPServiceRoute. This API requires EnvId and a Domain object. Domain contains the domain configuration and the 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 numeric Type field in the old GWAPI (e.g. 6 in historical examples) has been replaced with the enum field UpstreamResourceType in the new API — no more magic numbers. Fill in the corresponding enum value for the current upstream resource type. The current official example uses "CBR" for CloudBase Run services.

If you only want to create the domain first, you can pass Domain without Routes.

Step 6: Confirm the route is in effect

Call DescribeHTTPServiceRoute with EnvId, and optionally filter by Domain and Path via Filters. Check Domains[].Status and Domains[].DNSStatus in the response:

  • Status = SUCCESS: configuration is in effect
  • DNSStatus = SUCCESS: DNS is in effect
  • Status = PROCESSING: keep polling

After the API returns success, route propagation may still take a moment; we recommend an additional HTTP / HTTPS probe to verify.

(Optional) Incrementally maintain routes

The above cloud APIs can be invoked uniformly through the Management SDK commonService. You can also call the Cloud Function APIs directly with Tencent Cloud SDK 3.0, which supports Python, Java, PHP, Go, Node.js, .NET, C++, Ruby, and more.

Cloud Function API Reference

Pass the CloudBase environment ID as Namespace to operate on functions in that environment. Full parameters: Cloud Function API Overview.

Additionally, when calling SCF Cloud Function APIs, pass these two parameters:

  • Stamp: fixed value "MINI_QCBASE"
  • Role: cloud function execution role name
Security notice

If you are a regular user (single-environment account), pass the default role TCB_QcsRole directly, no extra setup required.

If you are a platform customer managing multiple sub-tenants through environments, using TCB_QcsRole risks cross-environment privilege escalation. We recommend creating a dedicated custom CAM role per environment:

  1. Go to the CAM role console to create the role.
  2. Choose "Tencent Cloud Product Service" as the role carrier.
  3. Under service authorization, select SCF (Cloud Function) and CLS (Cloud Log Service).
  4. Attach a custom policy (grant write-only log permission 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

Building on regular HTTP functions, WebSocket functions require passing the following additional parameters to CreateFunction:

ProtocolType: 'WS',
ProtocolParams: {
WSParams: {
IdleTimeOut: 7200 // connection idle timeout, 10–7200 seconds
}
},
Timeout: 7200 // function timeout, must be >= IdleTimeOut, 15–7200 seconds

Note: the function timeout must be ≥ the idle timeout, otherwise creation will fail.

Multiple concurrency per instance (Session-Based is recommended for WebSocket; Request-Based for regular HTTP):

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

Container Image Deployment

Image deployment suits complex dependencies, large sizes, or custom runtimes. You can also deploy via the CLI.

Prerequisites:

  1. Grant permission to pull images: attach the policy QcloudAccessForSCFRoleInPullImage to the cloud function role. One-time setup: click to grant.
  2. Prepare an image repository: create a repository on Tencent Container Registry (TCR). See obtain access credentials and push images.
  3. Image requirements: Linux amd64 image with the container listening on port 9000.

When building on an Apple Silicon Mac or another ARM host, 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 .

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

Code: {
ImageConfig: {
ImageType: 'personal', // personal repository
ImageUri: 'ccr.ccs.tencentyun.com/your-ns/your-image:tag',
// RegistryId: '' // required for enterprise repositories
}
}

Reference: ImageConfig parameter description

CloudBase Access APIs


Domains and Secure Domains

Bind custom domains and certificates to the tenant environment's static hosting or HTTP Access Service, and configure the front-end secure domain allow-list for making CloudBase requests.

Steps

Step 1: Apply for an SSL certificate

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

Step 2: Bind a custom domain

Choose the API based on your use case:

Step 3: Configure DNS CNAME

After creating the HTTP Access Service domain, call DescribeHTTPServiceRoute to obtain the CNAME target provided by CloudBase from Domains[].Cname in the response. For Static Hosting, handle the response of the corresponding API. If you use Tencent Cloud DNSPod, you can operate via API:

  1. Check whether the CNAME record already exists: DescribeRecordFilterList
  2. If not, create the record: CreateRecord, with Value set to the CNAME target obtained above

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

Step 4: Configure secure domains (optional)

Secure domains control which front-end domains are allowed to make requests to CloudBase. Add tenant front-end domains to the allow-list:

Domain API Reference


Databases

Each environment provides two categories of database capabilities, with tenants isolated by environment.

  • Document database (FlexDB / NoSQL): stores data by collections and documents; supports collection CRUD and index management. Enable it by including flexdb in Resources when creating the environment.
  • Relational database (MySQL): supports standard SQL and DDL, and table schema management. The front end can access it via the Web SDK using Supabase-style APIs.
  • Permissions and security: supports database-level ACLs and table-level security rules to control read/write scope and row-level access.

Document Database

Steps

Step 1: Enable

Include flexdb in Resources when creating the environment — no extra action required.

Step 2: Create a collection

Call CreateTable to create a collection, passing 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. This is asynchronous — poll the results with:

Step 2: Initialize schema

Once enabled, use RunSql to execute DDL statements such as creating tables and indexes.

Step 3: Configure accounts and access permissions

MySQL API Reference

Lifecycle management (tcb.tencentcloudapi.com):

Account management (cynosdb.tencentcloudapi.com):

Connection and cluster (cynosdb.tencentcloudapi.com):

Backups (cynosdb.tencentcloudapi.com):


Monitoring and Logs

View monitoring curves and HTTP Access Service running status per environment, and search CLS logs for troubleshooting and usage analysis.

Steps

Step 1: Configure logs

Before searching logs, complete the log setup and create a log role. Skip this step if you have already configured it — see Cloud Function Deployment — Step 1: Create Log Configuration.

  1. Call CreateLogset to create a log set and obtain the LogsetId
  2. Call CreateTopic to create a log topic and obtain the TopicId
  3. Create a log role (for log delivery): in the CAM role console create a role, select Tencent Cloud Product Service, choose scf and cls as the role carriers, attach a custom policy (grant write-only permission to prevent cross-environment log privilege escalation), record the role name (e.g. SCF_CLSWriteOnly), and use it later during configuration or function creation
  4. When creating functions, pass ClsLogsetId, ClsTopicId, and Role

Step 2: Query monitoring data

Pick the granularity you need:

Step 3: Search logs

Call SearchLog with:

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

A single call returns at most 100 records; cursor-based pagination supports up to 10,000 records.

Monitoring and Log API Reference

Log Role Permissions and Multi-Tenant Isolation

Single-tenant scenarios: use the preset policy QcloudCLSFullAccess, which grants full read/write access to CLS resources.

Multi-tenant scenarios: the preset policy QcloudCLSFullAccess does not distinguish between log sets or log topics. When managing multiple tenant environments under the same account, any environment's role can read and write another environment's logs — a cross-environment privilege escalation risk.

For cross-environment log isolation, use a custom policy:

Option A: shared role + write-only permission (recommended, balances security and management cost)

All environments share one role, granted write-only log permission to prevent cross-environment log reads:

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

DescribeTopics and DescribeLogsets are the validation permissions needed during cloud function deployment. They return only log topic metadata — not log content.

Option B: per-environment role + resource-scoped policy (strictest isolation)

Create a dedicated role for each environment and scope the policy to a specific TopicId via a six-segment resource identifier:

{
"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-only permissionMulti-tenant, needs to prevent cross-environment log readsPrevents reads, not writesLow
Per-environment role + resource-scopedMulti-tenant, needs strict environment isolationBoth reads and writes isolatedHigher (can be automated)