Skip to main content

Manage Environment Resources

After an environment is created, you need to manage the resources within it through Tencent Cloud APIs, including cloud function deployment, domain configuration, database management, and monitoring and logging.

For environment creation and billing activation, see Enable and create your first environment.

CloudBase management API overview

All CloudBase management APIs can be found in the CloudBase API overview, supporting SDK integration in multiple languages including Python, Java, Go, Node.js, PHP, .NET, C++, and Ruby.

Deploy Backend Services for Tenants

Requests enter through the unified entry of the HTTP access service and are routed to the corresponding cloud functions. REST APIs, WebSocket long connections, and container image deployment are supported.

The complete call flow from getting environment information to being externally accessible:

Operation Steps

Step 1: Create log configuration

  1. Call CreateLogset to create a logset and get the returned LogsetId
  2. Call CreateTopic to create a log topic, pass in the LogsetId from the previous step, and get the returned TopicId
  3. Create a log role (for log delivery): create a role in the CAM role console, select Tencent Cloud product service, choose scf and cls as the role carriers, and attach a custom policy (granting only log write permissions to prevent cross-environment log privilege escalation). Note the role name (e.g., SCF_CLSWriteOnly) for later use in configuration or function creation

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

Step 2: Package and upload code

Package the function directory as a ZIP and Base64-encode it, with a limit of 50 MB. If it exceeds the limit, upload it to COS first, then 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 functions

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 the function to be ready

Poll ListFunctions until Status = Active.

Step 5: Configure HTTP access service routes

Call CreateHTTPServiceRoute. This API requires passing an EnvId and a Domain object; Domain contains the 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 numeric Type in the old GWAPI (for example, 6 in historical examples) has been changed to the UpstreamResourceType enum field in the new API, and magic numbers should no longer be written directly; fill in the corresponding enum value according to the current upstream resource type. In the official current examples, the CloudBase Run service uses "CBR".

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

Step 6: Confirm the routes are effective

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

  • Status = SUCCESS: the configuration is effective
  • DNSStatus = SUCCESS: DNS is effective
  • Status = PROCESSING: continue polling

After the API returns successfully, route delivery may still have a short delay; it is recommended to actually probe once over HTTP / HTTPS.

(Optional) Incrementally maintain routes

The above cloud APIs can be called uniformly through the Management SDK commonService; 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 the CloudBase environment ID as Namespace to operate functions in the corresponding environment; for the complete parameters, see the Cloud Function API overview.

In addition, the following two parameters are required when calling SCF cloud function APIs:

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

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 by environment, 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 the CAM role console to create a role;
  2. Select "Tencent Cloud product service" as the role carrier;
  3. Select SCF (Cloud Function) and CLS (Log Service) for service authorization;
  4. Attach a custom policy (granting only log write permissions to prevent cross-environment log privilege escalation);
  5. Note the role name (for example, SCF_CLSWriteOnly) and pass it as the value of the Role parameter.

WebSocket Functions

On top of regular HTTP functions, WebSocket functions require the following additional parameters in 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.

Single-instance concurrency (session-based is recommended for WebSocket, request-based for regular HTTP):

InstanceConcurrencyConfig: {
DynamicEnabled: 'FALSE',
MaxConcurrency: 10,
Type: 'Session-Based', // Use Session-Based for WebSocket; Request-Based for HTTP
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 sizes, or custom runtime environments. It can also be deployed via CLI.

Prerequisites:

  1. Authorize image pulling: grant the policy QcloudAccessForSCFRoleInPullImage to the cloud function role as a one-time operation: click to authorize
  2. Prepare the image repository: create a repository in Tencent Cloud Container Registry TCR; refer to Get access credentials and Push images.
  3. Image requirements: a Linux-based amd64 image, listening on port 9000 in the container.

When building on Apple Silicon Macs 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 .

When deploying, use Code.ImageConfig instead of Code.ZipFile in CreateFunction:

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

Reference: ImageConfig parameter description

CloudBase Integration APIs


Domains and Safe Domains

Bind custom domains and certificates to the static hosting or HTTP access service of tenant environments; configure the frontend safe domain whitelist that can initiate CloudBase requests.

Operation 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 get the CertId.

Step 2: Bind a custom domain

Choose the corresponding API according to the use case:

Step 3: Configure DNS CNAME

After creating an HTTP access service domain, you can get the CNAME target domain provided by CloudBase from Domains[].Cname in the DescribeHTTPServiceRoute response; for static hosting, follow the result returned by the corresponding API. If you use Tencent Cloud DNSPod, you can operate through APIs:

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

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

Step 4: Configure safe domains (optional)

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

Domain API Reference


Databases

The platform integration solution uses PostgreSQL database (PG mode) as the default database for environments. Passing postgresql in Resources when creating an environment enables it automatically, and tenants are isolated by environment.

  • PostgreSQL database: full SQL capabilities (tables, views, foreign keys, indexes, transactions, stored procedures, etc.), automatically exposes a RESTful API based on PostgREST, and clients can connect directly for reading and writing
  • Permission model: two-layer permissions of table-level GRANT + row-level RLS Policy, expressed in SQL, supporting row-level data isolation by tenant
  • Other databases: if you need MySQL or other types, you can enable them on demand after the environment is created

PostgreSQL

Operation Steps

Step 1: Enable

Pass postgresql in Resources when creating the environment. The environment automatically runs in PG mode and the PostgreSQL instance is enabled automatically, with no additional activation required. See PG mode overview.

Step 2: Create tables and execute SQL

Execute DDL and DML such as table creation through executePGSql (Management SDK) or the HTTP API Execute SQL statements:

await database.executePGSql({
Sql: 'CREATE TABLE users (id SERIAL PRIMARY KEY, name TEXT NOT NULL, email TEXT UNIQUE)'
})

Step 3: Configure permissions

PostgreSQL API Reference

MySQL

Operation Steps

Step 1: Enable MySQL

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

Step 2: Initialize the table structure

After activation, execute DDL statements such as table creation and index creation through RunSql.

Step 3: Configure accounts and access permissions

MySQL API Reference

Lifecycle management (tcb.tencentcloudapi.com):

Account management (cynosdb.tencentcloudapi.com):

Connection and clusters (cynosdb.tencentcloudapi.com):

Backup (cynosdb.tencentcloudapi.com):


Monitoring and Logging

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

Operation Steps

Step 1: Configure logging

Before searching logs, you need to complete the log configuration and create a log role. If already configured, you can skip this step; see Cloud function deployment - Step 1: Create log configuration.

  1. Call CreateLogset to create a logset and get LogsetId
  2. Call CreateTopic to create a log topic and get TopicId
  3. Create a log role (for log delivery): create a role in the CAM role console, select Tencent Cloud product service, choose scf and cls as the role carriers, and attach a custom policy (granting only log write permissions to prevent cross-environment log privilege escalation). Note the role name (e.g., SCF_CLSWriteOnly) for later use in configuration or function creation
  4. Pass ClsLogsetId, ClsTopicId, and Role when creating functions

Step 2: Query monitoring data

Choose the granularity as needed:

Step 3: Search logs

Call SearchLog, passing:

  • 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 up to 100 records, with cursor pagination supported (up to 10,000 records).

Monitoring and Logging API Reference

Log Role Permissions and Multi-Tenant Isolation

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

Multi-tenant scenario: the preset policy QcloudCLSFullAccess does not distinguish between logsets or log topics. When managing multiple tenant environments under the same account, any environment's role can read/write other environments' logs, posing a cross-environment privilege escalation risk.

If log isolation between environments is required, use a custom policy:

Option 1: Shared role + write-only permission (recommended, balancing security and management cost)

All environments share one role, granted only log write permissions to prevent cross-environment log content 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 validation permissions required for cloud function deployment; they only return the metadata of log topics, not log content.

Option 2: Independent role per environment + restricted resources (strictest isolation)

Create an independent role for each environment, and restrict to the specific TopicId in the policy through the six-segment resource 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-only permissionMulti-tenant, need to prevent cross-environment log readsPrevents reads, not writesLow
Independent role per environment + restricted resourcesMulti-tenant, need strict environment isolationIsolates both reads and writesHigher (can be automated)