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.
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
- Call CreateLogset to create a logset and get the returned
LogsetId - Call CreateTopic to create a log topic, pass in the
LogsetIdfrom the previous step, and get the returnedTopicId - Create a log role (for log delivery): create a role in the CAM role console, select Tencent Cloud product service, choose
scfandclsas 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 effectiveDNSStatus = SUCCESS: DNS is effectiveStatus = 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
- Modify an existing domain or route: call ModifyHTTPServiceRoute
- Delete a specified Path or the entire domain configuration: call DeleteHTTPServiceRoute
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
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:
- Go to the CAM role console to create a role;
- Select "Tencent Cloud product service" as the role carrier;
- Select SCF (Cloud Function) and CLS (Log Service) for service authorization;
- Attach a custom policy (granting only log write permissions to prevent cross-environment log privilege escalation);
- Note the role name (for example,
SCF_CLSWriteOnly) and pass it as the value of theRoleparameter.
- Get function list: ListFunctions
- Create function: CreateFunction
- Update function code: UpdateFunctionCode
- Update function configuration: UpdateFunctionConfiguration
- Get function details: GetFunction
- Delete function: DeleteFunction
- Invoke function: Invoke
- Get function code download address: GetFunctionAddress
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:
- Authorize image pulling: grant the policy
QcloudAccessForSCFRoleInPullImageto the cloud function role as a one-time operation: click to authorize - Prepare the image repository: create a repository in Tencent Cloud Container Registry TCR; refer to Get access credentials and Push images.
- Image requirements: a Linux-based
amd64image, 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
- Create HTTP access service route: CreateHTTPServiceRoute
- Delete HTTP access service route: DeleteHTTPServiceRoute
- Query HTTP access service route info: DescribeHTTPServiceRoute
- Modify HTTP access service route: ModifyHTTPServiceRoute
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:
- HTTP access service domain: call CreateHTTPServiceRoute to create a domain and routes, passing at least
EnvIdandDomain; if you only want to bind the domain first, you can create only the domain info and later maintain routes incrementally through ModifyHTTPServiceRoute. - Static hosting domain: call CreateHostingDomain; the task is asynchronous, and you should poll DescribeHostingDomainTask for the completion status.
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:
- Query whether the CNAME record already exists: DescribeRecordFilterList
- Create the record if it does not exist: CreateRecord, fill in
Valuewith 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:
- Add a safe domain: CreateAuthDomain
- Get the safe domain list: DescribeAuthDomains
Domain API Reference
- Create HTTP access service domain / route: CreateHTTPServiceRoute
- Modify HTTP access service domain / route: ModifyHTTPServiceRoute
- Query HTTP access service domain / route: DescribeHTTPServiceRoute
- Delete HTTP access service domain / route: DeleteHTTPServiceRoute
- Bind static hosting domain: CreateHostingDomain
- Query static hosting domain task status: DescribeHostingDomainTask
- Add safe domain: CreateAuthDomain
- Get safe domain list: DescribeAuthDomains
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
- Table-level permissions:
GRANT ... TO <role>, using the three built-in rolesanon/authenticated/service_role - Row-level permissions:
RLS Policy, isolating data rows by tenant - See PostgreSQL database - data permission management
PostgreSQL API Reference
- Execute SQL via management plane: executePGSql
- Execute SQL via HTTP: Execute SQL statements
- HTTP data operations: PostgREST style, see PostgreSQL RESTful API
- Permissions and data security: Data permission management, RLS permission pattern library
MySQL
Operation Steps
Step 1: Enable MySQL
Call CreateMySQL to enable it. The API is asynchronous; poll for the result through the following APIs:
- Query the activation result: DescribeCreateMySQLResult
- Query task status: DescribeMySQLTaskStatus
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
- Query existing accounts: DescribeAccounts
- Modify account password: ResetAccountPassword
- Modify account permissions (isolate read/write scope by tenant): ModifyAccountPrivileges
MySQL API Reference
Lifecycle management (tcb.tencentcloudapi.com):
- Enable MySQL: CreateMySQL
- Query the activation result: DescribeCreateMySQLResult
- Query task status: DescribeMySQLTaskStatus
- Query cluster info: DescribeMySQLClusterDetail
- Execute SQL statements: RunSql
- Destroy MySQL: DestroyMySQL
Account management (cynosdb.tencentcloudapi.com):
- Query account list: DescribeAccounts
- Modify account password: ResetAccountPassword
- Modify account permissions: ModifyAccountPrivileges
- Modify account parameters: ModifyAccountParams
Connection and clusters (cynosdb.tencentcloudapi.com):
- Enable public network: OpenWan
- Disable public network: CloseWan
- Query cluster parameters: DescribeClusterParams
- Modify cluster parameters: ModifyClusterParam
Backup (cynosdb.tencentcloudapi.com):
- Create manual backup: CreateBackup
- Delete manual backup: DeleteBackup
- Get backup download address: DescribeBackupDownloadUrl
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.
- Call CreateLogset to create a logset and get
LogsetId - Call CreateTopic to create a log topic and get
TopicId - Create a log role (for log delivery): create a role in the CAM role console, select Tencent Cloud product service, choose
scfandclsas 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 - Pass
ClsLogsetId,ClsTopicId, andRolewhen creating functions
Step 2: Query monitoring data
Choose the granularity as needed:
- Environment-level monitoring curves (invocations, traffic, etc.): DescribeCurveData
- Environment-level monitoring metric data: DescribeGraphData
- HTTP access service (gateway) monitoring: DescribeGatewayData
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
- Query environment monitoring curves: DescribeCurveData
- Query environment monitoring data: DescribeGraphData
- Query gateway monitoring data: DescribeGatewayData
- Search cloud function logs: SearchLog
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": "*"
}
]
}
DescribeTopicsandDescribeLogsetsare 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": "*"
}
]
}
| Option | Applicable scenario | Isolation granularity | Management cost |
|---|---|---|---|
QcloudCLSFullAccess | Single tenant, or all environments belong to the same user | No isolation | Lowest |
| Shared role + write-only permission | Multi-tenant, need to prevent cross-environment log reads | Prevents reads, not writes | Low |
| Independent role per environment + restricted resources | Multi-tenant, need strict environment isolation | Isolates both reads and writes | Higher (can be automated) |