
Cloudbase Cli
- 4 installs
- 27 repo stars
- Updated August 4, 2026
- tencentcloudbase/cloudbase-skills
Manage CloudBase resources with the tcb CLI: deploy functions, CloudRun apps, storage, databases, static hosting, and configure permissions, CORS, and domains.
About
A CloudBase resource-management skill driven by the tcb CLI for deterministic, scriptable operations. A developer uses it to deploy functions and hosting, query databases, and script CI/CD or batch operations from the terminal.
- Deploy functions, CloudRun, storage, hosting, and databases via tcb
- --help-first workflow for CI/CD and batch operations
Cloudbase Cli by the numbers
- 4 all-time installs (skills.sh)
- Ranked #430 of 550 CLI & Terminal skills by installs in the Skillselion catalog
- Data as of Aug 5, 2026 (Skillselion catalog sync)
npx skills add https://github.com/tencentcloudbase/cloudbase-skills --skill cloudbase-cliAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 4 |
|---|---|
| repo stars | ★ 27 |
| Last updated | August 4, 2026 |
| Repository | tencentcloudbase/cloudbase-skills ↗ |
What it does
Manage CloudBase resources with the tcb CLI: deploy functions, CloudRun apps, storage, databases, static hosting, and configure permissions, CORS, and domains.
Files
CloudBase CLI
Manage CloudBase resources via tcb CLI — deterministic, scriptable, auditable. The preferred interface for AI agents in CI/CD, batch operations, and resource management.
Standalone Install Note
If this environment only installed the current skill, start from the CloudBase main entry and use the published cloudbase/references/... paths for sibling skills.
- CloudBase main entry:
https://cnb.cool/tencent/cloud/cloudbase/cloudbase-skills/-/git/raw/main/skills/cloudbase/SKILL.md - Current skill raw source:
https://cnb.cool/tencent/cloud/cloudbase/cloudbase-skills/-/git/raw/main/skills/cloudbase/references/cloudbase-cli/SKILL.md
Keep local references/... paths for files that ship with the current skill directory. When this file points to a sibling skill such as cloud-functions or cloudrun-development, use the standalone fallback URL shown next to that reference.
Cross-cutting protocols (load for deployment and change operations):
- Change Safety Protocol:
https://cnb.cool/tencent/cloud/cloudbase/cloudbase-skills/-/git/raw/main/skills/cloudbase/references/cloudbase-platform/references/protocols/change-safety-protocol.md - Deployment Gate:
https://cnb.cool/tencent/cloud/cloudbase/cloudbase-skills/-/git/raw/main/skills/cloudbase/references/cloudbase-platform/references/protocols/deployment-gate.md
Core Principles
1. `--help` first — never guess commands. tcb CLI changes between versions. Before using any command for the first time, run tcb <command> --help to check parameters and discover official doc links.
2. Deployment Gate. Before any deployment, publish, custom domain, or CloudRun operation, you must first complete the checks in cloudbase-platform/references/protocols/deployment-gate.md.
3. Verify your work. After deploying or modifying any resource, run the corresponding list/detail command to confirm the change took effect.
3. Dry-run before destructive actions. Use --dry-run for delete/overwrite operations. Show the preview to the user and wait for explicit confirmation before executing.
4. Confirm environment first. Always verify envId with the user before operations. Run tcb env use <envId> to avoid accidentally modifying production.
5. Recover from errors, don't loop. If a command fails after 2-3 attempts, check the exit code ($?), read the error message, consult tcb docs search, and try a different approach.
When to use this skill
Use when the user wants to manage CloudBase resources via command line:
- Deploy/debug cloud functions, web apps, CloudRun services
- Manage storage, hosting, databases (NoSQL/MySQL)
- Configure permissions, CORS, domains, routing
- CI/CD scripting, batch operations, terminal-based resource management
Do NOT use for
- SDK-based in-app integration (web/miniprogram/node) → use
cloud-functions,
no-sql-web-sdk, auth-web, etc.
- MCP tool calls for IDE-integrated workflows → use CloudBase MCP directly
- Console UI operations
- CloudBase Agent SDK development → use
cloudbase-agent-ts
How to use this skill (for a coding agent)
1. Always load `references/core.md` first — it covers authentication, environment switching, tcb docs queries, and error diagnosis. 2. Route to the correct domain reference using the Routing table below. 3. Load only the one reference file that matches the user's task. Do not preload all references. 4. Stop loading more context once you have the workflow and command syntax for the current task. 5. If the task shifts to SDK/in-app code, switch to the appropriate SDK skill (e.g., cloud-functions, no-sql-web-sdk) instead.
Routing
| User Task | Read |
|---|---|
| Login, env switching, tcb docs, error diagnosis | references/core.md |
| Deploy/debug cloud functions | references/functions.md |
| Deploy web app (React/Vue/Next.js) | references/app.md |
| Deploy CloudRun service | references/cloudrun.md |
| Deploy static site | references/hosting.md |
| Upload/download files, ACL rules | references/storage.md |
| NoSQL (MongoDB) database operations | references/nosql.md |
| MySQL database operations | references/mysql.md |
| Roles, policies, access control | references/permission.md |
| CORS, custom domains, routing rules | references/access.md |
Quick workflow
1. tcb login → confirm envId with user → tcb env use <envId> 2. tcb <command> --help to verify syntax 3. Execute the command (with --dry-run for destructive ops) 4. Verify the result with the corresponding list / detail command 5. Report the outcome to the user
Minimum self-check
- [ ] Loaded
references/core.mdbefore any domain module? - [ ] Confirmed target envId with the user?
- [ ] Used
--helpfor unfamiliar commands? - [ ] Used
--dry-runbefore destructive operations? - [ ] Verified the result after each operation?
- [ ] Stayed within CLI scope — did not drift into SDK code?
Access — CloudBase CLI
Three independent modules for configuring external access to CloudBase environments:
| Module | Commands | Purpose |
|---|---|---|
| CORS | tcb cors list/add/rm | Security domains for cross-origin access |
| Domains | tcb domains ls/add/rm | Bind/unbind custom domains with TLS |
| Routes | tcb routes list/add/edit/delete | Map request paths to backend services |
⚠️ Routes require the domain to exist first — use the system default domain or bind one via tcb domains add before creating routes.---
When to Use
- Configuring CORS security domains for cross-origin access
- Binding or unbinding custom domains to a CloudBase environment
- Creating, editing, or deleting routing rules (path -> service mapping)
- Setting up a complete domain + routing + CORS workflow
Do NOT use for
- Storage ACL permissions (use
tcb-storage) - Role-based access control / user permissions (use
tcb-permission) - Static file hosting deployment (use
tcb-hosting) - Web app deployment (use
tcb-app)
---
Workflow 1: CORS Configuration
Step 1 — List current security domains
tcb cors list -e <envId> --jsonStep 2 — Add domains
# Single domain
tcb cors add api.example.com -e <envId> --yes
# Multiple domains (comma-separated, no protocol prefix)
tcb cors add localhost:3000,dev.example.com,app.example.com -e <envId> --yes⚠️ CORS domains do NOT auto-include subdomains — each subdomain must be added separately.
Step 3 — Remove domains
tcb cors rm old.example.com -e <envId> --yesStep 4 — Verify
tcb cors list -e <envId> --jsonParameters: <domain> (no https:// prefix, comma-separated for multiple), -e/--envId, --yes, --json, --dry-run
---
Workflow 2: Custom Domain Binding
Step 1 — Check existing domains
tcb domains ls -e <envId> --jsonStep 2 — Bind domain (SSL cert required)
# Direct connection (default)
tcb domains add api.example.com --certid <certId> -e <envId> --yes
# CDN-accelerated
tcb domains add cdn.example.com --certid <certId> --access-type CDN -e <envId> --yes
# Custom CNAME
tcb domains add custom.example.com --certid <certId> --access-type CUSTOM --custom-cname <cname> -e <envId> --yesAccess types: DIRECT (default, request goes straight to CloudBase), CDN (CDN-accelerated), CUSTOM (custom CNAME target)
Step 3 — Configure DNS
After binding, set a CNAME record pointing your domain to the CloudBase endpoint returned in the response.
Step 4 — Verify binding
tcb domains ls -e <envId> --filter "Domain=api.example.com" --jsonStep 5 — Unbind domain
⚠️ If the domain has routes bound, you MUST delete all routes first, then unbind the domain.
# Check for routes on this domain
tcb routes list -e <envId> --filter "Domain=api.example.com" --json
# Delete routes first (if any)
tcb routes delete api.example.com -e <envId> -p /api/users --yes
# Then unbind domain
tcb domains rm api.example.com -e <envId> --yesParameters: <domain>, --certid (required for add), --access-type, --custom-cname, --disable, --filter, --offset/--limit
---
Workflow 3: Routing Rules
Step 1 — List routes
tcb routes list -e <envId> --json
tcb routes list -e <envId> --filter "Domain=api.example.com" --jsonStep 2 — Create routes
# Single route
tcb routes add -e <envId> --data '{
"domain": "api.example.com",
"routes": [{
"path": "/api/users",
"upstreamResourceType": "CBR",
"upstreamResourceName": "user-service"
}]
}' --yes
# Multiple routes in one call
tcb routes add -e <envId> --data '{
"domain": "api.example.com",
"routes": [
{"path": "/api/users", "upstreamResourceType": "CBR", "upstreamResourceName": "user-service"},
{"path": "/api/orders", "upstreamResourceType": "CBR", "upstreamResourceName": "order-service"},
{"path": "/api/fn", "upstreamResourceType": "SCF", "upstreamResourceName": "my-function"}
]
}' --yes⚠️ If the path already exists under that domain,routes addwill fail — useroutes editinstead.
`upstreamResourceType` values: CBR (CloudBase Run), SCF (Cloud Function), STATIC_STORE (Static Hosting), WEB_SCF (Web Cloud Function), LH (Lighthouse)
Step 3 — Edit routes (incremental update)
routes edit is an incremental update — only pass domain, path (to locate), and the fields you want to change:
# Enable auth on existing route
tcb routes edit -e <envId> --data '{
"domain": "api.example.com",
"routes": [{"path": "/api/users", "enableAuth": true}]
}' --yes
# Add QPS rate limiting
tcb routes edit -e <envId> --data '{
"domain": "api.example.com",
"routes": [{
"path": "/api/users",
"qpsPolicy": {"qpsTotal": 500, "qpsPerClient": {"limitBy": "ClientIP", "limitValue": 50}}
}]
}' --yes⚠️ No need to repeatupstreamResourceType/upstreamResourceNamewhen editing — only changed fields required.
Step 4 — Delete routes
tcb routes delete api.example.com -e <envId> -p /api/users --yes⚠️-p <path>is required forroutes delete— omitting it will error.
Route JSON fields
| Field | Required | Description |
|---|---|---|
domain | ✅ | System default or custom-bound domain |
routes[].path | ✅ | Route path (no wildcards) |
routes[].upstreamResourceType | ✅ (add) | Backend service type |
routes[].upstreamResourceName | ✅ (add) | Backend service name |
routes[].enable | Enable route (default: true) | |
routes[].enableAuth | Enable auth (default: false) | |
routes[].enableSafeDomain | Enable CORS domain check (default: true) | |
routes[].pathRewrite.prefix | Path rewrite prefix | |
routes[].qpsPolicy.qpsTotal | Total QPS limit (max 500) |
---
Complete Scenario: Domain + Routes + CORS
ENV_ID="env-xxx"
DOMAIN="api.example.com"
CERT_ID="cert-abc123"
# 1. Add CORS for frontend
tcb cors add app.example.com -e $ENV_ID --yes
# 2. Bind custom domain
tcb domains add $DOMAIN --certid $CERT_ID -e $ENV_ID --yes
# 3. Configure DNS CNAME (manual step)
# 4. Create routes
tcb routes add -e $ENV_ID --data "{
\"domain\": \"$DOMAIN\",
\"routes\": [
{\"path\": \"/api/users\", \"upstreamResourceType\": \"CBR\", \"upstreamResourceName\": \"user-service\"},
{\"path\": \"/api/fn\", \"upstreamResourceType\": \"SCF\", \"upstreamResourceName\": \"my-function\"}
]
}" --yes
# 5. Verify everything
tcb cors list -e $ENV_ID --json
tcb domains ls -e $ENV_ID --filter "Domain=$DOMAIN" --json
tcb routes list -e $ENV_ID --filter "Domain=$DOMAIN" --jsonTeardown (reverse order)
# Delete routes first
tcb routes delete $DOMAIN -e $ENV_ID -p /api/users --yes
tcb routes delete $DOMAIN -e $ENV_ID -p /api/fn --yes
# Unbind domain
tcb domains rm $DOMAIN -e $ENV_ID --yes
# Remove CORS entry
tcb cors rm app.example.com -e $ENV_ID --yes---
Command Quick Reference
# CORS
tcb cors list -e <envId> [--json]
tcb cors add <domain> -e <envId> --yes # comma-separated for multiple
tcb cors rm <domain> -e <envId> --yes
# Domains
tcb domains ls -e <envId> [--json] [--filter "Domain=xxx"]
tcb domains add <domain> --certid <certId> -e <envId> --yes [--access-type CDN]
tcb domains rm <domain> -e <envId> --yes
# Routes
tcb routes list -e <envId> [--json] [--filter "Domain=xxx"]
tcb routes add -e <envId> --data '<json>' --yes
tcb routes edit -e <envId> --data '<json>' --yes # incremental update
tcb routes delete <domain> -e <envId> -p <path> --yes---
Common Errors
| Error | Cause | Fix |
|---|---|---|
域名 xxx 不存在 | Route references unbound domain | Use system default domain, or domains add first |
域名下有路由绑定 | Trying to unbind domain with routes | Delete all routes on that domain first |
路径 xxx 已存在 | Duplicate path on routes add | Use routes edit to modify existing route |
请提供 -p 参数 | routes delete missing path | Add -p <path> parameter |
域名 xxx 已存在 | Duplicate CORS/domain add | Skip, or remove then re-add |
证书 xxx 不存在 | Invalid cert ID | Get correct ID from Tencent Cloud SSL console |
域名未备案 | Domain lacks ICP filing | Complete ICP filing first |
---
Self-Check
- [ ]
tcb>= 3.0.0 and logged in with correct environment - [ ] CORS: domain format has no protocol prefix (
api.example.com, nothttps://api.example.com) - [ ] Domains: SSL certificate ID is ready (
--certid) - [ ] Domains: domain has ICP filing completed
- [ ] Routes: target domain exists (system default or custom-bound)
- [ ] Routes: using
routes addfor new paths,routes editfor existing paths - [ ] Routes:
--dataJSON is valid and includesdomain+routes[].path - [ ] Unbind sequence: delete routes first, then unbind domain
- [ ] Added
--yesfor CI;--jsonfor programmatic parsing
App — CloudBase CLI
Deploy web applications with automatic framework detection, cloud build, and CDN hosting. App = framework build + deploy; for pre-built static files only, use hosting instead.
When to Use
- Deploying web apps (React, Vue, Vite, Next.js, Nuxt, Angular) to CloudBase
- Need zero-config deployment with automatic framework detection
- Managing web app versions, build status, or redeployment
- Deploying monorepo sub-projects
Do NOT use for
- Pre-built static files without build step — use
hosting - Cloud functions — use
functions - Containerized long-running services — use
cloudrun - Database operations — use
mysqlornosql
---
Workflow 1: First Deploy (Zero Config)
# 1. Confirm target environment
tcb env list
# 2. Deploy from project root (auto-detects framework)
tcb deploy --env-id <envId>
# Or specify a service name
tcb deploy my-app --env-id <envId>CLI auto-completes: detect framework -> infer build command + output dir -> upload to COS -> cloud build (~3-5 min) -> output access URL -> save config to cloudbaserc.json.
Supported Frameworks
| Framework | Detection signal | Default build cmd | Default output dir |
|---|---|---|---|
| React | react-scripts in package.json | npm run build | build |
| Vue | @vue/cli-service / vite | npm run build | dist |
| Vite | vite in devDependencies | npm run build | dist |
| Next.js | next in dependencies | npm run build | .next |
| Nuxt | nuxt in dependencies | npm run build | .output |
| Angular | @angular/core | ng build | dist/<name> |
| Static | No build tool detected | _(none)_ | . |
⚠️ If framework is not detected (Cannot auto-detect project framework), specify explicitly with--framework react --build-command "npm run build" --output-dir dist.
---
Workflow 2: Redeployment
# Redeploy (reads saved config from cloudbaserc.json)
tcb deploy --env-id <envId>
# Force overwrite — skip confirmation prompt
tcb deploy my-app --env-id <envId> --force⚠️ Overwrite creates a new version (e.g. my-app-002 -> my-app-003). Previous versions are preserved, never deleted.Monorepo Sub-project
# Option A: CLI flag (relative path only)
tcb deploy my-app --env-id <envId> --cwd ./packages/frontend
# Option B: cloudbaserc.json
# { "app": { "root": "packages/frontend" } }⚠️--cwdmust be a relative path, not absolute.rootin config is relative tocloudbaserc.json, not CWD.
---
Workflow 3: Version Management
# List all versions
tcb app versions list my-app --env-id <envId>
# View latest version details
tcb app versions detail my-app --env-id <envId>
# View a specific version
tcb app versions detail my-app --version-name my-app-001 --env-id <envId>
# Extract fail reason (JSON mode)
tcb app versions detail my-app --env-id <envId> --json | jq '.data.failReason'Build status values: PENDING (waiting) | BUILDING (in progress) | SUCCESS | FAILED (check failReason).
---
Workflow 4: Deletion
# Preview deletion (always do this first)
tcb app delete my-app --env-id <envId> --dry-run
# Interactive confirmation
tcb app delete my-app --env-id <envId>
# Skip confirmation (CI/CD)
tcb app delete my-app --env-id <envId> --yes⚠️ Deletion is irreversible — removes the app and all its versions.
---
cloudbaserc.json App Config
Auto-saved after first deployment:
{
"envId": "env-xxx",
"app": {
"serviceName": "my-app",
"framework": "react",
"installCommand": "npm install",
"buildCommand": "npm run build",
"outputDir": "./dist",
"deployPath": "/my-app",
"root": "packages/frontend",
"envVariables": { "REACT_APP_API": "https://api.example.com" },
"ignore": ["tests/**", "docs/**"]
}
}| Field | Notes |
|---|---|
serviceName | Auto-inferred from directory name if not specified |
installCommand | ⚠️ Omitted = skipped in --yes/--json mode (unless package.json exists) |
buildCommand | Auto-detected; omit to skip build |
outputDir | ⚠️ Use ./dist for builds, ./ for static-only. Always use ./ prefix |
deployPath | Defaults to /<serviceName>. Only non-default values are saved to config |
envVariables | ⚠️ Build-time only — injected during npm run build, NOT at runtime. Never put secrets here |
ignore | Resolved from cloudbaserc.json location. node_modules/.git always excluded |
---
Command Quick Reference
tcb deploy [name] --env-id <id> # Deploy (shorthand)
tcb app deploy [name] --env-id <id> # Deploy (full form)
tcb app list # List all apps
tcb app info <name> --env-id <id> # App details
tcb app versions list <name> --env-id <id> # List versions
tcb app versions detail <name> --env-id <id> # Version details
tcb app delete <name> --env-id <id> # Delete appKey flags:
| Flag | Purpose |
|---|---|
--framework <name> | Override auto-detection |
--build-command <cmd> | Override build command (empty string to skip) |
--output-dir <dir> | Override output directory |
--deploy-path <path> | CDN mount path (default: /<serviceName>) |
--cwd <path> | Project directory for monorepo |
--force | Skip overwrite confirmation |
--yes | Skip all interactive prompts |
--json | JSON output for CI/CD |
--verbose | Verbose output for debugging |
--yes / --json Auto-detection Logic
| Parameter | Auto-detection |
|---|---|
installCommand | Has package.json? -> npm install; otherwise skip |
buildCommand | Detect build/pack/prebuild script; otherwise skip |
outputDir | Has build command? -> ./dist; otherwise ./ |
deployPath | Default /<serviceName> |
⚠️--yeswithout--env-idhangs in CI — non-interactive mode cannot open the environment selector. Always pass both.
To skip build entirely in CI: tcb deploy my-app --env-id env-xxx --build-command '' --output-dir './' --yes
---
Common Errors
| Error | Cause | Fix |
|---|---|---|
Build failed (FAILED) | Wrong build command, missing deps, Node.js mismatch | Check failReason via --json; verify local build works; cloud uses Node 18 |
| Framework not detected | No framework signature in package.json | Specify --framework, --build-command, --output-dir explicitly |
| Directory not found | --cwd or root points to non-existent path | Verify path with ls; use relative path |
| Build timeout (5 min) | Large upload or slow build | Add ignore patterns; check for accidental node_modules upload |
| Name conflict prompt | App already exists | Use --force or --yes to skip; creates new version |
| URL unreachable after deploy | CDN propagation or bad outputDir | Wait 1-2 min; verify outputDir contains index.html |
| Env ID required | --yes/--json without --env-id | Always pass --env-id in non-interactive mode |
---
Self-Check
- [ ]
tcbCLI installed, version >= 3.0.0 - [ ] Logged in (
tcb login) and correct environment set (tcb env use <envId>) - [ ] Framework auto-detected correctly (or specified explicitly)
- [ ]
outputDiruses./prefix and matches actual build output - [ ]
envVariablescontain no secrets (build-time only, may leak into bundle) - [ ] For monorepo:
root/--cwduses relative path - [ ] For CI/CD:
--env-id+--yesboth specified - [ ] For deletion: previewed with
--dry-runfirst - [ ] For redeployment:
cloudbaserc.jsonconfig reviewed for correctness
CloudRun — CloudBase CLI
Deploy and manage containerized/server-rendered applications with traffic shifting and canary releases. CloudRun = persistent containers; for event-triggered serverless, use functions instead.
When to Use
- Deploying containerized or server-rendered applications to CloudBase
- Managing CloudRun services (init, deploy, list, delete)
- Setting up canary deployment or traffic shifting between versions
- Running function-based CloudRun services locally for testing
- Need persistent long-running services (web APIs, backends)
Do NOT use for
- Serverless event-triggered functions — use
functions - Static file hosting — use
hosting - Web app deployment with framework auto-detection — use
app - Database operations — use
mysqlornosql
---
Workflow 1: Init and Deploy
Step 1: Initialize project
# Initialize from template
tcb cloudrun init --service-name <serviceName> --template <templateName>
# Initialize in a specific directory
tcb cloudrun init --service-name <serviceName> --template <templateName> --target <path>Step 2: Deploy
# Basic deploy
tcb cloudrun deploy --service-name <serviceName> --env-id <envId>
# Container-based: specify port
tcb cloudrun deploy --service-name <serviceName> --port 8080 --env-id <envId>
# With online dependency installation
tcb cloudrun deploy --service-name <serviceName> --install-dependency true --env-id <envId>
# Deploy with canary mode (new version starts at 0% traffic)
tcb cloudrun deploy --service-name <serviceName> --traffic --env-id <envId>
# CI/CD: skip confirmation
tcb cloudrun deploy --service-name <serviceName> --force --env-id <envId>⚠️ Without--trafficflag, the new version replaces the old one with 100% traffic immediately. Use--trafficwhen you want gradual rollout.
⚠️ --force skips the confirmation prompt but does NOT preview changes — it just skips the prompt.Step 3: Verify
# List all services
tcb cloudrun list --env-id <envId>
# Filter by name or type
tcb cloudrun list --service-name <serviceName> --env-id <envId>
tcb cloudrun list --service-type container --env-id <envId>Container-based Deploy Example (Node.js API)
FROM node:18-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production
COPY . .
EXPOSE 80
CMD ["node", "server.js"]# Build and push image
docker build -t ccr.ccs.tencentyun.com/my-repo/api:v1.0.0 .
docker push ccr.ccs.tencentyun.com/my-repo/api:v1.0.0
# Deploy
tcb app deploy \
--service-name api \
--image ccr.ccs.tencentyun.com/my-repo/api:v1.0.0 \
--env-id <envId> \
--remark "v1.0.0 initial"⚠️ Use--remarkfor meaningful version tracking (e.g."v1.2.3 feat: add auth"). Avoid vague remarks like"update".
---
Workflow 2: Traffic Shifting (Canary)
Traffic shifting enables canary releases, blue/green deployments, and instant rollbacks.
View current traffic
tcb cloudrun traffic get --service-name <serviceName> --env-id <envId>Canary release (recommended pattern)
# 1. Deploy new version at 0% traffic
tcb app deploy \
--service-name my-service \
--image ccr.ccs.tencentyun.com/my-repo/app:v2.0.0 \
--env-id <envId> \
--remark "v2.0.0 canary"
# 2. Get new version name
tcb app versions list my-service --env-id <envId>
# 3. Shift 10% -> monitor ~15 min
tcb cloudrun traffic set \
--service-name my-service --env-id <envId> \
--version-weights <newVersion>=10,<stableVersion>=90
# 4. Shift 50% -> monitor
tcb cloudrun traffic set \
--service-name my-service --env-id <envId> \
--version-weights <newVersion>=50,<stableVersion>=50
# 5. Full rollout
tcb cloudrun traffic set \
--service-name my-service --env-id <envId> \
--version-weights <newVersion>=100⚠️ Always note the current stable version name BEFORE starting a rollout. Run tcb app versions list first.⚠️traffic promotesets canary to 100% and removes the stable version — this is irreversible.traffic rollbackdoes the opposite.
Instant rollback
tcb cloudrun traffic set \
--service-name my-service --env-id <envId> \
--version-weights <stableVersion>=100Monitoring after traffic shift
tcb logs search --service my-service --level error --env-id <envId>
tcb logs search --service my-service --limit 50 --env-id <envId>
tcb app info my-service --env-id <envId>Rollback triggers: error rate > 1%, P99 latency > 2x baseline, any crash/OOM in logs.
Multi-environment Promotion (dev -> staging -> prod)
IMAGE=ccr.ccs.tencentyun.com/my-repo/my-service:v1.2.0
tcb app deploy --service-name svc --image $IMAGE --env-id dev-env-xxx
# test in dev...
tcb app deploy --service-name svc --image $IMAGE --env-id staging-env-xxx
# sign-off...
tcb app deploy --service-name svc --image $IMAGE --env-id prod-env-xxx --dry-run
tcb app deploy --service-name svc --image $IMAGE --env-id prod-env-xxx \
--remark "v1.2.0 promoted from staging"---
Workflow 3: Local Development
# Run function-based service locally
tcb cloudrun run --env-id <envId>
# With hot reload
tcb cloudrun run --hot-reload true --env-id <envId>
# On specific port
tcb cloudrun run --port 3000 --env-id <envId>
# Agent mode (for AI agent debugging)
tcb cloudrun run --mode agent --agent-id <agentId> --env-id <envId>
# Dry run (validate without starting)
tcb cloudrun run --dry-run true --env-id <envId>⚠️ tcb cloudrun run only supports function-based services. Container-based services must be tested via Docker locally.Function-based vs Container-based
| Capability | Function-based | Container-based |
|---|---|---|
tcb cloudrun run (local) | Supported | Not supported |
| Custom Dockerfile | No | Yes |
| Port configuration | Auto-detected | Must specify --port |
| Hot reload | --hot-reload true | Not supported |
| Agent mode | Supported | Not supported |
---
Workflow 4: Download and Delete
# Download latest deployed code
tcb cloudrun download --service-name <serviceName> --target <path> --env-id <envId>
# Force overwrite existing directory
tcb cloudrun download --service-name <serviceName> --force --env-id <envId>
# Delete a service (interactive confirmation)
tcb cloudrun delete --service-name <serviceName> --env-id <envId>
# Force delete (CI/CD)
tcb cloudrun delete --service-name <serviceName> --force --env-id <envId>⚠️ Deletion removes all versions and traffic configuration. There is no undo or --dry-run for CloudRun delete.⚠️ tcb cloudrun download downloads the latest deployed code only, not a specific version. Does not include runtime config (env vars, secrets).---
Secrets Injection
# Set secrets (injected as env vars at container startup)
tcb secrets set DATABASE_URL "mysql://..." --env-id <envId>
tcb secrets set API_SECRET "..." --env-id <envId>
# List configured secrets
tcb secrets list --env-id <envId>⚠️ Secrets are shared across ALL services in the environment, not per-service.
⚠️ Changing a secret does NOT auto-restart running services — you must redeploy.
---
Command Quick Reference
tcb cloudrun init --service-name <n> --template <t> # Init project
tcb cloudrun deploy --service-name <n> --env-id <id> # Deploy service
tcb cloudrun list --env-id <id> # List services
tcb cloudrun download --service-name <n> --env-id <id> # Download code
tcb cloudrun delete --service-name <n> --env-id <id> # Delete service
tcb cloudrun run --env-id <id> # Local run (function only)
tcb cloudrun traffic get --service-name <n> --env-id <id> # View traffic
tcb cloudrun traffic set --service-name <n> --env-id <id> --version-weights ... # Set trafficKey flags: --force (skip confirmation), --traffic (canary mode on deploy), --port (container port), --hot-reload true (local dev), --install-dependency true (online install), --remark (version label), --dry-run (preview deploy).
---
Common Errors
| Error | Cause | Fix |
|---|---|---|
| Local run fails for container service | tcb cloudrun run is function-only | Use Docker to test container services locally |
| New version gets no traffic | Deployed with --traffic (canary mode) | Explicitly shift traffic with tcb cloudrun traffic set |
| Deploy prompt hangs in CI | Missing --force flag | Always use --force for non-interactive pipelines |
| Secret not available in container | Secret set after deploy | Redeploy the service after changing secrets |
| Download missing config | Download only includes source code | Runtime config (env vars, secrets) not included |
---
Self-Check
- [ ]
tcbCLI installed, version >= 3.0.0 - [ ] Logged in (
tcb login) and correct environment set (tcb env use <envId>) - [ ] Service type determined: function-based or container-based
- [ ] For container:
--portmatches app's listening port; image built and pushed - [ ] For canary: current stable version name noted before deploying
- [ ] For canary: traffic shifting plan ready (10% -> 50% -> 100%)
- [ ] Secrets stored via
tcb secrets set, not hardcoded - [ ] For CI/CD:
--forceflag added to skip confirmation - [ ] Post-deploy: service endpoint tested and traffic distribution verified
Core — CloudBase CLI
Core foundation for all CloudBase CLI operations (云开发 CLI 核心基础).
This reference covers authentication, environment setup, documentation queries, config, and error handling.
When to Use
- Any CloudBase CLI operation (always start here)
- Authenticating with
tcb loginor switching environments withtcb env use - Querying CLI docs with
tcb docsor checking command help with--help - Diagnosing CLI errors via exit codes
Do NOT use for
- CloudBase SDK development (use
cloudbase-skillsrepo) - CloudBase MCP server operations (use MCP server docs)
- Tencent Cloud console-only operations (this reference is CLI-only)
---
Workflow 1: Authentication
Quick Commands
tcb login # Interactive login (device code, recommended)
tcb login --flow web # Web authorization (same-machine only)
tcb login --apiKeyId <Id> --apiKey <Key> # CI / non-interactive
tcb login --apiKeyId <Id> --apiKey <Key> --token <T> # Temp token (CI, more secure)
tcb logout # Clear local credentialsLogin Methods
1. Device Code Authorization (default, recommended)
tcb login
# Prints a device code + verification URL.
# Open URL in any browser (can be a different machine), enter code to authorize.Works in remote SSH, headless servers, WSL. Browser and CLI need not be on the same machine.
2. Web Authorization (same-machine only)
tcb login --flow web
# Opens browser on local machine; CLI receives token via local callback.⚠️ Requires browser and CLI on the same machine. Falls back to key-based login if browser cannot open.
3. CI / Non-Interactive Login
# Permanent credentials
tcb login --apiKeyId $SECRET_ID --apiKey $SECRET_KEY
# Temporary token (shorter TTL, more secure for CI)
tcb login --apiKeyId $TMP_SECRET_ID --apiKey $TMP_SECRET_KEY --token $SESSION_TOKEN⚠️ Never hardcode credentials. Always inject via environment variables.
不要把密钥硬编码在命令里,通过环境变量注入。
Checking Login Status
tcb login
# If already logged in: prints "您已登录,无需再次登录!" and exits.⚠️ Do not use tcb env list to check login status — sub-accounts may lack list permissions, causing misleading errors.Sub-account Policies (子账号策略)
Sub-accounts need these CAM policies to use the CLI:
| Policy | Purpose |
|---|---|
QcloudAccessForTCBRole | TCB access to cloud resources |
QcloudAccessForTCBRoleInAccessCloudBaseRun | TCB access to VPC/CVM for CloudRun |
QcloudCamReadOnlyAccess | Required for web/device code login; without it, only API key login works |
⚠️ If sub-account device/web login fails, grantQcloudCamReadOnlyAccessor switch to--apiKeyId / --apiKey.
Auth Troubleshooting
| Issue | Solution |
|---|---|
Not logged in | Run tcb login |
| Cannot open browser / browser loop | Use default device code flow (no --flow flag) |
| Device code not working in CI | Use --apiKeyId / --apiKey credential login |
| Sub-account web/device login fails | Grant QcloudCamReadOnlyAccess, or use key login |
| Permission denied on resources | Check sub-account CAM policies for the specific TCB resource |
---
Workflow 2: Environment Setup
Core Principle
操作任何云开发资源前,必须先确认 envId。优先让用户明确告知 envId。
⚠️ Always confirm envId before any operation to avoid accidentally modifying production. Ask the user to provide the envId directly — do not auto-discover.
Login -> Environment Flow
tcb login
|
Ask user: "Which environment? (please provide the envId)"
|
User knows envId?
+-- YES --> tcb env use <envId>
+-- NO --> tcb env list <-- fallback only; sub-accounts may see limited results
|
User selects --> tcb env use <envId>Basic Operations
tcb env use <envId> # Set default env for all subsequent commands
tcb env detail <envId> # View environment details
tcb env rename <newAlias> --env-id <envId> --yes # Rename alias
tcb env create --alias <name> --package <packageId> --yes # Create new env⚠️ tcb env list may return incomplete results under sub-account permissions. Use only when user explicitly asks.Per-Command Override
tcb app deploy --env-id <envId> # Override without changing defaultMulti-Environment Best Practices
- Use separate envIds for dev / staging / production — never share
- Before production operations: confirm envId with user +
--dry-run - When switching environments, explicitly confirm the new envId before proceeding
---
Workflow 3: Documentation Query (tcb docs)
When in doubt, query first. Never guess command signatures.
不确定参数时,先查,不要猜。猜错在生产环境上可能触发你不想要的操作。
Commands
tcb docs list # List all top-level documentation modules
tcb docs read <module|path> # Read module structure or specific document
tcb docs search "keyword" # Search documents by keywordStandard Query Flow
tcb docs list
|
Identify relevant module
|
tcb docs read <moduleName>
|
Browse document tree, find target path
|
tcb docs read <path> # e.g. "MySQL数据库.数据操作.字段类型"
|
Read content --> construct commandOr shortcut: tcb docs search "关键词" --> review results --> tcb docs read <path>
Decision Tree
User describes a task
|
Know exact command + all flags?
+-- NO --> tcb docs list --> tcb docs read --> confirm flags
+-- YES --> Destructive operation?
+-- YES --> --dry-run first
+-- NO --> Execute directlyQuery docs when
- Unsure about subcommands or flags
- A command returned an error and you don't know why
- The user mentions a feature you haven't used before
- Combining multiple flags and want to verify compatibility
- About to perform a destructive or irreversible operation
Skip docs when
- Simple read operation you've already run this session
- User provided all parameters and you've verified the syntax
Anti-patterns
| Anti-pattern | Do instead |
|---|---|
| Guessing a flag name | tcb docs list -> tcb docs read <module> first |
| Running full deploy to "test" if it works | Use --dry-run |
| Repeating same failed command with same flags | Re-read docs, change flags |
| Assuming v2.x flag names still work | Query docs after version upgrade |
Jumping to tcb docs read <path> without listing | Start with tcb docs list |
--help First Rule (MANDATORY)
Before using ANY `tcb` command for the first time, run `<command> --help` to check:
- Parameter names and formats
- Required vs optional parameters
- Official API doc URLs (many commands include Tencent Cloud API links)
- Examples and usage patterns
Unsure about usage?
|
tcb <command> --help
|
Help shows API doc link?
+-- YES --> web_fetch the doc --> understand data structure --> construct correctly
+-- NO --> tcb docs search "<keyword>" --> construct from docs⚠️ Real lesson:tcb db nosql execute --helpshowsMgoCommandParamstructure doc link.
Without reading it, agents construct wrong Command field format (should be a JSON-encodedstring of MongoDB shell syntax, NOT a raw array). This mistake cost 10+ minutes. Don't repeat it.
--dry-run Safety Mechanism
所有破坏性操作必须先 --dry-run 预览,等用户确认后再执行。tcb app deploy --dry-run # Preview app version to be published
tcb fn deploy --dry-run # Preview functions to be overwrittenWorkflow: --dry-run -> show preview -> wait for user confirmation -> re-run without --dry-run.
⚠️ Never skip --dry-run for destructive operations (overwrite / delete / rollback).
---
cloudbaserc.json Quick Reference
Project config file in project root. Defines environment, functions, servers, and app settings.
File Location
project-root/
+-- cloudbaserc.json <-- Default
+-- .cloudbaserc.json <-- Alternative (hidden)
+-- custom-config.json <-- Use with --config-file flagtcb app deploy --config-file config/staging.jsonRoot Structure (ICloudBaseConfig)
{
"envId": "env-xxxxx",
"functionRoot": "functions",
"functions": [],
"servers": [],
"app": {}
}| Field | Type | Required | Description |
|---|---|---|---|
envId | string | Yes | CloudBase environment ID (env- prefix). Override with --env-id |
functionRoot | string | No | Base directory for cloud functions. Default: "functions" |
functions | array | No | Cloud function configs (see below) |
servers | array | No | CloudRun service configs (see below) |
app | object | No | Web app hosting config (see below) |
functions Array — Essential Fields
Each entry is an ICloudFunction:
| Field | Type | Default | Description |
|---|---|---|---|
name | string | (required) | Function name, unique in env |
handler | string | — | Entry point, e.g. "index.main" |
runtime | string | auto-detected | Nodejs18.15, Python3.9, Go1.8, Java11, etc. |
timeout | number | 3 | Execution timeout in seconds (1-900) |
memorySize | number | 256 | Memory in MB (128-3008, multiples of 128) |
type | string | "Event" | "Event" (background) or "HTTP" (web-accessible) |
envVariables | object | {} | Runtime env vars (process.env.* / os.environ[]) |
triggers | array | [] | Timer, COS, API Gateway triggers |
installDependency | boolean | true | Auto-install deps before deploy |
vpc | object | — | { vpcId, subnetId } for VPC access |
dir | string | functionRoot/name | Custom code directory |
ignore | string[] | [] | Glob patterns to exclude from deploy |
⚠️ For sensitive values, usetcb secretsinstead ofenvVariables.
Minimal function example:
{
"functions": [{
"name": "my-function",
"handler": "index.main",
"runtime": "Nodejs18.15",
"timeout": 30,
"envVariables": { "NODE_ENV": "production" }
}]
}For full function config (triggers, image deployment, concurrency, WebSocket, VPC) see tcb-functions skill.servers Array
{
"servers": [
{ "type": "node", "name": "api-service", "path": "services/api" }
]
}Only"node"type currently supported. For full CloudRun config seetcb-cloudrunskill.
app Object — ICloudAppConfig
| Field | Type | Default | Description |
|---|---|---|---|
serviceName | string | (required) | Service name, unique in env, used in URLs |
framework | string | auto-detected | react, vue, nextjs, nuxt, static, etc. |
root | string | "." | App code directory (relative to project root) |
installCommand | string | framework-dependent | Empty string "" = skip |
buildCommand | string | framework-dependent | Empty string "" = skip build |
outputDir | string | "dist" | Build output dir. For static hosting: "./" |
deployPath | string | /<serviceName> | URL path. Only non-default values are saved to config |
envVariables | object | {} | Build-time environment variables |
ignore | string[] | [] | Files/dirs to exclude from deploy |
Minimal app example:
{
"app": {
"serviceName": "web-app",
"framework": "react",
"buildCommand": "npm run build",
"outputDir": "dist"
}
}Config Priority (highest to lowest)
1. CLI flags (--env-id, --deploy-path, etc.) 2. cloudbaserc.json 3. CLI defaults
CI/CD environment variable overrides:
export TCB_ENV_ID=env-production # Override envId
export TCB_FRAMEWORK=vue # Override framework detectionConfig Best Practices
- Commit
cloudbaserc.jsonto git for team consistency; never add secrets - Use separate config files per environment (
cloudbaserc.production.json) - Add
cloudbaserc.*.jsonto.gitignore - Validate:
tcb app info --config-file cloudbaserc.json --json
---
Error Diagnosis (Exit Codes)
CloudBase CLI uses structured exit codes for CI/CD and agent error handling.
| Code | Meaning | Typical Scenario | Recovery |
|---|---|---|---|
| 0 | Success | — | — |
| 1 | General error | Uncategorized exception | Check message, investigate |
| 2 | Auth failed | Not logged in, token expired | tcb login |
| 3 | Invalid input | Missing/malformed params | Check --help, fix params |
| 4 | Resource not found | Wrong envId, missing function/collection | Verify with tcb env list / tcb fn list |
| 5 | Cloud API error | Network timeout, SDK error | Retry with backoff |
| 6 | Local file error | cloudbaserc.json missing/corrupt | Check config, tcb init |
Agent Error Handling Strategy
1. Read exit code ($?) to categorize 2. Parse error message for details (envId, param name, etc.) 3. Targeted recovery:
- Code 2 ->
tcb login - Code 3 -> Fix params (check docs, ask user)
- Code 4 -> Verify resource exists
- Code 5 -> Retry with exponential backoff
- Code 6 -> Check/repair config
4. Escalate to user if recovery fails after 2-3 attempts
CI/CD Script Pattern
tcb fn deploy || {
code=$?
case $code in
2) echo "Auth failed"; tcb login && tcb fn deploy ;;
5) echo "API error, retrying..."; sleep 30 && tcb fn deploy ;;
*) echo "Unrecoverable (code $code)"; exit $code ;;
esac
}Run tcb help exit-codes for source-level docs (requires CLI >= 3.0.0-alpha.9).---
Self-Check
每次 CLI 操作前的核心检查清单
Environment Setup
- [ ]
tcb --version>= 3.0.0 - [ ]
tcb logincompleted (token valid) - [ ] Target envId confirmed with user
- [ ]
tcb env use <envId>executed
Before Any Command
- [ ] Run
<command> --helpfor any new command - [ ] Check API doc links in help output (use
web_fetchif available) - [ ] Verify parameter names/formats match help
Destructive Operations
- [ ]
--dry-runto preview first - [ ] Show preview to user
- [ ] Wait for explicit confirmation
- [ ] Re-run without
--dry-runonly after "yes"
Error Handling
- [ ] Check exit code (
$?) - [ ] Apply targeted recovery per exit code table above
- [ ] Escalate to user after 2-3 failed attempts
Common Global Flags
--env-id <envId> # Temporarily override env (does not change `env use` setting)
--verbose # Verbose logging (add when debugging)
--version # Print tcb version (verify >= 3.0.0)Functions — CloudBase CLI
Deploy, update, debug, and manage cloud functions (云函数) via tcb fn commands. Covers both Event Functions (普通云函数) and HTTP Functions (HTTP 云函数).
When to Use
- Deploy or update cloud functions from terminal / CI pipeline
- Query function logs, diagnose runtime errors
- Manage triggers (timer/定时触发器), layers, versions
- Inject secrets / environment variables
- Batch deploy via
cloudbaserc.json
Do NOT use for
- Calling functions from client code (web/miniprogram) → use
cloud-functionsskill - CloudRun container deployments → use
references/cloudrun.md - SDK-based in-app function invocation → use
@cloudbase/js-sdk - Console UI operations
Command Quick Reference
| Task | Command |
|---|---|
| List all functions (列出函数) | tcb fn list |
| Function detail (查看详情) | tcb fn detail <name> |
| Deploy all functions | tcb fn deploy --all |
| Deploy single Event Function | tcb fn deploy <name> |
| Deploy HTTP Function | tcb fn deploy <name> --httpFn |
| Deploy HTTP + WebSocket | tcb fn deploy <name> --httpFn --ws |
| Deploy multiple | tcb fn deploy fn1 fn2 |
| Update code only (仅更新代码) | tcb fn code update <name> |
| Update config only (仅更新配置) | tcb fn config update <name> |
| Invoke remotely (调用函数) | tcb fn invoke <name> |
| Invoke with params | tcb fn invoke <name> --params '{"key":"val"}' |
| Run locally (本地调试) | tcb fn run <name> |
| View logs (查看日志) | tcb fn log <name> |
| View log by RequestId | tcb fn log <name> --reqId <id> |
| Create trigger (创建触发器) | tcb fn trigger create <name> |
| Delete trigger | tcb fn trigger delete <name> --name <trigger> |
| List layers (层) | tcb fn layer list |
| Publish version (发布版本) | tcb fn publish-version <name> |
| Copy to another env | tcb fn copy <name> --envId <target> |
| Delete function | tcb fn delete <name> |
Always run tcb fn <subcommand> --help first to check current syntax.---
Workflow 1: Deploy Functions
Deploy All
# Reads cloudbaserc.json → deploys every function listed
tcb fn deploy --all
# Verify
tcb fn listDeploy Single Function
# Event Function(普通云函数)
tcb fn deploy my-function
# HTTP Function(HTTP 云函数)— requires scf_bootstrap
tcb fn deploy my-http-fn --httpFn
# Force overwrite existing
tcb fn deploy my-function --forceDeploy Multiple (Selective)
tcb fn deploy func-a func-b func-cConfig-Only Update (仅更新配置,不上传代码)
tcb fn config update my-function⚠️ Function type is locked after creation (函数类型创建后不可更改).
Cannot change Event → HTTP or vice versa. To switch: delete → recreate.
⚠️ Runtime is locked after creation. To change (e.g., Nodejs16 → Nodejs18):
delete the function and create a new one.
Deploy Modes
| Mode | Flag / Config | Use Case |
|---|---|---|
| COS upload (default) | — | Code < 50 MB, standard deploy |
| ZIP package | deployMode: "zip" | Bundled dependencies |
| Image (镜像) | deployMode: "image" | Custom runtime, large dependencies |
⚠️ Code encryption (代码加密): Once enabled, code cannot be downloaded in console.
Enable only when you have source control in place.
⚠️ `installDependency` conflict (依赖安装冲突):
IfinstallDependency: true, the platform installs deps frompackage.jsonon deploy.
Do NOT also upload node_modules/ — they will conflict. Choose one approach.For HTTP Functions,installDependencyis NOT supported; bundlenode_modulesyourself.
---
Workflow 2: Incremental Update
When only code changed (no config changes):
tcb fn code update my-functionWhen only config changed (timeout, memory, env vars):
tcb fn config update my-functionTypical iteration cycle:
# 1. Edit code locally
# 2. Push code only
tcb fn code update my-function
# 3. Invoke to test
tcb fn invoke my-function --params '{"action":"test"}'
# 4. Check logs
tcb fn log my-function---
Workflow 3: Debug and Investigate
Step 1: Query Logs (查询日志)
# Recent logs (default last 10 minutes)
tcb fn log my-function
# Filter by time range
tcb fn log my-function --offset 0 --limit 100
# Search for errors
tcb fn log my-function --keyword "Error"
tcb fn log my-function --keyword "timeout"
# Filter failures only
tcb fn log my-function --success falseStep 2: Get Detailed Log by RequestId
tcb fn log my-function --reqId "abc-123-def-456"Step 3: Invoke and Inspect
# Remote invoke with test payload
tcb fn invoke my-function --params '{"action":"test"}'
# Local run for fast iteration(本地调试)
tcb fn run my-function --params '{"action":"test"}'Common Error Patterns
| Symptom | Likely Cause | Fix |
|---|---|---|
MODULE_NOT_FOUND / 模块未找到 | Missing dependency | Check package.json; set installDependency: true or bundle node_modules |
Task timed out / 超时 | Exceeds timeout | Increase timeout in config (max 900s); optimize code |
Memory size exceeded / 内存溢出 | OOM kill | Increase memorySize (128–3072 MB); reduce payload |
Environment variable not found | Var not set or overwritten | Check tcb fn detail; merge env vars on update |
Permission denied / EACCES | VPC or IAM issue | Check VPC config and security group rules |
ECONNREFUSED / network error | Downstream service issue | Verify VPC settings, security groups, endpoint URLs |
---
Workflow 4: Triggers and Versions
Timer Trigger (定时触发器 / Cron)
Config in cloudbaserc.json:
{
"functions": [{
"name": "daily-cleanup",
"triggers": [{
"name": "daily-timer",
"type": "timer",
"config": "0 0 2 * * * *" // 每天凌晨2点 (2:00 AM daily)
}]
}]
}# Deploy the trigger
tcb fn trigger create daily-cleanup
# List triggers
tcb fn trigger list daily-cleanup
# Delete a trigger
tcb fn trigger delete daily-cleanup --name daily-timerCron format: 秒 分 时 日 月 星期 年 (7 fields — note the leading seconds field).| Expression | Schedule |
|---|---|
0 0 2 * * * * | 每天 02:00 |
0 30 9 * * * * | 每天 09:30 |
0 */5 * * * * * | 每5分钟 |
0 0 2 1 * * * | 每月1号 02:00 |
0 0 18 * * MON-FRI * | 工作日 18:00 |
Multi-Environment Cron Deploy Example
# Deploy cron function to dev, then staging
tcb env use env-dev-xxx
tcb fn deploy daily-cleanup
tcb fn trigger create daily-cleanup
tcb env use env-staging-xxx
tcb fn deploy daily-cleanup
tcb fn trigger create daily-cleanupPublish a Version
tcb fn publish-version my-function
tcb fn list-version my-function⚠️ Traffic / concurrency (流量与并发): Traffic split between versions and
reserved concurrency are configured via console or API, not CLI.
Layers (层)
tcb fn layer listLayers share dependencies across functions — useful for large libraries (puppeteer, ffmpeg) that would exceed the code size limit. Bind layers via cloudbaserc.json layers array.
---
Secrets Injection
Inject secrets via environment variables — never hardcode credentials.
// cloudbaserc.json
{
"functions": [{
"name": "my-function",
"envVariables": {
"DB_HOST": "10.0.0.1",
"API_KEY": "{{YOUR_API_KEY}}" // 替换为实际密钥
}
}]
}# Update env vars without redeploying code
tcb fn config update my-function
# Verify
tcb fn detail my-function⚠️ Env var update is a full replace, not a merge (环境变量更新为全量覆盖).
Always include ALL env vars in the config — omitting one will delete it.
Workflow: tcb fn detail <name> → copy existing vars → add new → update config.For CI/CD pipelines, use shell variable substitution:
export API_KEY="$CI_SECRET_API_KEY"Access in code:
const apiKey = process.env.API_KEY;
const dbUrl = process.env.DB_URL;---
cloudbaserc.json Function Config
{
"envId": "your-env-id",
"functionRoot": "cloudfunctions", // 函数代码根目录
"functions": [
{
"name": "my-event-fn",
"handler": "index.main", // ⚠️ format: filename.export
"runtime": "Nodejs18.15",
"timeout": 10,
"memorySize": 256,
"installDependency": true, // 云端安装依赖 (Event only)
"envVariables": { "NODE_ENV": "production" },
"triggers": [],
"ignore": ["node_modules/**", ".git/**"]
},
{
"name": "my-http-fn",
"handler": "index.main",
"runtime": "Nodejs18.15",
"timeout": 60,
"memorySize": 512,
"isHTTP": true // HTTP 云函数
}
]
}Key Fields
| Field | Description | Default |
|---|---|---|
name | 函数名称 (required) | — |
handler | 入口,格式 filename.export | index.main |
runtime | 运行时版本 | Nodejs18.15 |
timeout | 超时时间(秒,max 900) | 3 |
memorySize | 内存(MB,128–3072,64 的倍数) | 256 |
installDependency | 云端安装依赖(仅 Event Function) | false |
envVariables | 环境变量 key-value | {} |
isHTTP | 是否为 HTTP 云函数 | false |
triggers | 触发器数组 | [] |
functionRoot | 所有函数的代码根目录 | functions |
dir | 单个函数的子目录(覆盖 name) | same as name |
ignore | 部署时排除的文件 glob | [] |
⚠️ `handler` format (入口格式): Must befilename.export— e.g.,index.main.
Do NOT include file extension or directory path. Wrong:src/index.main,index.js.main.
⚠️ `functionRoot` vs `dir`: functionRoot is the parent directory for ALL functions.Each function folder name must matchname. Usedirto override if the folder name
differs: "dir": "actual-folder-name".Supported Runtimes (运行时)
| Runtime | Value | Notes |
|---|---|---|
| Node.js 18 | Nodejs18.15 | ✅ Recommended |
| Node.js 16 | Nodejs16.13 | ✅ Supported |
| Node.js 14 | Nodejs14.18 | ⚠️ Maintenance |
| Node.js 12 | Nodejs12.16 | ⚠️ Deprecated |
| Python 3.10 | Python3.10 | HTTP Function only |
| Go 1.x | Go1 | HTTP Function only |
| Java 11 | Java11 | HTTP Function only |
| PHP 8 | Php8.0 | HTTP Function only |
HTTP Functions require scf_bootstrap file (executable, port 9000, LF line endings).---
Common Errors (Top-5)
1. Function not exist / 函数不存在
Cause: Name typo or function not yet deployed.
tcb fn list # verify name exists
tcb fn deploy my-function # deploy if missing2. Module not found / 模块未找到
Cause: Dependencies not installed in deployed environment.
# Event Function: enable cloud install
# cloudbaserc.json → "installDependency": true, exclude node_modules
# HTTP Function: bundle locally
npm install --production
tcb fn deploy my-http-fn --httpFn3. Execution timeout / 执行超时
Cause: Function exceeds configured timeout.
tcb fn detail my-function # check current timeout
# Increase in cloudbaserc.json → "timeout": 60
tcb fn config update my-functionAlso check: infinite loops, unresolved promises, slow external API calls.
4. Deploy timeout / 部署超时
Cause: Large code package or slow network.
# Reduce package — add to cloudbaserc.json:
# "ignore": ["node_modules/**", "test/**", ".git/**", "*.md"]
# Or use installDependency: true to skip uploading node_modules
tcb fn deploy my-function5. HTTP 404 / CORS — 访问不通
Cause: HTTP access not configured, path mismatch, or missing CORS headers.
tcb fn detail my-function # verify HTTP access config
# Ensure HTTP Function listens on port 9000
# Ensure scf_bootstrap exists and is executable (chmod +x)
# For CORS: add Access-Control-Allow-Origin header in function code---
Self-Check
Before deploying:
- [ ] Confirmed target
envIdwith the user? (tcb env list) - [ ]
cloudbaserc.jsonhas correctfunctionRootand functionname? - [ ]
handlerformat isfilename.export(no path, no.js)? - [ ]
runtimeexplicitly set (not relying on default)? - [ ] HTTP Function has
scf_bootstrapwithchmod +x, port 9000, LF endings? - [ ]
installDependencyconsistent? (Event only; nonode_modulesin upload) - [ ] Secrets in
envVariables, not hardcoded? - [ ]
ignoreexcludes test files, docs,.git?
After deploying:
- [ ] Verified with
tcb fn detail <name>? - [ ] Tested with
tcb fn invoke <name>? - [ ] Checked logs with
tcb fn log <name>for startup errors? - [ ] Triggers working? (
tcb fn trigger list <name>)
When updating env vars:
- [ ] Queried current vars first? (
tcb fn detail <name>) - [ ] Merged existing + new vars in config?
- [ ] Did NOT overwrite — all existing vars preserved?
Hosting — CloudBase CLI
Deploy pre-built static files (HTML/CSS/JS) to CloudBase CDN hosting. Hosting = pre-built static files with CDN; for framework build + deploy, use app instead.
When to Use
- Deploying pre-built static files to CloudBase CDN hosting
- Managing hosted files: listing, downloading, or deleting
- Setting up a static website or SPA with CDN acceleration
- Need fine-grained control over individual file deployment
Do NOT use for
- Web app deployment with framework auto-detection and build — use
app - File storage with ACL rules — use
storage - Cloud functions — use
functions - Containerized services — use
cloudrun
---
Workflow 1: Deploy Static Site
# 1. Confirm target environment
tcb env list
# 2. Check hosting status (auto-enables if not active)
tcb hosting detail --env-id <envId>
# 3. Build locally first
npm run build
# 4. Deploy built assets
tcb hosting deploy ./dist --env-id <envId> --yes
# 5. Verify
tcb hosting list --env-id <envId>Deploy Variations
# Deploy current directory
tcb hosting deploy --env-id <envId> --yes
# Deploy to a sub-path
tcb hosting deploy ./dist /v2 --env-id <envId> --yes
# Deploy a single file
tcb hosting deploy ./index.html --env-id <envId> --yes
# Update only one file (incremental)
tcb hosting deploy ./dist/index.html /index.html --env-id <envId> --yes
# CI/CD: non-interactive with JSON output
tcb hosting deploy ./dist --env-id $ENV_ID --yes --json⚠️ Deploy overwrites existing files at the same path. There is no built-in versioning — consider cleaning old files before redeploying.
---
Workflow 2: Safe Deletion
# 1. Always preview first
tcb hosting delete --dry-run --env-id <envId>
# 2. Delete a specific file
tcb hosting delete path/to/file --env-id <envId> --yes
# 3. Delete a directory
tcb hosting delete path/to/dir --dir --env-id <envId> --yes⚠️ Always use --dry-run first before bulk deletions.⚠️ CDN cache delay: deleted files may remain accessible for 5-10 minutes. Flush CDN cache in console if needed.
Clean Redeploy Pattern
# Preview what will be deleted
tcb hosting delete --dry-run --env-id <envId>
# Delete all hosted files
tcb hosting delete --env-id <envId> --yes
# Deploy fresh build
tcb hosting deploy ./dist --env-id <envId> --yes---
Workflow 3: List and Download
List files (with pagination)
# List all files
tcb hosting list --env-id <envId>
# Paginated listing
tcb hosting list --env-id <envId> --limit 10 --offset 20
# JSON output
tcb hosting list --env-id <envId> --json⚠️ meta.total in list output excludes directories (Size=0 entries) — count may seem inaccurate.Download files
# Download a single file
tcb hosting download path/to/file.txt --env-id <envId>
# Download to a specific local path
tcb hosting download path/to/file.txt ./local --env-id <envId>
# Download entire directory
tcb hosting download path/to/dir ./local --dir --env-id <envId>
# Download full hosting backup
tcb hosting download / ./hosting-backup --dir --env-id <envId>---
Common Options
| Option | Description |
|---|---|
-e, --env-id <envId> | Target environment ID |
--yes | Skip interactive confirmation |
--json | JSON output for scripting |
--dry-run | Preview mode (delete only) |
-d, --dir | Operate on directory |
-l, --limit <n> | Max items returned (default 50) |
--offset <n> | Skip N items (default 0) |
---
Command Quick Reference
tcb hosting detail --env-id <id> # View hosting service info
tcb hosting deploy <localPath> [cloudPath] --env-id <id> # Deploy files
tcb hosting delete [cloudPath] --env-id <id> # Delete files
tcb hosting list --env-id <id> # List hosted files
tcb hosting download <cloudPath> [localPath] --env-id <id> # Download files---
Common Errors
| Error | Cause | Fix |
|---|---|---|
| "Hosting not enabled" | Hosting service not activated | Run tcb hosting detail -e <envId> to auto-enable |
| File still accessible after delete | CDN cache delay (5-10 min) | Wait or flush CDN cache in console |
meta.total looks wrong | Directories (Size=0) excluded from count | This is expected behavior |
| Deploy has no effect | Deploying to wrong path or env | Verify --env-id and cloud path; run tcb hosting list to check |
---
Self-Check
- [ ]
tcbCLI installed, version >= 3.0.0 - [ ] Logged in (
tcb login) and correct environment set (tcb env use <envId>) - [ ] Hosting service enabled (
tcb hosting detail --env-id <envId>) - [ ] Build output ready locally before deploying (e.g.
npm run buildcompleted) - [ ] For deletion: previewed with
--dry-runfirst - [ ] For CI/CD:
--env-id+--yesboth specified - [ ] CDN cache delay considered (5-10 min after updates/deletions)
MySQL Database Operations (tcb db)
Execute SQL, manage instances, backups, and slow queries for CloudBase MySQL via tcb db commands.
⚠️ MySQL commands live under `tcb db ...` (NOT tcb db mysql ...). Don't confuse with tcb db nosql ... (NoSQL).
When to Use
- Execute SQL queries or mutations against CloudBase MySQL
- Inspect, restart, or resize MySQL instances
- Create, list, restore, or delete backups
- Analyze slow queries for performance troubleshooting
Do NOT use for
- NoSQL/MongoDB operations → use
references/nosql.md(commands aretcb db nosql ...) - In-app MySQL queries via server SDK → use
cloud-functionsskill - Storage file management → use
references/storage.md - Complex stored procedures or multi-statement transactions → use a MySQL client directly
Command Quick Reference
tcb db execute Execute SQL statement
tcb db instance list List MySQL instances
tcb db instance restart Restart a MySQL instance
tcb db instance config get Read instance configuration
tcb db instance config set Resize CPU/memory
tcb db backup list List backups
tcb db backup create Create a backup
tcb db backup restore Restore from backup
tcb db backup drop Delete a backup
tcb db monitor slow-query Analyze slow queriesGlobal options
-e, --envId <envId>— target environment--json— structured output (use for automation)--yes— skip confirmation for destructive/confirmation-gated operations
⚠️ In --json mode, interactive prompts are suppressed — commands that need --instance-id or --yes will fail silently without them.
---
Workflow 1: Safe SQL Execution
Always start with read-only queries for discovery:
# Read-only query
tcb db execute -e <envId> --sql "SELECT * FROM users WHERE status = 'active' LIMIT 10" --read-only --json
# Simple connectivity test
tcb db execute -e <envId> --sql "SELECT 1" --read-only --json⚠️ Always use --read-only for SELECT queries to prevent accidental mutations.
Data mutations (INSERT/UPDATE/DELETE)
# Insert
tcb db execute -e <envId> --sql "INSERT INTO users (name, age, status) VALUES ('alice', 25, 'active')" --json
# Update (keep WHERE clauses narrow)
tcb db execute -e <envId> --sql "UPDATE users SET status = 'inactive' WHERE id = 1001" --json⚠️ Do NOT add --read-only to mutation SQL. Show the exact SQL to the user before execution.
⚠️ Always include a WHERE clause in UPDATE and DELETE. Without it, all rows are affected.
tcb db execute options
| Option | Description |
|---|---|
-s, --sql <sql> | Required — the SQL statement |
--read-only | Run in read-only mode |
--json | Rows for SELECT; affected-row info for mutations |
---
Workflow 2: Instance Management
Inspect instances
# List all instances
tcb db instance list -e <envId> --json
# Get instance configuration
tcb db instance config get -e <envId> --instance-id <instanceId> --jsonResize instance
# Step 1: Check current config
tcb db instance config get -e <envId> --instance-id <instanceId> --json
# Step 2: Resize (both --cpu and --memory required)
tcb db instance config set -e <envId> --instance-id <instanceId> --cpu 2 --memory 4 --yes⚠️ Resizing changes CPU and memory together. May cause brief service interruption.
⚠️ In --json mode, config set requires `--yes` — otherwise it fails silently (no interactive prompt available).
Restart instance
tcb db instance restart -e <envId> --instance-id <instanceId>⚠️ Restart causes service interruption. Only use when:
- Instance is unresponsive
- Configuration changes require restart
- User explicitly confirms after understanding impact
⚠️ In --json mode, --instance-id is required for restart, config get, and monitor slow-query.
---
Workflow 3: Backup and Restore
Create and list backups
# List existing backups
tcb db backup list -e <envId> --json
# List with time range
tcb db backup list -e <envId> --start-time "2026-03-01 00:00:00" --end-time "2026-03-31 23:59:59" --json
# Create a manual backup
tcb db backup create -e <envId>
# Create logical backup of specific databases
tcb db backup create -e <envId> --type logic --databases db1,db2 --name nightly-manualRestore from backup — two strategies
⚠️ Verify which strategy you need before running. Mixing flags causes validation failure.
# Strategy A: Snapshot rollback (requires --backup-id)
tcb db backup restore -e <envId> --strategy snapRollback --backup-id <backupId>
# Strategy B: Point-in-time rollback (requires --expect-time)
tcb db backup restore -e <envId> --strategy timeRollback --expect-time "2024-03-15 14:00:00"| Strategy | Required flag | Use case |
|---|---|---|
snapRollback | --backup-id | Restore from a known backup artifact |
timeRollback | --expect-time | Roll back to a verified timestamp |
⚠️ Restore is a cluster-level operation. Confirm scope and impact with the user.
Delete a backup
tcb db backup drop -e <envId> --backup-id <backupId> --yes⚠️ Backup deletion is irreversible. Confirm the backup ID and check retention/compliance requirements first.
Recommended backup workflow
# 1. List to identify the target
tcb db backup list -e <envId> --json
# 2. Create safety backup before risky operations
tcb db backup create -e <envId>
# 3. Restore if needed
tcb db backup restore -e <envId> --strategy snapRollback --backup-id <backupId>---
Workflow 4: Slow Query Analysis
# Basic slow query inspection
tcb db monitor slow-query -e <envId> --instance-id <instanceId> --json
# Scoped by time range and threshold
tcb db monitor slow-query -e <envId> --instance-id <instanceId> \
--start "2026-03-01 00:00:00" --end "2026-03-01 23:59:59" \
--threshold 1 --jsonmonitor slow-query options
| Option | Description |
|---|---|
--instance-id | Required in --json mode |
--start, --end | Time range filter |
--threshold | Local filter in seconds |
--order-by | QueryTime, LockTime, RowsExamined, or RowsSent |
--order-by-type | asc or desc |
--database | Filter by database name |
--username | Filter by user |
--limit, --offset | Pagination |
Analysis strategy: Sort by QueryTime first → pivot to RowsExamined to find inefficient scans → filter by --database or --username for shared workloads.
---
Real-World Scenarios
Inspect-first workflow (recommended starting point)
tcb db instance list -e <envId> --json
tcb db backup list -e <envId> --json
tcb db monitor slow-query -e <envId> --instance-id <instanceId> --jsonSafe read → mutate cycle
# Preview affected rows
tcb db execute -e <envId> --sql "SELECT COUNT(*) FROM logs WHERE created_at < '2025-01-01'" --read-only --json
# Delete after user confirmation
tcb db execute -e <envId> --sql "DELETE FROM logs WHERE created_at < '2025-01-01'" --json
# Verify
tcb db execute -e <envId> --sql "SELECT COUNT(*) FROM logs" --read-only --jsonFull backup-restore cycle
tcb db backup list -e <envId> --json # identify backups
tcb db backup create -e <envId> # safety backup
tcb db backup restore -e <envId> --strategy snapRollback --backup-id <backupId>Cleanup old backups
tcb db backup list -e <envId> --json # identify old backups
tcb db backup drop -e <envId> --backup-id <backupId> --yes---
Common Errors
| Error / Symptom | Cause | Fix |
|---|---|---|
Missing instance in --json mode | --instance-id omitted | Add --instance-id <id> explicitly |
config set fails silently in JSON mode | Missing --yes | Add --yes to skip suppressed prompt |
--sql missing | No SQL statement provided | Add --sql "..." |
| Backup restore validation error | Strategy/flag mismatch | snapRollback → --backup-id; timeRollback → --expect-time |
--cpu/--memory missing | Incomplete resize | Both --cpu and --memory are required |
UPDATE/DELETE affects all rows | Missing WHERE clause | Always add a WHERE condition |
| No rows returned for mutation | Expected result set from INSERT/UPDATE | Mutations return affected-row info, not rows |
| Timeout on large queries | Query scans too many rows | Add indexes, use LIMIT, or narrow the WHERE clause |
---
Self-Check
- [ ] Using
tcb db ...(nottcb db mysql ...) for MySQL commands? - [ ] Started with
--read-onlyfor exploratory queries? - [ ] Included
WHEREclause in allUPDATEandDELETEstatements? - [ ] Specified
--instance-idexplicitly (especially in--jsonmode)? - [ ] For
config set --json: included--yes? - [ ] For backup restore: verified correct strategy + matching required flag?
- [ ] For destructive ops (restart, resize, backup drop): confirmed with user?
- [ ] Used
--jsonfor automation and script consumption? - [ ] Showed exact SQL to user before executing mutations?
NoSQL Database Operations (tcb db nosql)
Execute MongoDB-style commands against CloudBase document database — CRUD, aggregation, backup, and restore.
⚠️ Always run `tcb db nosql execute --help` first — this is the most error-prone command family due to nested JSON encoding.
When to Use
- Execute MongoDB-style CRUD against CloudBase NoSQL document database
- Run aggregation or count commands on document collections
- Manage backup/restore workflows for document collections
- Query restoreable timestamps or collections
- Track restore task status
Do NOT use for
- MySQL/SQL database operations → use
references/mysql.md(commands aretcb db ...withoutnosql) - In-app database queries via Web/Mini-Program SDK → use
no-sql-web-sdkskill - Cloud function database access via server SDK → use
cloud-functionsskill - Storage file management → use
references/storage.md
Command Quick Reference
tcb db nosql execute Run Mongo-style commands
tcb db nosql backup time Discover restoreable timestamps
tcb db nosql backup collection List restoreable collections at a given time
tcb db nosql backup restore Submit a restore task
tcb db nosql backup task Track restore task status⚠️ Don't confuse tcb db nosql ... (NoSQL) with tcb db ... (MySQL) — they are different command families.
Global options
-e, --envId <envId>— target environment--json— structured output (use for automation)--tag <tag>— select instance when multiple document DBs exist in the environment
---
The MgoCommandParam Format (Critical)
Every execute call takes a --command argument: a JSON array of MgoCommandParam objects.
[
{
"TableName": "users",
"CommandType": "QUERY",
"Command": "{\"find\":\"users\",\"filter\":{\"status\":\"active\"},\"limit\":10}"
}
]⚠️ The Command field must be a JSON-encoded string (with escaped quotes), NOT a raw JSON object. This is the #1 source of errors.
Two-layer structure
1. Outer layer — the MgoCommands JSON array (parsed by the CLI) 2. Inner layer — the Command value: a stringified MongoDB shell command
Build process: Write the inner MongoDB JSON first → stringify it (escape all " as \") → paste into the Command field.
CommandType → Command template
CommandType | Command template |
|---|---|
QUERY | {"find":"<coll>","filter":{...},"limit":N} |
INSERT | {"insert":"<coll>","documents":[{...}]} |
UPDATE | {"update":"<coll>","updates":[{"q":{...},"u":{"$set":{...}}}]} |
DELETE | {"delete":"<coll>","deletes":[{"q":{...},"limit":1}]} |
COMMAND (count) | {"count":"<coll>","query":{...}} |
COMMAND (aggregate) | {"aggregate":"<coll>","pipeline":[...],"cursor":{}} |
Notes:
TableNameusually matches the target collection name.- ⚠️
UPDATEandDELETEcommonly fail because users pass an object instead of the requiredupdates/deletesarray. - ⚠️ Aggregation requires
"cursor":{}— omitting it causes an error.
---
Workflow 1: Query Documents
tcb db nosql execute -e <envId> --command \
'[{"TableName":"users","CommandType":"QUERY","Command":"{\"find\":\"users\",\"filter\":{\"status\":\"active\"},\"limit\":10}"}]' --json⚠️ Always start with a single read command before attempting writes.
---
Workflow 2: Insert Documents
tcb db nosql execute -e <envId> --command \
'[{"TableName":"products","CommandType":"INSERT","Command":"{\"insert\":\"products\",\"documents\":[{\"name\":\"Widget A\",\"price\":29.99},{\"name\":\"Widget B\",\"price\":49.99}]}"}]' --json---
Workflow 3: Update Documents
tcb db nosql execute -e <envId> --command \
'[{"TableName":"users","CommandType":"UPDATE","Command":"{\"update\":\"users\",\"updates\":[{\"q\":{\"name\":\"alice\",\"status\":\"pending\"},\"u\":{\"$set\":{\"status\":\"active\",\"age\":26}}}]}"}]'Inner Command (after unescaping) for reference:
{
"update": "users",
"updates": [{
"q": { "name": "alice", "status": "pending" },
"u": { "$set": { "status": "active", "age": 26 } }
}]
}---
Workflow 4: Delete Documents
tcb db nosql execute -e <envId> --command \
'[{"TableName":"sessions","CommandType":"DELETE","Command":"{\"delete\":\"sessions\",\"deletes\":[{\"q\":{\"expiredAt\":{\"$lt\":\"2024-01-01\"}},\"limit\":0}]}"}]' --json"limit": 1→ delete one matching document"limit": 0→ delete all matching documents
⚠️ Always preview with a QUERY command before running DELETE.
---
Workflow 5: Aggregation
tcb db nosql execute -e <envId> --command \
'[{"TableName":"orders","CommandType":"COMMAND","Command":"{\"aggregate\":\"orders\",\"pipeline\":[{\"$match\":{\"status\":\"done\"}},{\"$group\":{\"_id\":\"$product\",\"total\":{\"$sum\":\"$amount\"}}}],\"cursor\":{}}"}]' --json⚠️ The "cursor":{} field is required for aggregation — omitting it causes an error.
---
Workflow 6: Backup and Restore
Resolve restore inputs in order — do not skip steps:
# Step 1: Discover restoreable timestamps
tcb db nosql backup time -e <envId> --json
# Step 2: List restoreable collections at that time
tcb db nosql backup collection -e <envId> --time "2024-03-15 14:00:00" --json
# Step 3: Submit restore (creates NEW collections, does NOT overwrite)
tcb db nosql backup restore -e <envId> \
--time "2024-03-15 14:00:00" \
--tables '[{"OldTableName":"users","NewTableName":"users_restore_20240315"}]'
# Step 4: Track restore progress
tcb db nosql backup task -e <envId> --json⚠️ Restore creates new collections with NewTableName. Original collections remain untouched.
Backup command options
| Command | Required options |
|---|---|
backup time | -e <envId> |
backup collection | -e <envId>, --time; optionally --filters users,orders |
backup restore | -e <envId>, --time, --tables (non-empty JSON array) |
backup task | -e <envId> |
Validation rules
--tablesmust parse as a non-empty JSON array.--timeis required forbackup collectionandbackup restore.- Use
--tag <tag>when the environment has multiple document database instances.
---
Workflow 7: Multi-Collection Batch Query
tcb db nosql execute -e <envId> --command '[
{"TableName":"users","CommandType":"QUERY","Command":"{\"find\":\"users\",\"filter\":{},\"limit\":5}"},
{"TableName":"products","CommandType":"QUERY","Command":"{\"find\":\"products\",\"filter\":{\"price\":{\"$gt\":100}},\"limit\":5}"}
]' --json⚠️ Validate each command individually before batching multiple operations.
---
Shell Quoting Rules
- Wrap the entire
--commandvalue in single quotes ('...') in bash/zsh - Use double quotes inside JSON keys and string values
- Escape double quotes inside the inner
Commandstring as\" - ⚠️ If the command contains
$set,$gt, etc., single quotes prevent shell `$` interpolation
# CORRECT — single quotes protect $ and inner \"
tcb db nosql execute -e <envId> --command '[{"TableName":"users","CommandType":"UPDATE","Command":"{\"update\":\"users\",\"updates\":[{\"q\":{\"name\":\"alice\"},\"u\":{\"$set\":{\"status\":\"active\"}}}]}"}]'
# WRONG — double quotes cause shell to interpret $ and break JSON
tcb db nosql execute -e <envId> --command "[{"TableName":"users"...}]"Practical tips:
- Build the inner JSON in an editor first, then compress to one line for the shell.
- When debugging, validate the outer payload first (must be a JSON array), then inspect only the inner
Commandstring. - If parsing still fails, check for unescaped backslashes in the inner string.
Connector options (advanced)
Use --instance-id and --database-name only when targeting a specific connector. If not needed, omit them for the simplest working command.
---
Common Errors
| Error / Symptom | Cause | Fix |
|---|---|---|
--command parse failure | Not a valid JSON array | Validate JSON locally; must be [...] not {...} |
Command field rejected | Raw object instead of string | Stringify inner JSON: escape " as \" |
UPDATE/DELETE fails silently | Missing updates/deletes array | Use "updates":[{...}] not a bare object |
$set / $gt resolves to empty | Shell interprets $ as variable | Switch to single quotes around --command |
| Wrong database targeted | Multiple instances, no --tag | Add --tag <tag> |
--tables parse failure | Not a non-empty JSON array | Validate: [{"OldTableName":"x","NewTableName":"y"}] |
aggregate returns error | Missing "cursor":{} | Add \"cursor\":{} to the aggregate command |
| Restore seems to have no effect | Looking at original collection | Check the NewTableName collection instead |
---
Self-Check
- [ ] Ran
tcb db nosql execute --helpto verify current command syntax? - [ ]
--commandis a valid JSON array (not a single object)? - [ ] Inner
Commandfield is a JSON-encoded string (with escaped quotes)? - [ ] Used single quotes around
--commandvalue in shell? - [ ] Started with a read command before writes?
- [ ] For restore: discovered time → collections → submitted restore (in order)?
- [ ] Used
--tagwhen environment has multiple document DB instances? - [ ] Used
--jsonfor automation and debugging?
Permission — CloudBase CLI
CloudBase access control has three independent layers — know which one to use before running any command:
| Layer | Command | Controls |
|---|---|---|
| Resource Permission | tcb permission get/set | Access level on a specific resource (table, collection, function, storage) |
| Role | tcb role ... | Policy bundles + member assignments (identity dimension) |
| User | tcb user ... | Account attributes only (name, email, status) — NOT role binding |
⚠️ Role policies and resource permissions are two parallel systems with NO automatic sync. Changing a role policy does NOT affect permission get results, and vice versa. Audit both separately.---
When to Use
- Managing resource-level access (table/collection/function/storage access levels)
- Creating, updating, or deleting roles with policies and user assignments
- Managing user accounts (create, update status, delete)
- Auditing permission state across resources and roles
Do NOT use for
- Storage ACL rules (use
tcb-storagerules get/update) - CORS / domain / routing access (use
tcb-access) - CloudBase console access control (CLI-managed permissions only)
---
Workflow 1: Manage Resource Permissions (tcb permission)
Step 1 — Query current state
tcb permission get --env-id <envId> # all resource types
tcb permission get table --env-id <envId> # all tables
tcb permission get table:users,orders --env-id <envId> # specific resources (max 100)
tcb permission get function --env-id <envId> # functions⚠️ Do NOT usefunction:(colon with empty resource) — returns empty results. Usefunctioninstead.
Step 2 — Set permissions
# Fixed level
tcb permission set table:users --level readonly --env-id <envId>
tcb permission set storage:assets --level private --env-id <envId>
# Function (custom only, --rule required)
tcb permission set function --level custom \
--rule '{"*":{"invoke":"auth != null && auth.loginType != '\''ANONYMOUS'\''"}}' \
--env-id <envId>
# Rule without level => defaults to custom
tcb permission set collection:posts --rule '{"read": true, "write": false}' --env-id <envId>Combination rules:
- Must provide at least
--levelor--rule --rulewithout--level=> autocustom;customlevel requires--rulefunctiononly supportscustom- ⚠️
setrequirestype:resourcefor table/collection/storage — onlyfunctioncan omit resource name
Allowed levels by resource type
| Resource | Levels |
|---|---|
table | readonly, private, adminwrite, adminonly |
collection | readonly, private, adminwrite, adminonly, custom |
function | custom only |
storage | readonly, private, adminwrite, adminonly, custom |
---
Workflow 2: Manage Roles (tcb role)
Step 1 — List and inspect
tcb role list --env-id <envId>
tcb role list --type custom --detail --env-id <envId>
tcb role get --id <roleId> --detail --env-id <envId>⚠️role getquery conditions--id/--identity/--nameare mutually exclusive — pass exactly one.
Step 2 — Create or update (parameter sets differ!)
| Action | Policies param | Members param |
|---|---|---|
role create | --policies | --users |
role update | --add-policies / --remove-policies | --add-users / --remove-users |
⚠️ Do NOT use--add-policieswithcreate, or--policieswithupdate— they will fail.
# Create with preset policy codes
tcb role create --name "developer" --identity dev_role \
--policies '["FunctionsAccess","StoragesAccess"]' \
--users "u1001,u1002" --env-id <envId>
# Update: add policies + members
tcb role update --id <roleId> \
--add-policies '["CloudrunAccess"]' \
--add-users "u1003" --yes --env-id <envId>
# Update: remove
tcb role update --id <roleId> \
--remove-policies '["StoragesDeny"]' \
--remove-users "u1002" --yes --env-id <envId>Preset policy codes: AdministratorAccess, FunctionsAccess, StoragesAccess, CloudrunAccess, FunctionsDeny, StoragesDeny, CloudrunDeny
Step 3 — Custom policy objects
Policies array can mix preset codes (strings) and custom objects:
tcb role update --id <roleId> --add-policies '[
"FunctionsAccess",
{
"code": "api_guard",
"name": "API Guard",
"description": "Allow /api, deny /api/admin",
"effect": "deny",
"expression": {
"version": "1.0",
"statement": [
{"action": "functions:/api/*", "resource": "*", "effect": "allow"},
{"action": "functions:/api/admin/*", "resource": "*", "effect": "deny"}
]
}
}
]' --yes --env-id <envId>Policy object fields: code (required), name (required), description, effect (allow|deny), expression (JSON object, NOT string) with version ("1.0") and statement array.
⚠️expressionmust be a JSON object, not a string. Whenallowanddenyboth match, deny wins.
Step 4 — System role constraints
| Role Type | Modify users | Modify policies | Modify name |
|---|---|---|---|
| 管理员 (Admin) | ✅ | ❌ | ❌ |
| 注册用户/组织成员/匿名用户/所有用户 | ❌ | ✅ | ❌ |
| Custom roles | ✅ | ✅ | ✅ |
Step 5 — Delete roles
tcb role delete <roleId1> <roleId2> --yes --env-id <envId> # max 100, custom only---
Workflow 3: Manage Users (tcb user)
# List (filters combinable)
tcb user list --name alice --email a@example.com --env-id <envId>
# Create
tcb user create alice --uid u1001 --type internalUser --status ACTIVE --env-id <envId>
# Update (NO --role parameter!)
tcb user update u1001 --status BLOCKED --env-id <envId>
# Delete (max 100)
tcb user delete u1001 u1002 --yes --env-id <envId>⚠️tcb user updatehas NO--roleparam. To assign roles, usetcb role create --usersortcb role update --add-users.
---
Workflow 4: Audit & Revoke
# 1) Full role inventory
tcb role list --detail --env-id <envId> --json
# 2) Spot-check critical resources
tcb permission get table:users,orders --env-id <envId>
tcb permission get function --env-id <envId>
# 3) Revoke temporary access
tcb role update --id <roleId> --remove-users "u_temp" --yes --env-id <envId>
# 4) Optional: block account
tcb user update u_temp --status BLOCKED --env-id <envId>---
Decision Guide
| Goal | Command |
|---|---|
| Change a resource's access level | permission set |
| Manage access policies for an identity group | role create/update |
| Assign user to a role | role create --users (new) or role update --add-users (existing) |
| Change user profile/status | user update |
| Full audit | role list --detail + permission get on key resources |
---
Command Quick Reference
tcb permission get [resourceArg] # Query resource permissions
tcb permission set <resourceArg> # Set resource permissions
tcb role list # List roles
tcb role get # Get single role (--id/--identity/--name, pick ONE)
tcb role create # Create role (--policies, --users)
tcb role update # Update role (--add-*/-remove-*, --id required)
tcb role delete <roleIds...> # Delete roles (custom only, max 100)
tcb user list # List users
tcb user create <name> # Create user
tcb user update <uid> # Update user (NO --role!)
tcb user delete <uids...> # Delete users (max 100)Global flags: --env-id <envId> (required), --json (machine output), --yes (skip confirmation for CI)
---
Common Errors
| Error | Cause | Fix |
|---|---|---|
| "请且仅传入一个查询条件" | role get with multiple or zero query conditions | Use exactly one of --id/--identity/--name |
| "资源类型不支持权限级别" | permission set level incompatible with resource type | Check allowed levels table above |
| "权限级别为 custom 时,需要提供 --rule" | Missing --rule with custom level | Add --rule JSON |
| JSON parse error | --policies/--add-policies not valid JSON array | Validate JSON before execution |
| Role update silently fails | Violating system role constraints | Check system role table — admin can't change policies, etc. |
| "不存在的命令" | Using permission list or role detail | Correct: permission get / role get |
---
Real-World Scenarios
Scenario 1: Team Onboarding
tcb role list --type custom --env-id <envId> # confirm role exists
tcb role update --id <devRoleId> --add-users "<newUid>" --yes --env-id <envId>
tcb role get --id <devRoleId> --detail --env-id <envId> # verifyScenario 2: Contractor Temporary Access + Revocation
# Grant
tcb role create --name "contractor-ro" --identity contractor_ro \
--policies '["StoragesAccess"]' --env-id <envId>
tcb role update --id <roleId> --add-users "<contractorUid>" --yes --env-id <envId>
# Revoke on contract end
tcb role update --id <roleId> --remove-users "<contractorUid>" --yes --env-id <envId>
tcb user update <contractorUid> --status BLOCKED --env-id <envId>Scenario 3: Store RBAC (Owner / Manager / Clerk)
# Owner: full access + admin console
tcb role create --name "owner" --identity shop_owner \
--policies '["FunctionsAccess",{"code":"owner_admin","name":"Admin Access","effect":"allow","expression":{"version":"1.0","statement":[{"action":"functions:/shop/admin/*","resource":"*","effect":"allow"}]}}]' \
--env-id <envId>
# Clerk: POS only, deny refund
tcb role create --name "clerk" --identity shop_clerk \
--policies '[{"code":"clerk_pos","name":"POS Only","effect":"allow","expression":{"version":"1.0","statement":[{"action":"functions:/shop/pos/*","resource":"*","effect":"allow"},{"action":"functions:/shop/pos/refund/*","resource":"*","effect":"deny"}]}}]' \
--env-id <envId>
# Resource baseline (separate from role policies!)
tcb permission set table:orders --level private --yes --env-id <envId>
tcb permission set function --level custom --rule '{"*":{"invoke":"auth != null"}}' --yes --env-id <envId>---
Self-Check
- [ ]
tcb>= 3.0.0 and logged in with correct environment - [ ] Identified correct command:
permission(resource) vsrole(identity) vsuser(account) - [ ] For
permission set: resource format istype:resource(exceptfunction) - [ ] For
role create: using--policies/--users(NOT--add-*) - [ ] For
role update: using--add-*/--remove-*(NOT--policies),--idis set - [ ] For
role get: exactly ONE of--id/--identity/--name - [ ] System role constraints checked before update
- [ ] Policy JSON:
expressionis object (not string), hasversion+statement - [ ]
--yesadded for CI;--jsonadded for programmatic parsing - [ ] Audited BOTH role policies AND resource permissions (they are independent)
Cloud Storage Management (tcb storage)
Manage CloudBase cloud storage — upload, download, delete, copy/move files, generate temp URLs, and configure ACL rules.
When to Use
- Upload or download files to/from CloudBase cloud storage
- Delete files (single, batch, or wildcard-based)
- Generate temporary access URLs for stored files
- Copy or move files within cloud storage
- Manage storage ACL permission rules
Do NOT use for
- Static website hosting with CDN → use
references/hosting.md - Web app deployment → use
references/app.md - Database operations → use
references/mysql.mdorreferences/nosql.md - In-app file operations via Web/Mini-Program SDK → use
cloud-storage-webskill - Large-scale data migration (>10 GB) → use the console bulk-import tool
Command Quick Reference
tcb storage upload Upload local file(s) or directory
tcb storage download Download file(s) or directory
tcb storage rm Delete file(s) — supports wildcards and --dry-run
tcb storage list List files in storage
tcb storage url Get temporary access URL
tcb storage detail Get file metadata
tcb storage cp Copy or move files in cloud
tcb storage rules get Get storage ACL rules
tcb storage rules update Update storage ACL rules⚠️ storage delete, storage get-acl, storage set-acl are deprecated — use the new commands:
| Old (deprecated) | New command |
|---|---|
storage delete | storage rm |
storage get-acl | storage rules get |
storage set-acl | storage rules update |
---
Workflow 1: Upload Files
# Single file
tcb storage upload ./logo.png images/logo.png -e <envId>
# Directory (recursive)
tcb storage upload ./images images/ -e <envId>
# With retry (0-10 retries, default 1)
tcb storage upload ./images images/ --times 3 --interval 1000 -e <envId>⚠️ `cloudPath` must NOT start with `/` — this is the #1 upload error.
# WRONG — errors with "cloudPath cannot start with /"
tcb storage upload ./logo.png /images/logo.png
# CORRECT
tcb storage upload ./logo.png images/logo.pngFor 50+ file uploads, check cloudbase-error.log for partial failure details. Retry with --times 5 --interval 1000.
---
Workflow 2: Download Files
# Single file
tcb storage download images/logo.png ./logo.png -e <envId>
# Directory — requires --dir
tcb storage download images/ ./images --dir -e <envId>⚠️ Missing --dir when downloading a folder will fail or only affect one file.
---
Workflow 3: Safe File Deletion
Always preview before executing:
# 1. Dry-run preview (no actual deletion)
tcb storage rm "*.tmp" --dry-run -e <envId>
# 2. Execute after confirming
tcb storage rm "*.tmp" --force -e <envId>Deletion patterns
tcb storage rm file.txt -e <envId> # Single file
tcb storage rm file1.txt file2.txt -e <envId> # Multiple files
tcb storage rm "*.log" -e <envId> # Wildcard — current dir only
tcb storage rm "temp/**" -e <envId> # Recursive wildcard
tcb storage rm folder/ --dir -e <envId> # Directory⚠️ Wildcard patterns must be quoted — use "*.log", not *.log. Unquoted globs expand against your local filesystem, not cloud storage.
⚠️ Deleting 2+ files triggers a confirmation prompt. Use --force to skip (required in CI/scripts).
Wildcard rules
| Pattern | Meaning |
|---|---|
* | Match any filename in current directory (not across /) |
** | Match any path including / (recursive) |
? | Match single character (not /) |
# Only root-level .log files
tcb storage rm "*.log" -e <envId>
# .log files in ALL directories
tcb storage rm "**/*.log" -e <envId>---
Workflow 4: Temporary URL Generation
# Default expiry: 3600 seconds
tcb storage url images/logo.png -e <envId>
# Custom expiry (1-86400 seconds)
tcb storage url data.json --expires 7200 -e <envId>---
Workflow 5: Copy and Move Files
tcb storage cp images/a.jpg backup/a.jpg -e <envId> # Copy
tcb storage cp old/data.json new/data.json --move -e <envId> # Move (copy + delete source)
tcb storage cp src.txt dest.txt --force -e <envId> # Overwrite existing
tcb storage cp src.txt dest.txt --skip-existing -e <envId> # Skip if exists⚠️ cp only supports file-level operations, NOT directories. To copy a directory, script a loop over tcb storage list output and copy each file individually.
---
Workflow 6: ACL Permission Management
# Get current rules
tcb storage rules get -e <envId>
# Set predefined ACL
tcb storage rules update --acl READONLY -e <envId>
# Set custom rules
tcb storage rules update --acl CUSTOM \
--rule '{"read": true, "write": "auth.openid == resource.openid"}' -e <envId>Predefined ACL types
| ACL value | Read | Write | Use case |
|---|---|---|---|
READONLY | Everyone | Creator + admin | Public assets (images, documents) |
PRIVATE | Creator + admin | Creator + admin | User private data (default) |
ADMINWRITE | Everyone | Admin only | Read-only public resources |
ADMINONLY | Admin only | Admin only | Sensitive internal data |
CUSTOM | Per rule | Per rule | Fine-grained access control |
Custom rule format
{ "read": <condition>, "write": <condition> }At least one of read or write must be present. Condition values:
true— unrestrictedfalse— deny all- Expression string — evaluated per request
| Variable | Description |
|---|---|
auth.openid | OpenID of the currently authenticated user |
resource.openid | OpenID of the user who uploaded the file |
Example rules:
# Public read, owner-only write
--rule '{"read": true, "write": "auth.openid == resource.openid"}'
# Authenticated users only (read + write)
--rule '{"read": "auth != null", "write": "auth != null"}'
# Public read, no writes
--rule '{"read": true, "write": false}'---
Real-World Scenarios
Static asset deploy
npm run build
tcb storage upload ./dist/ website/ -e <envId>
tcb storage rules update --acl READONLY -e <envId>
tcb storage list website/ -e <envId> # verifyUpload user content with signed URL
tcb storage upload ./uploads/avatar-001.jpg avatars/user-001.jpg -e <envId>
tcb storage url avatars/user-001.jpg --expires 3600 -e <envId>
tcb storage detail avatars/user-001.jpg -e <envId>Backup and restore files
tcb storage download backups/ ./local-backups/ --dir -e <envId>
tcb storage upload ./local-backups/ backups/ -e staging-env-xxx # restore to different env
tcb storage list backups/ -e <envId> # verify file countBatch cleanup old files
tcb storage rm "temp/**" --dry-run -e <envId> # preview
tcb storage rm "temp/**" --force -e <envId> # execute
tcb storage rm "**/*.log" --force -e <envId> # cross-directory cleanupCopy files for migration
tcb storage cp data/report.pdf archive/2024/report.pdf -e <envId>
tcb storage cp old-path/config.json new-path/config.json --move -e <envId>---
Common Errors
| Error / Symptom | Cause | Fix |
|---|---|---|
cloudPath cannot start with / | Leading / in cloud path | Remove the leading / |
FILE_NOT_FOUND | File doesn't exist or wrong path | Check with tcb storage list; ensure no leading /; use --dir for folders |
Partial upload (failedCount > 0) | Network issues on large batch | Retry: --times 5 --interval 1000; check cloudbase-error.log |
| Delete hangs in CI | Confirmation prompt blocking | Add --force |
cp destination already exists | Target file present | Use --force (overwrite) or --skip-existing |
cp silently skips subdirectories | cp is file-only | Loop over tcb storage list and copy each file |
command not found: delete | Deprecated command | Use tcb storage rm |
command not found: get-acl | Deprecated command | Use tcb storage rules get / rules update |
JSON output key fields
| Command | Key fields |
|---|---|
storage rm (success) | { deletedCount, files } |
storage rm (not found) | { error: true, code: "FILE_NOT_FOUND", notFoundPaths } |
storage list | [{ key, lastModified, eTag, size }] + total |
storage url | { url, expires } |
storage detail | { size, type, date, eTag } |
storage rules get | { acl, aclDesc, rule } |
Debugging tips
tcb storage detail images/logo.png -e <envId> # check file exists + metadata
tcb storage list images/ -e <envId> # list directory contents
tcb storage rm "temp/**" --dry-run -e <envId> # preview before delete
tcb storage rm file.txt --json -e <envId> # script-friendly output---
Self-Check
- [ ]
cloudPathdoes NOT start with/? - [ ] Used
--dry-runbefore batch/wildcard deletions? - [ ] Wildcard patterns are properly quoted in shell?
- [ ] Used new commands (
rm,rules get/update) not deprecated ones? - [ ] Used
--dirfor directory download/delete? - [ ] Used
--forcefor non-interactive CI/script usage? - [ ] Verified result with
list/detailafter each operation?