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.
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:
- Check whether CloudBase is enabled: CheckTcbService
- Query the environment count limit: DescribeEnvLimit
- Get the list of available regions: DescribeTcbRegions
- Get the list of available packages: DescribeBaasPackageList
Step 2: Call CreateEnv to create an environment
Call CreateEnv. The API automatically places an order and charges the account. Key parameters:
| Parameter | Description |
|---|---|
PackageId | Package ID (e.g. baas_personal); can be obtained via DescribeBaasPackageList |
Alias | Environment alias |
Resources | Resource types to enable together with the environment (see the table below) |
Period | Purchase duration in months (default 1) |
Tags | Environment tags used for permission isolation and resource grouping; recommended by tenant ID or business line |
Available values for Resources:
| Value | Description |
|---|---|
flexdb | Document database (NoSQL) |
storage | Object storage (Cloud Storage) |
function | Cloud Function (including HTTP cloud functions) |
postgresql | PostgreSQL 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:
- Query environment billing info: DescribeEnvBilling
- Query environment quota usage: DescribeEnvLimit
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
- Create environment: CreateEnv
- Get environment list: DescribeEnvs
- Destroy environment: DestroyEnv
- Renew environment: RenewEnv
- Change package: ModifyEnvPlan
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
- Call CreateLogset to create a log set and obtain the returned
LogsetId - Call CreateTopic to create a log topic, passing the
LogsetIdfrom the previous step, and obtain the returnedTopicId - Create a log role (for log delivery): in the CAM role console create a role, select Tencent Cloud Product Service, choose
scfandclsas 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 effectDNSStatus = SUCCESS: DNS is in effectStatus = 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
- Modify an existing domain or route: call ModifyHTTPServiceRoute
- Delete a specific Path or the entire domain configuration: call DeleteHTTPServiceRoute
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
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:
- Go to the CAM role console to create the role.
- Choose "Tencent Cloud Product Service" as the role carrier.
- Under service authorization, select SCF (Cloud Function) and CLS (Cloud Log Service).
- Attach a custom policy (grant write-only log permission to prevent cross-environment log privilege escalation).
- Record the role name (e.g.
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 URL: GetFunctionAddress
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:
- Grant permission to pull images: attach the policy
QcloudAccessForSCFRoleInPullImageto the cloud function role. One-time setup: click to grant. - Prepare an image repository: create a repository on Tencent Container Registry (TCR). See obtain access credentials and push images.
- Image requirements: Linux
amd64image 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
- Create HTTP Access Service route: CreateHTTPServiceRoute
- Delete HTTP Access Service route: DeleteHTTPServiceRoute
- Query HTTP Access Service route: DescribeHTTPServiceRoute
- Modify HTTP Access Service route: ModifyHTTPServiceRoute
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:
- HTTP Access Service domain: call CreateHTTPServiceRoute to create the domain and route, passing at least
EnvIdandDomain. If you only want to bind the domain first, you can create just the domain info and later maintain routes incrementally via ModifyHTTPServiceRoute. - Static Hosting domain: call CreateHostingDomain. This is asynchronous — poll DescribeHostingDomainTask for completion status.
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:
- Check whether the CNAME record already exists: DescribeRecordFilterList
- If not, create the record: CreateRecord, with
Valueset 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:
- Add a secure domain: CreateAuthDomain
- Get the list of secure domains: 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 secure domain: CreateAuthDomain
- Get secure domain list: DescribeAuthDomains
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
flexdbinResourceswhen 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
- Create collection: CreateTable
- Query collection info: DescribeTable
- List all collections: ListTables
- Modify collection indexes: UpdateTable
- Delete collection: DeleteTable
- Modify database ACL: ModifyDatabaseACL
- Get database ACL: DescribeDatabaseACL
- Query security rules: DescribeSecurityRule
MySQL
Steps
Step 1: Enable MySQL
Call CreateMySQL to enable it. This is asynchronous — poll the results with:
- Query enable result: DescribeCreateMySQLResult
- Query task status: DescribeMySQLTaskStatus
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
- Query existing accounts: DescribeAccounts
- Reset account password: ResetAccountPassword
- Modify account privileges (isolate read/write scope by tenant): ModifyAccountPrivileges
MySQL API Reference
Lifecycle management (tcb.tencentcloudapi.com):
- Enable MySQL: CreateMySQL
- Query enable result: DescribeCreateMySQLResult
- Query task status: DescribeMySQLTaskStatus
- Query cluster details: DescribeMySQLClusterDetail
- Execute SQL: RunSql
- Destroy MySQL: DestroyMySQL
Account management (cynosdb.tencentcloudapi.com):
- Query account list: DescribeAccounts
- Reset account password: ResetAccountPassword
- Modify account privileges: ModifyAccountPrivileges
- Modify account parameters: ModifyAccountParams
Connection and cluster (cynosdb.tencentcloudapi.com):
- Open public network access: OpenWan
- Close public network access: CloseWan
- Query cluster parameters: DescribeClusterParams
- Modify cluster parameters: ModifyClusterParam
Backups (cynosdb.tencentcloudapi.com):
- Create manual backup: CreateBackup
- Delete manual backup: DeleteBackup
- Get backup download URL: DescribeBackupDownloadUrl
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.
- Call CreateLogset to create a log set and obtain the
LogsetId - Call CreateTopic to create a log topic and obtain the
TopicId - Create a log role (for log delivery): in the CAM role console create a role, select Tencent Cloud Product Service, choose
scfandclsas 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 - When creating functions, pass
ClsLogsetId,ClsTopicId, andRole
Step 2: Query monitoring data
Pick the granularity you need:
- Environment-level monitoring curves (invocations, traffic, etc.): DescribeCurveData
- Environment-level monitoring metrics: DescribeGraphData
- HTTP Access Service (gateway) monitoring: DescribeGatewayData
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
- Query environment monitoring curves: DescribeCurveData
- Query environment monitoring metrics: DescribeGraphData
- Query gateway monitoring data: DescribeGatewayData
- Search cloud function logs: SearchLog
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": "*"
}
]
}
DescribeTopicsandDescribeLogsetsare 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": "*"
}
]
}
| 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, needs to prevent cross-environment log reads | Prevents reads, not writes | Low |
| Per-environment role + resource-scoped | Multi-tenant, needs strict environment isolation | Both reads and writes isolated | Higher (can be automated) |