Exit Code
CloudBase CLI uses structured Exit Codes (Exit Codes) to represent command execution results, facilitating CI/CD pipelines, scripts, and automation tools in error handling and retry decision-making.
Why Exit Codes Are Needed
Exit code is a standard mechanism in Unix/Linux processes, used to inform the caller whether the command was successful and the classification of failure reasons:
1. CI/CD Process Control
# GitHub Actions Sample
- name: Deploy function
run: tcb fn deploy app --env-id ${{ secrets.ENV_ID }}
continue-on-error: false # Non-zero exit codes halt the pipeline
2. Shell Script Error Handling
#!/bin/bash
set -e # Exit immediately upon encountering a non-zero exit code
tcb fn deploy app --env-id my-env
if [ $? -eq 2 ]; then
echo "Authentication failed, please log in again"
tcb login
fi
3. Conditional Execution and Retry
# Deploy static resources only upon successful function deployment
tcb fn deploy && tcb hosting deploy
# Automatic Retry on Authentication Failure
tcb fn list || (tcb login && tcb fn list)
4. Automated Testing
# Test script validates CLI behavior
tcb fn delete non-existent-func
EXIT_CODE=$?
if [ $EXIT_CODE -eq 4 ]; then
echo "✅ Resource not found error code handled correctly"
else
echo "❌ Expected exit code 4, actual $EXIT_CODE"
exit 1
fi
Exit Code Definition
| Exit Code | Meaning | Trigger Scenario | Recommended Action |
|---|---|---|---|
| 0 | Success | Command executed successfully | Proceed to next step |
| 1 | General Error | Unclassified Error (Catch-all) | View error message, manually troubleshoot |
| 2 | Authentication Failure | Not logged in, Token expired, Insufficient permissions | Execute tcb login to log in again |
| 3 | Parameter Error | Missing required parameters, Invalid format, Illegal enum values | Check command parameters, refer to --help |
| 4 | Resource Not Found | Invalid function name/environment ID, collection does not exist, etc. | Verify resource name is correct |
| 5 | Cloud API Error | CloudBase API returned error, network timeout | Check network connection, view --verbose logs |
| 6 | Local File Error | cloudbaserc.json missing/corrupted, path does not exist | Check configuration file and path |
Use Cases
Scenario 1: Conditional Execution
# Deploy static resources only upon successful function deployment
tcb fn deploy app && tcb hosting deploy
Scenario 2: Error Capture and Handling
#!/bin/bash
tcb fn deploy app --env-id my-env
EXIT_CODE=$?
case $EXIT_CODE in
0)
echo "✅ Deployment succeeded"
;;
2)
echo "❌ Authentication failed, please log in again"
tcb login
;;
3)
echo "❌ Parameter error, please check the command"
exit 1
;;
4)
echo "❌ Resource does not exist"
exit 1
;;
5)
echo "⚠️ Cloud API error, retrying in 5 seconds..."
sleep 5
tcb fn deploy app --env-id my-env
;;
*)
echo "❌ Unknown error (exit code $EXIT_CODE)"
exit 1
;;
esac
Scenario 3: Retry Mechanism
#!/bin/bash
MAX_RETRIES=3
RETRY_DELAY=5
for i in $(seq 1 $MAX_RETRIES); do
tcb fn deploy app --env-id my-env
EXIT_CODE=$?
if [ $EXIT_CODE -eq 0 ]; then
echo "✅ Deployment succeeded"
exit 0
elif [ $EXIT_CODE -eq 5 ]; then
echo "⚠️ Cloud API error, retrying in $RETRY_DELAY seconds (attempt $i/$MAX_RETRIES)"
sleep $RETRY_DELAY
else
echo "❌ Non-retryable error (exit code $EXIT_CODE)"
exit $EXIT_CODE
fi
done
echo "❌ Failed after $MAX_RETRIES retries"
exit 1
Scenario 4: Batch Operations
#!/bin/bash
FUNCTIONS=("func1" "func2" "func3")
FAILED=()
for func in "${FUNCTIONS[@]}"; do
tcb fn deploy "$func" --yes
if [ $? -ne 0 ]; then
FAILED+=("$func")
fi
done
if [ ${#FAILED[@]} -gt 0 ]; then
❌ The following functions failed to deploy:
printf '%s\n' "${FAILED[@]}"
exit 1
else
All functions deployment succeeded
fi
Scenario 5: Makefile
.PHONY: deploy test clean
deploy:
@echo "Deploying functions..."
@tcb fn deploy app --env-id $(ENV_ID)
@echo "Deploying static resources..."
@tcb hosting deploy --env-id $(ENV_ID)
test:
@echo "Running tests..."
@tcb fn invoke app --env-id $(ENV_ID) --data '{"test": true}'
@if [ $$? -eq 0 ]; then \
echo "✅ Tests passed"; \
else \
echo "❌ Tests failed"; \
exit 1; \
fi
clean:
@echo "Cleaning up resources..."
@tcb fn delete app --yes --env-id $(ENV_ID) || true
CI/CD Best Practices
GitHub Actions
name: Deploy to CloudBase
on:
push:
branches: [main]
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Setup Node.js
uses: actions/setup-node@v3
with:
node-version: '18'
- name: Install CloudBase CLI
run: npm install -g @cloudbase/cli
- name: Login to CloudBase
run: |
echo "${{ secrets.CLOUDBASE_SECRET_ID }}" > /tmp/secret_id
echo "${{ secrets.CLOUDBASE_SECRET_KEY }}" > /tmp/secret_key
tcb login --key --secretId $(cat /tmp/secret_id) --secretKey $(cat /tmp/secret_key)
- name: Deploy Function
id: deploy
run: |
tcb fn deploy app --env-id ${{ secrets.ENV_ID }} --json --yes
continue-on-error: true
- name: Handle Deployment Result
if: failure()
run: |
EXIT_CODE=${{ steps.deploy.outcome }}
if [ "$EXIT_CODE" = "2" ]; then
echo "Authentication failed, check the key configuration"
exit 1
elif [ "$EXIT_CODE" = "5" ]; then
echo "Cloud API error, retrying in 5 seconds"
sleep 5
tcb fn deploy app --env-id ${{ secrets.ENV_ID }} --json --yes
else
echo "Deployment failed (exit code $EXIT_CODE)"
exit 1
fi
GitLab CI
deploy:
stage: deploy
image: node:18
script:
- npm install -g @cloudbase/cli
- tcb login --key --secretId $SECRET_ID --secretKey $SECRET_KEY
- tcb fn deploy app --env-id $ENV_ID --json --yes
retry:
max: 2
when:
- script_failure # Retry only when script fails
only:
- main
Jenkins
pipeline {
agent any
stages {
stage('Deploy') {
steps {
script {
def result = sh(
script: 'tcb fn deploy app --env-id ${ENV_ID} --json --yes',
returnStatus: true
)
if (result == 0) {
echo '✅ Deployment succeeded'
} else if (result == 2) {
error '❌ Authentication failed, check the key configuration'
} else if (result == 5) {
echo '⚠️ Cloud API error, retrying...'
sleep 5
sh 'tcb fn deploy app --env-id ${ENV_ID} --json --yes'
} else {
error "❌ Deployment failed (exit code ${result})"
}
}
}
}
}
}
Debugging Methods
1. View Exit Code
tcb fn deploy app
echo "Exit Code: $?"
2. Use --verbose to view detailed logs
tcb fn deploy app --verbose
3. Use --json to Obtain Structured Error Information
tcb fn deploy app --json
Example Output:
{
"error": {
"code": "FUNCTION_NOT_FOUND",
"message": "Function app does not exist",
"exit_code": 4
}
}
Precautions
Exit code is not HTTP status code
Exit code4indicates "resource does not exist", not HTTP 404. Exit code5indicates "Cloud API error", not HTTP 500.--yesdoes not affect the exit code
--yesonly skips confirmation prompts and does not change the command execution results or exit code.Pipeline operations require
set -e
In Shell scripts, useset -eto ensure that any command failure in the pipeline will abort the execution:#!/bin/bash
set -e # Exit immediately upon encountering a non-zero exit code
tcb fn deploy app
tcb hosting deployIn CI/CD, it is recommended to use
--json
--jsonoutputs structured data, facilitating the parsing of error messages and extraction of fields.