
Alibabacloud Ecs Code Deploy
- 166 installs
- 208 repo stars
- Updated August 4, 2026
- aliyun/alibabacloud-aiops-skills
alibabacloud-ecs-code-deploy is a Claude skill that installs the Aliyun CLI and deploys applications or AI agents to Alibaba Cloud ECS via aliyun appmanager.
About
This skill installs the Alibaba Cloud CLI and deploys projects to Alibaba Cloud ECS using aliyun appmanager commands. It follows an enforced workflow of environment check, init, price check, deploy, and verify. A developer uses it to deploy applications or AI agents to ECS, including from a git URL or the current directory.
- Installs the Aliyun CLI and deploys projects to ECS via aliyun appmanager
- Non-interactive mode with structured JSON and streaming NDJSON output
- Enforced deploy workflow with pre-deploy price check and log verification
Alibabacloud Ecs Code Deploy by the numbers
- 166 all-time installs (skills.sh)
- Ranked #437 of 1,435 DevOps & CI/CD skills by installs in the Skillselion catalog
- Data as of Aug 5, 2026 (Skillselion catalog sync)
alibabacloud-ecs-code-deploy capabilities & compatibility
Requires Alibaba Cloud credentials; deploying to ECS incurs cloud and OSS charges
- Capabilities
- devops · ci cd · orchestration
- Works with
- aws · github
- Use cases
- devops · ci cd · orchestration
- Runs
- Runs locally
- Pricing
- Bring your own API key
What alibabacloud-ecs-code-deploy says it does
Install Alibaba Cloud CLI (aliyun) and deploy projects to Alibaba Cloud ECS using aliyun appmanager commands.
`aliyun appmanager` is an Agent-friendly CLI tool for one-click deployment of applications (App) and AI Agents to Alibaba Cloud ECS.
npx skills add https://github.com/aliyun/alibabacloud-aiops-skills --skill alibabacloud-ecs-code-deployAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 166 |
|---|---|
| repo stars | ★ 208 |
| Last updated | August 4, 2026 |
| Repository | aliyun/alibabacloud-aiops-skills ↗ |
What it does
Deploy applications and AI agents to Alibaba Cloud ECS using aliyun appmanager commands.
Who is it for?
Deploying an app or AI agent to Alibaba Cloud ECS with an enforced, verified workflow
Skip if: Deploying to non-ECS or non-Alibaba-Cloud targets
When should I use this skill?
A developer wants to deploy a project or AI agent to Alibaba Cloud ECS
What you get
Deploys the project to ECS and verifies the deployment via logs before reporting success.
- Deployed application or AI agent on ECS
- Console link, cost reminder, and management commands
By the numbers
- 8-step deploy todo list
- requires aliyun CLI >= 3.3.19
Files
Deploy to Alibaba Cloud ECS via aliyun appmanager
Overview
aliyun appmanager is an Agent-friendly CLI tool for one-click deployment of applications (App) and AI Agents to Alibaba Cloud ECS. It supports non-interactive mode (--non-interactive), structured JSON output (--output json), and streaming NDJSON responses.
Default behavior: When user invokes /alibabacloud-ecs-code-deploy without specifying a project path or URL, deploy the current working directory project to Alibaba Cloud ECS. If user provides a git URL, clone it to the current directory first, then cd into the cloned directory and proceed with deployment.
EXECUTION ORDER: The Agent MUST follow the "Complete Deployment Workflow" section at the bottom of this document for the correct execution sequence. The Task sections below are organized by topic for reference — their numbering does NOT imply execution order.
---
MANDATORY: Create Todo List Before Starting
Before executing any step, the Agent MUST create a todo list with ALL of the following items. Do NOT omit any item. Do NOT start deployment until the todo list is created.
Todo list (Deploy to Alibaba Cloud ECS):
[ ] 0. Resolve $SKILL_DIR (cross-platform path — MUST run first; see "Step 0" below)
[ ] 1. Environment pre-check (MUST run deploy_toolkit.py check; manual commands FORBIDDEN as replacement)
[ ] 2. Obtain project (clone git URL here if needed; skip for local projects)
── Check whether .appmanager/config.yaml already exists (repeat-deploy shortcut) ──
│ Exists + new ECS (no instanceId) → skip 3-5, start from 5.5 (price check)
│ Exists + existing ECS (has instanceId) → skip 3-5.5, jump to 6 (deploy)
│ Does not exist → proceed normally from 3
───────────────────────────────────────────────────────────────────────────────
[ ] 3. Read project (README.md -> quick-deploy method) + identify type (agent / app)
[ ] 4. Ask user for deployment config (region + new ECS / existing ECS)
[ ] 5. Init + generate scripts (appmanager init -> write start/stop scripts to config.yaml)
[ ] 5.5. Pre-deploy price check + risk warning (MUST run deploy_toolkit.py price; confirm price / OSS billing / existing-ECS impact / group overwrite item by item)
[ ] 6. Deploy (MUST run deploy_toolkit.py deploy; manual deploy command FORBIDDEN as replacement)
[ ] 7. Verify (MUST run deploy_toolkit.py verify; manual status command FORBIDDEN as replacement)
[ ] 8. Output final result (console link + cost reminder + management commands)⛔ SCRIPT-FIRST RULE: Steps 1, 5, 6, 7 have a dedicated toolkit script at$SKILL_DIR/scripts/deploy_toolkit.py(where$SKILL_DIRis resolved in Step 0 below — works on Qoder, Claude Code, and any other platform). The Agent MUST run the corresponding subcommand DIRECTLY as the FIRST and ONLY action for that step — NEVER run manual CLI commands (likealiyun version, version checks, credential checks) BEFORE or INSTEAD of the script. The script already handles ALL checks internally. Manual commands are ONLY allowed as fallback if the script file itself does not exist.
>
❌ WRONG (Step 1): Runaliyun version→ check version → run~/.aliyun/appmanager-venv/bin/python ...→ check version → THEN rundeploy_toolkit.py check
✅ CORRECT (Step 1): Run python3 "$SKILL_DIR/scripts/deploy_toolkit.py" check → if exit 1, fix the issue it reports → if script file missing, THEN fall back to manual checksItem 6 is NON-NEGOTIABLE. An Agent that skips log verification and directly outputs "deployment succeeded" has NOT completed this skill correctly. If deploy_toolkit.py verify exits 1 (failed), the Agent MUST fix the issue and re-deploy before proceeding to item 7.---
Step 0 (MANDATORY): Resolve $SKILL_DIR — Cross-Platform Path
The toolkit script lives at<skill-root>/scripts/deploy_toolkit.py. Different platforms install skills to different locations (Qoder/Claude Code/Qwen/...). The Agent MUST resolve the absolute skill root once at session start and reuse it everywhere$SKILL_DIRappears below. Hardcoding any platform-specific path is FORBIDDEN.
See [references/skill-dir-resolution.md](references/skill-dir-resolution.md) for the full 10-candidate detection algorithm, the `export + test -f` verify snippet, and Pattern A / Pattern B / ⛔ Anti-pattern usage rules.
Quick recap (read the reference for details):
- ✅ Pattern A (persistent shell):
export SKILL_DIR="/abs/path"then laterpython3 "$SKILL_DIR/scripts/deploy_toolkit.py" <sub> - ✅ Pattern B (fresh shell per call): inline the absolute path —
python3 "/abs/path/scripts/deploy_toolkit.py" <sub> - ⛔ Anti-pattern:
SKILL_DIR=/path python3 "$SKILL_DIR/..."— outer shell expands$SKILL_DIRBEFORE the prefix assignment, producing/scripts/deploy_toolkit.pyand ENOENT. If you seepython3: can't open file '/scripts/deploy_toolkit.py', switch to Pattern A or B.
---
Task 1: Install Alibaba Cloud CLI
Primary action: Run python3 "$SKILL_DIR/scripts/deploy_toolkit.py" check — it checks CLI version + appmanager-cli version + credentials in one run. Only if the script file is missing, use the fallback in references/init-and-credentials.md.
MUST — Handling unmet environment prerequisites: When check exits 1 because the aliyun CLI is missing or older than 3.3.19 (or appmanager-cli is missing/outdated), the Agent MUST NOT stop the workflow silently. The required flow is:1. CLI NOT installed → Auto-install directly without asking user — execute the install command (see snippet below or references/init-and-credentials.md for the right arch), then re-run deploy_toolkit.py check to confirm.2. CLI already installed → ASK the user first — show the detected version + the required version + the upgrade command, and ask for explicit consent (e.g. "aliyun CLI 3.3.4 is already installed but below the required >= 3.3.19 for appmanager; approve upgrade (overwrite-install into /usr/local/bin, requires sudo)?"). Never assume yes; never paste credentials.
- On approval — execute the install/upgrade command, then re-run deploy_toolkit.py check to confirm.- On refusal — stop with the refusal as the reason. Do NOT continue with the older version (deployment will fail anyway).
>
The toolkit'scheckoutput already includes an→ AGENT: DO NOT stop. ASK user ...line for each fixable issue — follow it verbatim (except for the "not installed" case, which is auto-handled).
>
MUST — Upgrade method priority (avoid the "repeated upgrade" pitfall:/usr/local/bin/is often shadowed by earlier PATH entries like/opt/homebrew/bin):
1. brew-managed (checkprints "managed by Homebrew") ->brew upgrade aliyun-cli; do NOT overwrite/usr/local/bin/again.
2. sudo available -> overwrite into/usr/local/bin/, then verify:hash -r && which -a aliyun && aliyun version.
3. No sudo -> install to~/bin/, ask user to approve appendingexport PATH="$HOME/bin:$PATH"to~/.zshrc/~/.bashrc.
>
After install/upgrade, ALWAYS rerundeploy_toolkit.py checkto confirm. Ifwhich -a aliyunstill shows the old binary first, fix PATH order — DO NOT repeat the same overwrite.
AI-Mode Configuration (MANDATORY after CLI install)
⛔ MUST configure AI-Mode: Agent MUST ensure AI-Mode is properly configured before running anyaliyun appmanagercommands.deploy_toolkit.py checkhandles this internally; the commands below are for manual fallback only.
aliyun configure ai-mode enable
aliyun configure ai-mode set-user-agent --user-agent "AlibabaCloud-Agent-Skills/alibabacloud-ecs-code-deploy"
aliyun plugin update
aliyun configure ai-mode show # verify: enabled=true, user-agent set
aliyun configure ai-mode disable # only when troubleshooting---
Task 2: Configure Credentials
deploy_toolkit.py check already validates credentials. Only if credentials are missing/invalid, see references/init-and-credentials.md for the default-credential-chain remediation flow.
⛔ PREFER OAuth OVER AK: This skill SHOULD guide users to use OAuth authentication as the PRIMARY method for providing Alibaba Cloud permissions. OAuth is more secure and convenient than AccessKey (no long-term secret storage needed). The Agent MUST present OAuth as the first option before mentioning AK-based methods.
>
OAuth Login Guide: Instruct the user to run the following command in their terminal:
```bash
aliyun configure --mode OAuth --profile oauth
```
This is an interactive command that will:
1. Open a browser with an authorization link — user clicks to authorize
2. Prompt for region (e.g.cn-hangzhou,cn-beijing) — user enters their preferred region
3. Prompt for language (e.g. zh) — user enters their preferred language>
After OAuth setup completes, verify with: aliyun sts get-caller-identity --profile oauth>
⛔ SA-2.12 — DO NOT explicitly handle AK/SK: This skill MUST rely on the aliyun CLI/SDK default credential chain (OAuth / ECS RAM Role / env vars / pre-existing~/.aliyun/config.json). The Agent NEVER asks the user to paste AccessKey/Secret/STS-Token values into the chat, NEVER puts raw AK/SK in tool-call arguments or scripts, and NEVER echoes credential values. When credentials are missing, instruct the user to configure them out-of-band (their own terminal/shell profile/RAM role) and only re-verify viaaliyun sts get-caller-identity. Full remediation flow → references/init-and-credentials.md.
>
CRITICAL PROHIBITION: NEVER run standaloneappmanageroraliyun appmanager login.
---
Task 3: Initialize Project
Step 1 (MANDATORY): Read README.md FIRST
CRITICAL ORDERING RULE: Before scanning any project files, the Agent MUST readREADME.md(orREADME) in the project root. This is ALWAYS the first action in Task 3.
What to extract from README:
- Quick-start / deploy commands (e.g.
pip install -r requirements.txt && python main.py,npm install && npm start) - Official build/run commands, Docker deploy methods, port number, required environment variables
MANDATORY: Present README Methods to User and Follow Decision Tree
Step A: List what README provides to the user.
Step B: Select method by priority:
| Priority | Method Type | Action |
|---|---|---|
| 1 (HIGHEST) | Native CLI / package manager install (npm install -g, pip install, go install) | Use directly |
| 2 | Native build + run (pip install && python main.py, npm install && npm start) | Use, install runtime |
| 3 | Script-based deploy (bash deploy.sh) | Must confirm non-interactive |
| 4 (LOWEST) | Docker / docker-compose | Only when no higher priority exists; check China accessibility |
Step C: Execute based on scenario:
- README has native method (priority 1/2) → Use it directly as start script core. NEVER ignore README and build from scratch.
- README only has Docker → Check image accessibility (see references/script-templates.md "Docker Image Accessibility Check"). Warn user about China mirror risks.
- README has no deploy info / absent → Agent scans project files independently (only allowed case).
Why README first? Most projects document the exact build/run commands. Auto-detecting from files alone is error-prone.
---
Step 2: Determine project type
| Condition | Type |
|---|---|
Project depends on agentscope | agent |
| Everything else (langchain, mcp, autogen, web services, tools, etc.) | app |
Determine --name
Use the project directory name (lowercased, hyphens). Inform user: Default app name uses the directory name <name>.
Determine --region and ECS target (MUST ask user)
Agent MUST ask both questions together in ONE message:
1. Which region do you want to deploy to?
- Shanghai (cn-shanghai) / Hangzhou (cn-hangzhou) / Beijing (cn-beijing) / Shenzhen (cn-shenzhen) / Guangzhou (cn-guangzhou) / Chengdu (cn-chengdu) / Nanjing (cn-nanjing) / Hong Kong (cn-hongkong)
>
2. New ECS or existing ECS?
- New ECS (auto-create instance, pay-as-you-go)
- Existing ECS (please provide the instance ID, e.g. i-bp1xxxxxxxx)NEVER use zone-based labels like "East China 1" / "North China 2". NEVER add descriptions. City names only.
⚠️ REGION PROPAGATION CHECK (MANDATORY): The chosen region MUST be passed verbatim toappmanager init --region, written intoconfig.yamlcommon.deployment.regionId, AND attached as--region <REGION_ID>to every subsequentdeploy_toolkit.py {price,deploy,verify}invocation. Mismatch / omission triggersInvalidParameter: DeployRegionId is invalidfrom the OOS API.
Determine --port (App type only, OPTIONAL)
Only specify when the project actually listens on HTTP. Skip for background services (bots, workers, CLI tools). If needed but unknown, default to 8080. Agent type does NOT use --port.
Non-interactive init
See references/init-and-credentials.md for all init flag combinations.
Creates .appmanager/config.yaml. Does NOT support --overwrite — delete .appmanager/ first if exists.
---
Task 4: Generate Deploy Scripts
For ALL project types, the Agent MUST generate deployment scripts and write them into .appmanager/config.yaml.
Workflow
1. Read README.md FIRST — follow Task 3 decision tree 2. If README has no deploy info — scan project structure (Language Detection below) 3. Docker accessibility check — if Docker path selected (see references/script-templates.md) 4. Generate start & stop scripts — following rules below. Start script MUST ALWAYS include zip extraction sequence. 5. Write to config.yaml — under common.scripts.start and common.scripts.stop (NEVER top-level scripts)
Language Detection Rules
| Indicator Files | Language |
|---|---|
package.json / *.js / *.ts | Node.js |
requirements.txt / pyproject.toml / *.py | Python |
pom.xml / build.gradle / *.java | Java |
go.mod / *.go | Go |
composer.json / *.php | PHP |
docker-compose.yml / Dockerfile | Docker |
Files to Read (MUST read content, not just detect presence)
| Language | Must Read | Why |
|---|---|---|
| Python | pyproject.toml, requirements.txt | Entry point, deps |
| Node.js | package.json | scripts.start, main field |
| Java | pom.xml or build.gradle | JAR name |
| Go | go.mod | Module → binary name |
| PHP | composer.json | Framework detection |
| Docker | docker-compose.yml / Dockerfile | Services, ports |
Entry Point Detection Order
- Python:
[project.scripts]in pyproject.toml →main.py→app.py→manage.py - Node.js:
scripts.start→mainfield →index.js→server.js - Java:
find ... -name "*.jar" | head -1→java -jar - Go: Pre-compiled binary:
find ... -type f -perm /111 - PHP:
composer install --no-dev→php artisan serveorphp -S - Docker Compose:
docker compose up -d/docker compose down
General Script Rules
| Rule | Requirement |
|---|---|
| ⛔ MANDATORY zip extract | Start script MUST: find zip → mkdir -p → unzip -o → cd. Without this, project dir DOES NOT EXIST on ECS |
| Runtime install | MUST install language runtime FIRST (ECS is bare) |
| Install unzip | `command -v unzip &>/dev/null \ |
| Idempotent | Safe to run multiple times |
| ⛔ Log file FIXED path | MUST be /root/app.log and /root/app.pid. verify script hardcodes these paths |
| Log append | Always >> (never >) |
| PID file | echo $! > /root/app.pid after nohup ... & |
| Background run | nohup ... >> /root/app.log 2>&1 & |
| Stop old process | `[ -f /root/app.pid ] && kill "$(cat /root/app.pid)" 2>/dev/null \ |
| App dir | /root/{app_name} |
| No heredoc | NEVER use << 'EOF' inside scripts — breaks YAML. Use printf or python3 -c |
| MANDATORY tail log | End with sleep 3 && cat /root/app.log for verification capture |
| ⛔ Stop script: NO exit | MUST NOT contain exit. Deploy system concatenates stop+start — exit kills the entire process |
ECS instances are bare Linux (typically Alibaba Cloud Linux, RHEL-based, usesyum/dnf).
For script templates, language install commands, and config.yaml writing method, see references/script-templates.md.
---
Task 4.5: Pre-deploy Price Check + Risk Warning
MANDATORY: Before deploying, rundeploy_toolkit.py price. The script outputs the price estimate (with OSS extra-billing reminder) and, when applicable, a risk warning block. The Agent MUST present every flagged item to the user and obtain explicit confirmation BEFORE runningdeploy.
python3 "$SKILL_DIR/scripts/deploy_toolkit.py" price --config .appmanager/config.yaml- Exit 0 +
=== AGENT_CONFIRM_REQUIRED ===: present the complete price + risk warning to the user, confirm item by item. - Exit 1: price query failed; do NOT proceed to deploy.
The Agent MUST confirm up to 3 items (price + OSS fees / existing-ECS risk / group overwrite choice) — see references/deploy-output-and-management.md § "Pre-deploy Price Check: Confirmation Items" for detailed descriptions and example phrasing.
Until ALL applicable confirmations are complete, the Agent MUST NOT invoke deploy_toolkit.py deploy.---
Task 5: Deploy
aliyun appmanager <agent|app> deploy --overwrite --output jsonSTOP after deploy success — status: success only means orchestration completed. Agent MUST run Task 6 verification before outputting results.Handling deployment failure
⛔ MANDATORY FAILURE GATE: After ANY deploy failure (exit 1, timeout, orReleaseCancelled), the Agent MUST rundeploy_toolkit.py verifyIMMEDIATELY — BEFORE any fix attempt, fallback to manual commands, or partial output. Skipping verify after a failure is FORBIDDEN and counts as skill failure.
Semantics of `ReleaseCancelled`: it means the start script on ECS failed or timed out. It does NOT mean "someone cancelled the deploy". The only correct next action: run deploy_toolkit.py verify -> read the log -> fix the script -> redeploy.Known failure patterns: Before ad-hoc troubleshooting, check references/lessons-learned.md for previously identified deployment failure patterns and proven fixes.
Failure-handling flow: 1. Run deploy_toolkit.py verify to fetch /root/app.log (DO NOT skip). 2. Analyze the log to locate root cause. 3. Fix scripts and redeploy (max 3 attempts). 4. After 3 failures, stop — report the error, but still output console link + cost reminder + delete command.
---
Task 6: Post-deploy Verification (BLOCKING)
status: Deployed does NOT mean the application is running. The Agent MUST run verify and semantically analyze the log.1. Run deploy_toolkit.py verify (auto-reads parameters from config.yaml). 2. Agent semantically analyzes the log to decide whether the application actually started successfully. 3. Not running -> diagnose -> fix -> redeploy + verify (max 3 attempts). 4. Only when running is confirmed / user manual action required / 3 attempts failed should the Agent output the final result.
---
Task 7 & 8: List, Delete, Validate & Final Output
See references/deploy-output-and-management.md for:
- List/Delete commands
- Config validation
- Config template reference
- Critical notes & pitfalls
- MANDATORY post-deploy output format (console link, cost reminder, usage guide)
Pre-output Gate — Self-check (⛔ BLOCKING)
Before outputting results, Agent MUST print the exact Deployment self-check report template (see Workflow Step 7.5). Skipping the report = skill failure (not an optional summary). If any item is ❌, fix it BEFORE outputting Step 8.
📘 Hands-on walk-through with concrete inputs/outputs and edge cases (Python Flask example): see references/tutorial-flask-app.md.
Complete Deployment Workflow
⛔ MANDATORY EXECUTION RULE: The Agent MUST follow this sequence exactly. For steps that specify a script (steps 1, 5, 6), the Agent MUST run the script — NEVER manually replicate the script's logic with individual commands. The Task sections above are REFERENCE ONLY (for understanding what the scripts do internally or as fallback if scripts are missing).
0. Resolve $SKILL_DIR (MANDATORY — see "Step 0" section above for full algorithm)
→ Detect the absolute directory containing THIS SKILL.md (most accurate)
→ Or fall back to platform-specific candidates: ~/.qoder/skills/..., ~/.claude/skills/..., ~/.qwen/skills/..., $SKILLS_HOME/..., etc.
→ Pattern A (persistent shell): export SKILL_DIR=<abs_path> ; verify $SKILL_DIR/scripts/deploy_toolkit.py exists ; reuse $SKILL_DIR everywhere
→ Pattern B (fresh shell per command): inline the absolute path — python3 "/abs/path/scripts/deploy_toolkit.py" ...
→ ⛔ NEVER use SKILL_DIR=/path python3 "$SKILL_DIR/..." — outer shell expands $SKILL_DIR
BEFORE the prefix assignment, producing /scripts/deploy_toolkit.py and ENOENT.
1. Environment check (MUST use deploy_toolkit.py check — DO NOT run manual commands)
python3 "$SKILL_DIR/scripts/deploy_toolkit.py" check
⛔ FORBIDDEN: running aliyun version, ~/.aliyun/appmanager-venv/bin/python -c "...",
credential checks, or ANY manual version-check commands before or instead of this script.
The script checks ALL of: CLI version + appmanager-cli version + credentials in one run.
Just run the script. Period.
→ If exit 0: all checks passed, proceed to step 2
→ If exit 1, address the issue printed by the script:
⚠️ DO NOT stop silently. For every fixable ❌ line the script prints,
Agent MUST follow the flow below:
- aliyun CLI NOT installed: AUTO-INSTALL directly (no need to ask user)
- aliyun CLI already installed but outdated: ASK user to approve upgrade
(covers to /usr/local/bin, needs sudo), then run the install command
printed by the script (see Task 1).
- appmanager-cli < 1.1.1 or BROKEN venv: ASK user to approve
rm -rf ~/.aliyun/appmanager-venv (auto-recreates on next aliyun
appmanager run).
⚠️ This path is fixed at ~/.aliyun/appmanager-venv (the venv is self-managed
by the aliyun CLI). After deletion, the next aliyun appmanager run
auto-recreates it. The Agent MUST use this exact literal path —
NEVER replace it with a variable or build it via concatenation,
to avoid accidentally wiping user data.
- credentials missing/invalid: present OAuth-first remediation
to the user (OAuth / RAM Role / env vars / aliyun configure interactive) — NEVER
collect AK/SK in chat. See Task 2 + references/init-and-credentials.md.
→ If user refuses any fix: stop with that refusal as the reason — DO NOT
continue with a broken environment (deployment will fail anyway).
→ If script file not found: ONLY THEN fall back to manual checks (Task 1 + Task 2)
2. Obtain project source (if needed)
→ If git URL provided: clone to CURRENT WORKING DIRECTORY, cd into cloned dir
git clone <URL> && cd <cloned_dir>
→ If local path / current directory: skip this step, use directly
🔀 REPEAT DEPLOYMENT SHORTCUT — check BEFORE step 3
→ Check if .appmanager/config.yaml already exists in the project directory
→ If YES (config.yaml exists):
Read the file and check for common.deployment.instanceId:
- instanceId ABSENT (new ECS): skip steps 3-5, jump to step 5.5 (price check)
- instanceId PRESENT (existing ECS): skip steps 3-5.5, jump to step 6 (deploy)
In both cases, inform user: "Existing .appmanager/config.yaml detected; will reuse the existing config and deploy directly."
→ If NO (config.yaml does NOT exist): proceed normally from step 3
3. Read project + identify type (agent or app)
→ READ README.md FIRST — highest priority source for deployment method:
- Agent MUST list README's methods to user and select by priority:
Native CLI install > Native build+run > Script deploy > Docker
- ❌ NEVER ignore README methods and scan project files instead
- ❌ NEVER prefer Docker when native methods are available
- Docker: ONLY when no native method exists, MUST warn user about China mirror risks
- Only if README absent/empty/no deploy info → Agent scans project files independently
→ Only classify as "agent" if project depends on agentscope; everything else is "app"
→ Determine --name from directory name, --port from project config/README
→ For Docker: check image accessibility from China (see references/script-templates.md)
4. Ask user for deployment region + ECS target (MANDATORY — ask together in one question)
→ Question 1: "Which region do you want to deploy to? Shanghai(cn-shanghai)/Hangzhou(cn-hangzhou)/Beijing(cn-beijing)/Shenzhen(cn-shenzhen)/Guangzhou(cn-guangzhou)..."
→ Question 2: "New ECS or existing ECS?" — for existing, the user must provide the instance ID, e.g. i-bp1xxxxxxxx
→ NEVER use zone-based labels like "East China 1" / "North China 2" — always use city names
→ NEVER skip the ECS choice and default to creating new
→ ⚠️ Region MUST be propagated verbatim to: appmanager init --region, config.yaml common.deployment.regionId, AND every deploy_toolkit.py --region. Mismatch → InvalidParameter: DeployRegionId from OOS API.
5. Init + generate scripts (appmanager init → write start/stop to config.yaml)
→ If .appmanager/ already exists in the CURRENT project directory, ask user before removing.
⚠️ DESTRUCTIVE: rm -rf .appmanager deletes the existing deployment config.
Required guard before deletion:
a. Confirm CWD matches the intended project directory (pwd shows expected path)
b. Confirm target is the relative path .appmanager (NEVER absolute, NEVER with variables)
c. Inform the user "About to delete the existing deployment config under ./.appmanager/. This is irreversible." and obtain consent
Recommended safer alternative: back up first
mv .appmanager .appmanager.bak.$(date +%Y%m%d%H%M%S)
Only after explicit user consent: rm -rf ./.appmanager
→ Run: aliyun appmanager init --non-interactive --name <DIR_NAME> --type <app|agent> --region <REGION> [--port <PORT>] [--ecs existing --instance-id <ID>] [--model qwen3.6-plus --api-key "$API_KEY"]
(See references/init-and-credentials.md for full flag combinations by type)
→ Then generate start/stop scripts and write to config.yaml:
- MUST write to common.scripts.start and common.scripts.stop (NEVER top-level scripts key)
- Use python3 yaml library: config['common']['scripts'] = {'start': ..., 'stop': ...}
- PRIORITY: README deployment commands → use directly; only auto-generate when README has none
- ⛔ MANDATORY: Start script MUST ALWAYS include zip extraction (mkdir + unzip + cd) BEFORE
any build/run commands. appmanager uploads zip but does NOT extract it.
5.5. Pre-deploy price check + risk warning (MUST run deploy_toolkit.py price — Agent handles user confirmation)
python3 "$SKILL_DIR/scripts/deploy_toolkit.py" price --config .appmanager/config.yaml
→ Script output structure:
[Price table] estimate from appmanager price (order-billed resources: ECS/EIP/bandwidth) + the trailing 📦 OSS extra-billing reminder
[Risk warning] only when detected: [Existing-ECS deployment risk] / [Group overwrite risk] / [Failure-leftover group]
→ Script does NOT ask user for confirmation — that's the Agent's job
→ If exit 0: Agent MUST read the output, present the COMPLETE breakdown to user — including:
1) Price estimate + OSS extra-billing reminder (OSS storage ~CNY 0.12/GB/month, public outbound ~CNY 0.50/GB only when cross-region, requests billed per 10k)
2) If output contains [Existing-ECS deployment risk] -> ask whether to deploy onto that existing ECS (may impact other apps on it)
3) If output contains [Group overwrite risk] -> ask user to choose A (overwrite) or B (new group)
Example: "Estimated cost: compute resources CNY X.XXX/hour (~CNY XXX.XX/month); public traffic billed by usage at CNY 0.80/GB;
the deployment also incurs minor OSS storage and request fees (intra-region pull is free of public outbound charges).
Confirm to continue?"
→ After ALL items confirmed by user: run the matching deploy command per item 3's choice (default overwrite / --force-new-group for new group)
→ If ANY item refused: STOP deployment
→ If exit 1: price query failed, show error to user, do NOT proceed
6. Deploy (MUST use deploy_toolkit.py deploy — DO NOT run deploy manually)
python3 "$SKILL_DIR/scripts/deploy_toolkit.py" deploy \ --type <agent|app> --name <APP_NAME> --group <GROUP_NAME> --region <REGION_ID>
⛔ FORBIDDEN: running aliyun appmanager deploy directly without this script
→ Handles: group status check → conflict auto-resolve → deploy
→ Exit 0: deploy submitted, proceed to step 7
→ Exit 1: ⛔ MUST run step 7 (verify) IMMEDIATELY to fetch /root/app.log;
skipping to step 8, outputting partial results, or running manual
commands instead is FORBIDDEN. Then fix script per log and redeploy
(max 3 attempts).
7. Verify (MUST use deploy_toolkit.py verify — DO NOT check status manually)
python3 "$SKILL_DIR/scripts/deploy_toolkit.py" verify \ --type <agent|app> --name <APP_NAME> --group <GROUP_NAME> --region <REGION_ID>
⛔ FORBIDDEN: running aliyun appmanager status + manual log analysis instead of this script
→ Optional: --wait <seconds> for slow-starting apps (default 3s, Java/heavy use 15-30)
→ Dual-path: Cloud Assistant cat /root/app.log (preferred) → deployCommandOutput (fallback)
→ Exit 0: app running, proceed to step 8
→ Exit 1: app failed — fix start script, re-deploy (back to step 6)
→ Exit 2: inconclusive — retry with longer --wait or suggest SSH check
7.5. Self-check summary (⛔ BLOCKING — skill fails if omitted)
MUST print the exact template below to the user — this is a completion criterion, NOT optional.
#
---
✅ Deployment self-check report:
0. Path resolution — SKILL_DIR=___ (script exists ✅)
1. Environment pre-check — CLI v___ / appmanager-cli v___ / credentials valid ✅
2. Project obtained — (local / cloned) ✅
3. Project identified — type: ___ / deploy method source: README.md ✅
4. Deployment region — user choice: ___ ✅
5. Init + scripts — config.yaml generated; start script: ___ (key command summary) ✅
5.5. Pre-deploy price check — user confirmed price (CNY ___/hour, ~CNY ___/month) ✅
6. Deploy executed — deploy_toolkit.py deploy exit 0 ✅
7. Run verification — deploy_toolkit.py verify exit 0 / log keywords: ___ ✅
---
#
If any item is ❌, fix it BEFORE step 8 — this is for the USER to see, proving the work is properly done.
8. Output results (MANDATORY: console link + cost reminder + management commands)
→ See references/deploy-output-and-management.md for full output format
Deploy Output & Management Reference
Common Deploy Options
| Flag | Description |
|---|---|
--config PATH | Custom config file (default: .appmanager/config.yaml) |
--overwrite | Force overwrite existing files in OSS |
--dry-run | Validate only, do not execute deployment |
--output json | Output NDJSON stream (Agent-friendly) |
--name TEXT | Override app name |
--group_name TEXT | Override group name |
--region TEXT | Override deployment region |
--revision_id TEXT | Redeploy using existing artifact |
Deploy output format
--overwrite --output json is the standard deploy invocation. Always use both flags.
Output format (NDJSON, one JSON per line):
{"type":"step", "step":1, "total":9, "message":"Validating config..."}
{"type":"step", "step":2, "total":9, "message":"Uploading to OSS..."}
{"type":"result", "status":"success", "data":{"revision_id":"rev-xxx", ...}}---
MANDATORY: Post-deploy Output
When the self-check passes (all items OK), output the following to the user:
1. Deployment summary table
Includes app name, deployment region, group name, deployment status, Revision ID, and ECS instance ID.
2. Console link
Read the console_url field from the deploy result; if missing, build the URL with the formats below:
- On success:
https://computenest.console.aliyun.com/app/detail?tabKey=overview&appName=<APP_NAME>&groupName=<GROUP_NAME> - On failure / pending confirmation (ReleaseWaiting, script execution failure, etc.):
https://computenest.console.aliyun.com/app/detail?tabKey=flow&appName=<APP_NAME>&groupName=<GROUP_NAME>(jumps to the execution-flow page)
3. Resource cost reminder (MUST include the delete command)
Resource cost reminder: this deployment uses ECS instances and OSS storage (pay-as-you-go). Delete the resources when you no longer need them to avoid recurring charges:
```bash
aliyun appmanager <agent|app> delete --name <APP_NAME> --group_name <GROUP_NAME>
```
4. Status query command
```bash
aliyun appmanager <agent|app> status --name <APP_NAME> --group_name <GROUP_NAME>
```
5. Usage guidance
The Agent MUST tailor the usage guidance to the project type and the deploy log:
| Project usage type | Detection signal | Usage guidance |
|---|---|---|
| Web service (HTTP listener) | Deploy log shows "Listening on port X"; project uses flask / fastapi / express / spring / django | Provide access URL: http://<ECS_PUBLIC_IP>:<PORT> (extract ECS public IP from status output) |
| API service | Project defines REST / GraphQL endpoints | Provide API base URL + sample curl command |
| CLI tool / library | Project is a command-line tool, SDK, or library (e.g. agentscope) | Provide SSH login command + a verification command |
| Background service / worker | Project is a queue consumer, scheduled job, or daemon | Inform the user the service is running in background; provide log-tail command |
| Static site / frontend | Project contains HTML/CSS/JS served by nginx / serve | Provide access URL: http://<ECS_PUBLIC_IP>:<PORT> |
Get the ECS public IP: extract public_ip or instance_ip from aliyun appmanager <agent|app> status --output json output.
WARNING: Omitting the console link or cost reminder is FORBIDDEN.
---
List & Delete
List applications
aliyun appmanager agent list
aliyun appmanager agent list --name my-agent # list groups under app
aliyun appmanager app listDelete
# Delete a group first
aliyun appmanager agent delete --name my-agent --group_name default-cn-beijing
# Then delete the application
aliyun appmanager agent delete --name my-agentIn --output json mode, confirmation is skipped automatically.---
Validate Config
aliyun appmanager config validate
aliyun appmanager config validate --config path/to/config.yaml --output json---
Config Template Reference
Generated by aliyun appmanager init --print-template. Below is a unified template (use type: agent or type: app):
metadata:
name: my-app # Required: app/agent name
type: app # "app" or "agent"
groupName: default-cn-beijing # NEVER use bare "default" — always include region suffix
regionId: cn-beijing # Required: deployment region
common:
deployment:
# Option 1: New ECS (auto-created)
ecsInstanceType: ecs.u1-c1m2.large
systemDiskSize: 40
internetMaxBandwidthOut: 5
# Option 2: Existing ECS (uncomment below, remove Option 1)
# instanceId: i-bp1xxxxxxxx
scripts: # REQUIRED: Agent-generated scripts (MUST be under common.scripts)
start: |
#!/bin/bash
# Agent generates start script based on project analysis (see SKILL.md Task 4)
stop: |
#!/bin/bash
# Agent generates stop script (MUST NOT contain 'exit' statement)
# Agent-specific config (ONLY for type: agent, remove for type: app)
agent:
model:
name: qwen3.6-plus
apiKey: "sk-xxx" # REQUIRED for agent type — deployment fails without this---
Critical Notes & Pitfalls
1. NEVER use standalone `appmanager` or `aliyun appmanager login`: Only aliyun appmanager <cmd> is valid. SA-2.12 — credentials must come from the aliyun CLI/SDK default credential chain (ECS RAM Role / env vars / pre-existing ~/.aliyun/config.json set up out-of-band by the user); the Agent MUST NOT collect AK/SK in chat or pass them via --access-key-* flags.
2. Agent type REQUIRES `apiKey`: Deploying type agent without agent.model.apiKey in config.yaml will fail.
3. Both types generate deploy scripts locally: Agent generates scripts by scanning project → writes to common.scripts in config.yaml. No API Key needed for script generation.
4. First run auto-installs: First aliyun appmanager auto-creates venv at ~/.aliyun/appmanager-venv/ — Agent should NEVER interact with this venv directly.
5. ECS zone compatibility: Not all instance types available in every zone. If zone-related errors occur, try a different region or instance type.
6. OSS Bucket name conflict: Bucket named <app_name>-<region> is globally unique. If AccessDenied at upload_to_oss → change --name to a more unique value and re-run init + deploy.
7. `groupName` MUST include region suffix: NEVER use bare default. Always default-<regionId> (e.g., default-cn-hangzhou).
8. Pre-deploy group check: Handled automatically by deploy_toolkit.py deploy.
9. Insufficient balance (`NotEnoughBalance`): account balance < CNY 100 cannot create pay-as-you-go ECS. Tell the user to top up at https://usercenter2.aliyun.com/finance/fund-management, or switch to deploying onto an existing ECS instance.
---
Pre-deploy Price Check: Confirmation Items
The Agent MUST confirm each applicable item with the user one by one before invoking deploy_toolkit.py deploy.
1. Price confirmation (including OSS extra fees — ALWAYS required)
The price output has two parts:
- The estimate from
appmanager pricefor "order-billed" resources (ECS / EIP / public bandwidth, etc.) in hourly/monthly form. - A
OSS extra billingnotice — these items are NOT covered byappmanager pricebut always occur during deployment: - OSS standard storage ~CNY 0.12 / GB / month (project archives are usually KB-MB scale, so the amount is tiny but non-zero)
- OSS public-network outbound traffic ~CNY 0.50 / GB (when ECS and OSS are in the same region, intra-region pull is free of public traffic charges; only cross-region transfer incurs the fee — therefore the deployment region SHOULD match the default OSS bucket region)
- OSS Put/Get requests are billed per 10k requests (negligible amount)
The Agent MUST relay both parts. Example phrasing: "Estimated cost: compute resources CNY X.XXX/hour (~CNY XXX.XX/month); public traffic billed by usage at CNY 0.80/GB; the deployment also incurs minor OSS storage and request fees (intra-region pull is free of public outbound charges). Confirm to continue?"
2. Existing-ECS deployment impact (only when script outputs [Existing-ECS deployment risk])
When config.yaml contains common.deployment.instanceId, the script lists the risk items. The Agent MUST ask: "About to deploy to the existing ECS instance i-xxx. The deployment runs stop -> upload -> start scripts and may stop or overwrite other applications already running on this instance. Confirm to continue?"
- User refuses -> STOP and recommend switching to "new ECS"
- User agrees -> proceed to item 3 (if applicable) or directly to deploy
3. Group overwrite vs new group (only when script outputs [Group overwrite risk])
When the target groupName already exists and is associated with active ECS, the script asks for an A/B choice:
- A) Overwrite the existing group:
python3 "$SKILL_DIR/scripts/deploy_toolkit.py" deploy(default; uses--overwriteto replace code / restart processes) - B) Create a new group:
python3 "$SKILL_DIR/scripts/deploy_toolkit.py" deploy --force-new-group(the script auto-appends a suffix to allocate a new group name and writes it back to config.yaml; the existing deployment is unaffected)
The Agent MUST clearly explain the impact of A vs B; do NOT default to A on the user's behalf.
Until ALL applicable confirmations are complete, the Agent MUST NOT invoke deploy_toolkit.py deploy.Init & Credentials Reference
AI-Mode Configuration (MANDATORY after CLI install)
⛔ MUST configure AI-Mode: Agent MUST ensure AI-Mode is properly configured before running anyaliyun appmanagercommands. All subsequentaliyunCLI calls automatically carry the configured User-Agent header — no per-command--user-agentflag needed.
# 1. Enable AI-Mode (MUST — enables User-Agent tracking in all API calls)
aliyun configure ai-mode enable
# 2. Set User-Agent for skill traceability (MUST — identifies this skill in API logs)
aliyun configure ai-mode set-user-agent --user-agent "AlibabaCloud-Agent-Skills/alibabacloud-ecs-code-deploy"
# 3. Update plugins to latest (ensures appmanager subcommand is available)
aliyun plugin update
# 4. Verify AI-Mode status
aliyun configure ai-mode show
# Expected: enabled=true, user-agent=AlibabaCloud-Agent-Skills/alibabacloud-ecs-code-deployDisable AI-Mode (when troubleshooting or if explicitly required):
# Disable AI-Mode (stops sending User-Agent header; re-enable with 'enable' above)
aliyun configure ai-mode disabledeploy_toolkit.py check already handles AI-Mode enable + set-user-agent internally. The above is only needed for manual fallback scenarios.---
Fallback: Manual CLI Verification & Install (only when deploy_toolkit.py unavailable)
Version requirements: aliyun CLI >= 3.3.19, appmanager-cli >= 1.1.1
⚠️ Privilege requirement: The install commands below extract to/usr/local/bin/, which requires elevated privileges (sudoon Linux/macOS for non-root users). If running as a non-root user, prependsudoto thetarstep. Alternatively, extract to a user-writable directory in$PATH(e.g.,~/.local/bin).
⚠️ Supply chain note: The downloads come from Alibaba Cloud's official OSS bucket over HTTPS. For higher assurance, verify the binary's SHA256 checksum against the version listed at https://help.aliyun.com/document_detail/121541.html before adding to $PATH.⚠️ PATH conflict pitfall (MUST READ): On macOS Apple Silicon,/opt/homebrew/binis ahead of/usr/local/binby default. If brew already installedaliyun-cli, extracting a fresh build into/usr/local/bin/will be shadowed by the brew-installed older version. Symptom: "the upgrade looks successful right after install, but the next shell session reverts to the old version -> repeated upgrades". Before AND after any install/upgrade, runwhich -a aliyunto list all matching binaries on PATH and confirm the one resolved byaliyun versionis the new one.
# 0. List all aliyun binaries on PATH (the first one wins). Detect any conflict.
which -a aliyun
aliyun version 2>&1 # the version actually in effect right now
# 1. Check aliyun CLI version
aliyun version 2>&1
# → Not found or < 3.3.19: install below. >= 3.3.19: skip to step 2.
# 2. Check appmanager-cli version (only if ~/.aliyun/appmanager-venv exists)
~/.aliyun/appmanager-venv/bin/python -c "from importlib.metadata import version; print(version('appmanager-cli'))" 2>/dev/null
# → < 1.1.1 or fails: rm -rf ~/.aliyun/appmanager-venv (auto-recreates on next run)
# 3. Install aliyun CLI — choose ONE path below by priority
# Priority A: macOS already manages aliyun-cli via Homebrew -> upgrade with brew
# (avoids being shadowed by PATH ordering)
brew list --formula | grep -qx aliyun-cli && brew upgrade aliyun-cli
# Priority B: system-directory install (recommended; writing to /usr/local/bin needs sudo)
# macOS Apple Silicon:
curl --connect-timeout 30 --max-time 120 -fsSL https://aliyun-cli.oss-cn-hangzhou.aliyuncs.com/aliyun-cli-macosx-latest-arm64.tgz | sudo tar xz -C /usr/local/bin/
# macOS Intel:
curl --connect-timeout 30 --max-time 120 -fsSL https://aliyun-cli.oss-cn-hangzhou.aliyuncs.com/aliyun-cli-macosx-latest-amd64.tgz | sudo tar xz -C /usr/local/bin/
# Linux amd64:
curl --connect-timeout 30 --max-time 120 -fsSL https://aliyun-cli.oss-cn-hangzhou.aliyuncs.com/aliyun-cli-linux-latest-amd64.tgz | sudo tar xz -C /usr/local/bin/
# Linux arm64:
curl --connect-timeout 30 --max-time 120 -fsSL https://aliyun-cli.oss-cn-hangzhou.aliyuncs.com/aliyun-cli-linux-latest-arm64.tgz | sudo tar xz -C /usr/local/bin/
# Priority C: no-sudo fallback (only when B is not viable) — install into ~/bin and persist PATH in shell rc
mkdir -p ~/bin
curl --connect-timeout 30 --max-time 120 -fsSL <platform-specific URL> | tar xz -C ~/bin/
# ⚠️ `export PATH` only affects the current shell session; it MUST also be appended to the shell rc
# file, otherwise the next session reverts to the old version:
grep -q 'HOME/bin' ~/.zshrc 2>/dev/null || echo 'export PATH="$HOME/bin:$PATH"' >> ~/.zshrc
# bash users edit ~/.bashrc instead. Then refresh the current session immediately:
hash -r # zsh users: rehash
export PATH="$HOME/bin:$PATH"
# 4. Mandatory post-install/upgrade re-verification (skipping this causes the "repeated upgrade" loop)
which -a aliyun # the first entry MUST be the dir you just installed into (/usr/local/bin or ~/bin)
aliyun version # MUST be >= 3.3.19
# If the first entry of `which -a` is still the old version (e.g. /opt/homebrew/bin/aliyun), the PATH conflict
# is unresolved:
# - if the old version is from brew, switch to Priority A: brew upgrade aliyun-cli
# - otherwise, manually `rm` the old binary, or fix PATH order in ~/.zshrc---
Configure Credentials
⛔ PREFER OAuth OVER AK: This skill SHOULD guide users to use OAuth authentication as the PRIMARY method for providing Alibaba Cloud permissions. OAuth is more secure and convenient than AccessKey (no long-term secret storage needed). The Agent MUST present OAuth as the first option before mentioning AK-based methods.
>
⛔ SA-2.12 — DO NOT explicitly handle AK/SK: This skill MUST rely on the default credential chain of the aliyun CLI/SDK. The Agent:
- MUST NOT ask the user to paste AccessKey ID / Secret / STS Token values into the chat
- MUST NOT put raw AK/SK/Token in tool-call arguments, command lines, scripts, or any persisted file (logs, ran_scripts, outputs)
- MUST NOT print or echo credential values, even partially, except for the masked profile diagnostic that deploy_toolkit.py check already produces- MUST instead instruct the user to configure credentials out-of-band (in their own terminal / shell profile / RAM role / secrets vault) and only verify by an identity-check call
>
The ONLY accepted Agent action is: detect whether some credential source is already in place, and if not, tell the user how to set one up themselves.
CRITICAL PROHIBITION: NEVER run standaloneappmanageroraliyun appmanager login. Credentials must come from the default credential chain below — never from interactive Agent prompts that collect AK/SK.
Default credential chain (aliyun CLI / SDK auto-resolves in this order)
The Agent only needs ONE of the sources below to be in place:
1. OAuth (RECOMMENDED — most secure and convenient) — user runs interactive OAuth setup in their own terminal:
aliyun configure --mode OAuth --profile oauthThis opens a browser authorization link, then prompts for region (e.g. cn-hangzhou) and language (e.g. zh). After setup, verify with:
aliyun sts get-caller-identity --profile oauth2. ECS RAM Role (recommended on Alibaba Cloud ECS) — instance metadata service auto-provides rotating STS credentials. The user configures it once with aliyun configure --mode EcsRamRole --ram-role-name <role> (<role> is an identifier, not a secret). No AK/SK ever leaves the instance. 3. Environment variables — ALIBABA_CLOUD_ACCESS_KEY_ID, ALIBABA_CLOUD_ACCESS_KEY_SECRET, optionally ALIBABA_CLOUD_SECURITY_TOKEN. Set by the user in their shell profile, secrets manager, or CI vault — outside the Agent session. The Agent MUST NOT read or echo these values. 4. Pre-existing profile in ~/.aliyun/config.json — created in advance by the user with interactive aliyun configure (NOT by the Agent passing flags). The skill reads only the profile name and a masked AK preview for diagnostics.
Verification (the ONLY Agent action — never reads raw credential values)
# Identity check — succeeds iff some credential source in the default chain is valid.
# Output reveals only Account / RoleArn / UserId, never AK/SK material.
aliyun sts get-caller-identity --output json >/dev/null 2>&1 \
&& echo "✅ credentials valid via default credential chain" \
|| echo "❌ no usable credentials — see remediation below"deploy_toolkit.py check already runs an equivalent check. If it exits 1 due to missing credentials, the Agent MUST stop and execute the remediation flow below — it MUST NOT prompt the user for AK/SK in the chat.
Remediation when credentials are missing
The Agent MUST present these self-service options to the user verbatim and wait for the user to confirm completion in their own terminal. Do not collect AK/SK in the chat under any circumstance.
No usable credentials were detected. Please configure them yourself in your own terminal using one of the methods below (do NOT paste the AccessKey into this chat or any file):
>
- Method A · OAuth (RECOMMENDED — most secure and convenient, no long-term secret storage):
aliyun configure --mode OAuth --profile oauth(This opens a browser authorization link, then prompts for region likecn-hangzhouand language likezh)
- Method B · ECS RAM Role (recommended on Alibaba Cloud ECS; no AK/SK):
aliyun configure --mode EcsRamRole --ram-role-name <your-role-name>- Method C · Environment variables (write into your~/.zshrc/~/.bashrc/ CI Secret; effective after re-login):
export ALIBABA_CLOUD_ACCESS_KEY_ID=... export ALIBABA_CLOUD_ACCESS_KEY_SECRET=... (For temporary credentials also set export ALIBABA_CLOUD_SECURITY_TOKEN=...)- Method D · Interactive `aliyun configure` (credentials only land in local ~/.aliyun/config.json): aliyun configure --profile <name> --mode AK (enter values at the terminal prompt, not in this chat)>
When done, reply "ready" and I will rerun aliyun sts get-caller-identity to verify. You will never need to paste any AK/SK value into this conversation.After the user confirms, the Agent re-runs the verification command above. If it still fails, ask the user to double-check the configuration — do not offer to "help" by accepting AK/SK in chat.
API Key for Agent type (separate from cloud control-plane credentials)
$ALIYUN_DASHSCOPE_API_KEY (matches sk-*) is required for the AgentScope runtime — it's a model-service key, not a cloud AK/SK, but the handling rule is identical:
- The Agent verifies presence with
[ -n "$ALIYUN_DASHSCOPE_API_KEY" ] && echo "set" || echo "missing"(never echoes the value). - If missing, instruct the user to obtain one at https://bailian.console.aliyun.com/cn-beijing?tab=model#/api-key and persist it in their own shell profile.
- The skill never asks the user to paste the key value into the chat.
Fixing credential errors
InvalidSecurityToken.Expired / InvalidAccessKeyId → instruct the user to refresh credentials via the same out-of-band methods (A / B / C). Re-verify with aliyun sts get-caller-identity. Never accept new AK/SK in the chat.
---
Non-interactive Init Examples
For App type (new ECS — default):
aliyun appmanager init --non-interactive \
--name my-app \
--type app \
--region cn-beijing \
--port 8080For App type (existing ECS — user provided instance ID):
aliyun appmanager init --non-interactive \
--name my-app \
--type app \
--ecs existing \
--instance-id i-bp1xxxxxxxx \
--region cn-beijing \
--port 8080For Agent type (new ECS):
aliyun appmanager init --non-interactive \
--name my-agent \
--type agent \
--region cn-beijing \
--model qwen3.6-plus \
--api-key sk-xxxxxxxxFor Agent type (existing ECS):
aliyun appmanager init --non-interactive \
--name my-agent \
--type agent \
--ecs existing \
--instance-id i-bp1xxxxxxxx \
--region cn-beijing \
--model qwen3.6-plus \
--api-key sk-xxxxxxxxNote:--portis optional for App type — omit it for background services that don't listen on HTTP. App type does NOT need--api-key. Agent type REQUIRES--api-keyfor the AI model runtime. Agent type does NOT use--port.--ecs existing --instance-idis only needed when user chooses to deploy to an existing ECS instance.
JSON mode (full config passthrough)
aliyun appmanager init --from-json '{
"metadata": {"name": "my-app", "type": "agent", "regionId": "cn-beijing"},
"agent": {"model": {"name": "qwen3.6-plus", "apiKey": "sk-xxx"}}
}' --output jsonOutput
Creates .appmanager/config.yaml in the current directory with deployment configuration.
WARNING:aliyun appmanager initdoes NOT support--overwriteflag. If config already exists, delete.appmanager/directory first or edit the YAML directly.
Lessons Learned — Deployment Failure Patterns & Fixes
This document is auto-populated by the batch deployment test (see tests/batch-deploy-100.md).When an Agent encounters a deployment issue, it SHOULD consult this file first for known
patterns and proven fixes before attempting ad-hoc troubleshooting.
How to Use This File
1. Before deploying: Skim the error signatures below. If the project matches a known trigger scenario, apply the fix proactively. 2. After a failure: Search this file for the error message or signature. If found, apply the documented fix and retry. 3. Contributing new lessons: When a new failure pattern is observed >= 2 times across different projects, add a new entry following the format below.
Entry Format
Each lesson follows this structure:
### <Error Signature>
- **Phase**: check / init / deploy / verify
- **Trigger Scenario**: <what type of project or condition triggers this>
- **Symptom**: <exact error message or observable behavior>
- **Root Cause**: <why it happens>
- **Fix**: <what the Agent should do — specific commands or decision changes>
- **Affected Projects**: <list of test project numbers/names that hit this>
- **First Observed**: <date or test round>---
Lessons
(The following entries are auto-appended by the Agent during batch deployment testing. Do not manually edit below this line unless correcting an inaccuracy.)
---
Java-Build-Use-Release-JAR
- Phase: deploy / verify
- Trigger Scenario: Spring Boot or any Java/Gradle/Maven project on 2C4G ECS where
appmanager initgenerated a default start script and the project requiresmvn package/gradle bootJarto produce a runnable JAR. - Symptom:
- Round 1:
Error: Unable to access jarfile *.jar(defaultjava -jar *.jarfinds no JAR in the cloned source tree). - Round 2 (if Agent retries with
gradle bootJar):ReleaseFailedorReleaseCancelledafter the 15-minute deploy budget elapses;gradle clean bootJartypically OOM's or runs >15 min on 2 vCPU + 4 GiB RAM. - Root Cause: 2C4G is too small to build large Java projects in the deploy window.
- Fix: Skip source build. Replace
common.scripts.startwith:
common:
scripts:
start: |
: > /root/app.log
mkdir -p /root && cd /root
if [ ! -f halo.jar ]; then
curl -fSL "https://github.com/halo-dev/halo/releases/download/v2.20.12/halo-2.20.12.jar" -o /root/halo.jar
fi
pkill -f 'halo.jar' || true
nohup java -Xmx384m -jar /root/halo.jar --server.port=8090 >> /root/app.log 2>&1 &Always set -Xmx ≤ 384 m (heap > 50 % of 4 GiB triggers OOM-killer when paired with the JVM's other memory regions).
- Affected Projects: #1 halo (validated Round 3 SUCCESS); also recommended for #81 spring-petclinic, #85 stirling-pdf.
- First Observed: Batch Round 1 (#1 halo Round 1).
---
RAM Policies Reference
Required RAM Permissions
The alibabacloud-ecs-code-deploy skill requires the following Alibaba Cloud RAM permissions for the configured AccessKey (AK/SK) or STS Token.
⚠️ Least-privilege principle: This skill's RAM permission strategy follows the
"minimum permissions necessary" rule. The recommended primary policy is the custom
least-privilege policy below. FullAccess system policies are listed only as aconvenience fallback for development/testing — production deployments MUST use the
custom policy.
Recommended (PRIMARY): Custom Least-Privilege Policy
This policy enumerates only the specific Actions the skill actually invokes (verified against deploy_toolkit.py and aliyun appmanager source). No wildcard * is used.
{
"Version": "1",
"Statement": [
{
"Sid": "ECSInstanceLifecycle",
"Effect": "Allow",
"Action": [
"ecs:CreateInstance",
"ecs:RunInstances",
"ecs:StartInstance",
"ecs:StopInstance",
"ecs:DeleteInstance",
"ecs:DescribeInstances",
"ecs:DescribeInstanceStatus",
"ecs:ModifyInstanceAttribute",
"ecs:AllocatePublicIpAddress",
"ecs:DescribeRegions",
"ecs:DescribeZones",
"ecs:DescribeAvailableResource"
],
"Resource": "*"
},
{
"Sid": "ECSCloudAssistant",
"Effect": "Allow",
"Action": [
"ecs:RunCommand",
"ecs:InvokeCommand",
"ecs:DescribeInvocations",
"ecs:DescribeInvocationResults",
"ecs:DescribeCloudAssistantStatus"
],
"Resource": "*"
},
{
"Sid": "ECSSecurityAndStorage",
"Effect": "Allow",
"Action": [
"ecs:CreateSecurityGroup",
"ecs:DescribeSecurityGroups",
"ecs:DescribeSecurityGroupAttribute",
"ecs:AuthorizeSecurityGroup",
"ecs:JoinSecurityGroup",
"ecs:CreateDisk",
"ecs:DescribeDisks",
"ecs:AttachDisk"
],
"Resource": "*"
},
{
"Sid": "OSSArtifactUpload",
"Effect": "Allow",
"Action": [
"oss:PutObject",
"oss:GetObject",
"oss:ListObjects",
"oss:ListBuckets",
"oss:CreateBucket",
"oss:GetBucketInfo",
"oss:GetBucketLocation"
],
"Resource": "*"
},
{
"Sid": "VPCNetwork",
"Effect": "Allow",
"Action": [
"vpc:CreateVpc",
"vpc:CreateVSwitch",
"vpc:DescribeVpcs",
"vpc:DescribeVSwitches",
"vpc:DescribeVpcAttribute"
],
"Resource": "*"
},
{
"Sid": "ComputeNestServiceInstance",
"Effect": "Allow",
"Action": [
"computenest:CreateServiceInstance",
"computenest:DeleteServiceInstance",
"computenest:GetServiceInstance",
"computenest:ListServiceInstances",
"computenest:UpdateServiceInstance",
"computenest:ContinueDeployServiceInstance",
"computenest:GetServiceTemplateParameterConstraints"
],
"Resource": "*"
}
]
}Note on omitted Actions:
-oss:DeleteObjectis not included — the skill only uploads deploy artifacts; cleanup is performed byaliyun appmanager <type> delete, which goes throughcomputenest:DeleteServiceInstancerather than direct OSS DELETE.
- No wildcard Action (e.g.ecs:*,oss:*,computenest:*) is used.
Fallback (DEV / TESTING ONLY): System FullAccess Policies
⛔ NOT RECOMMENDED FOR PRODUCTION: These policies grant broad permissions that
exceed what the skill actually needs and violate the least-privilege principle. Use
them ONLY for quick local prototyping, then switch to the custom policy above before
any non-throwaway use.
| Policy Name | Type | Purpose (subset actually used by this skill) |
|---|---|---|
AliyunECSFullAccess | System | ECS instance / SG / disk lifecycle + Cloud Assistant |
AliyunOSSFullAccess | System | Upload deployment artifacts |
AliyunVPCFullAccess | System | Create VPC / vSwitch for new ECS |
AliyunCloudAssistantFullAccess | System | Run shell commands on ECS via Cloud Assistant |
Permission Verification
The deploy_toolkit.py check script verifies credential validity by calling aliyun appmanager app status. If this call returns Forbidden or NoPermission, the user's RAM role/policy is insufficient.
Common permission errors and resolutions:
| Error Code | Cause | Fix |
|---|---|---|
Forbidden.RAM | Missing RAM policy | Attach the custom policy above (or required policies) |
NoPermission | Action not allowed | Verify the failing Action is enumerated in the custom policy |
InvalidAccessKeyId.NotFound | AK does not exist | Regenerate AK in RAM console |
SignatureDoesNotMatch | Secret key mismatch | Re-configure with correct SK |
Credential Types Supported
| Type | Config Method | Use Case |
|---|---|---|
| AK (long-term) | aliyun configure --mode AK (interactive) | Development/testing |
| STS Token (temporary) | aliyun configure --mode StsToken (interactive) | Production (recommended) |
| ECS RAM Role | aliyun configure --mode EcsRamRole --ram-role-name <role> | Running on ECS itself |
Script Templates & Language Reference
Start Script Template (Generic)
Replace{app_name}with the actual--namevalue used ininit. Replace{INSTALL_RUNTIME},{INSTALL_DEPS},{START_CMD}with language-specific commands from the Language Reference Table below.
#!/bin/bash
set -e
APP_DIR=/root/{app_name}
ZIP_FILE=$(ls /root/project_*.zip 2>/dev/null | tail -1)
LOG_FILE=/root/app.log
PID_FILE=/root/app.pid
# Stop existing process
[ -f "$PID_FILE" ] && kill "$(cat $PID_FILE)" 2>/dev/null || true
rm -f "$PID_FILE"
# Detect package manager
if command -v dnf &>/dev/null; then
PKG_MGR="dnf"
elif command -v yum &>/dev/null; then
PKG_MGR="yum"
elif command -v apt-get &>/dev/null; then
PKG_MGR="apt-get"
else
echo "ERROR: No supported package manager found" && exit 1
fi
# Install unzip if missing
if ! command -v unzip &>/dev/null; then
$PKG_MGR install -y unzip
fi
# {INSTALL_RUNTIME} — see Language Reference Table below
# Decompress (MANDATORY — appmanager uploads zip but does NOT extract)
mkdir -p "$APP_DIR"
[ -n "$ZIP_FILE" ] && unzip -o "$ZIP_FILE" -d "$APP_DIR"
cd "$APP_DIR"
# {INSTALL_DEPS} — see Language Reference Table below
# Start
nohup {START_CMD} >> "$LOG_FILE" 2>&1 &
echo $! > "$PID_FILE"
# MANDATORY: output log for verification
sleep 3 && cat /root/app.logLanguage Reference Table
⚠️ Supply chain security: Some rows below usecurl ... | bashorcurl ... | phppatterns to install runtimes. These are convenience patterns from upstream vendors (NodeSource, Composer, Go) — they execute remote code without local verification and are vulnerable to MITM/supply-chain attacks if the source is compromised. Mitigations applied below:
- NodeSource (Node.js): HTTPS-only, officialnodesource.comdomain. For high-security environments, prefer the distro package:dnf module install -y nodejs:22(RHEL 9) /apt-get install -y nodejs npm.
- Go: SHA256 checksum verification added before extraction. Reject if mismatch.
- Composer: SHA-384 installer signature verification added (per upstream guidance at https://getcomposer.org/download/). Reject and abort if signature mismatch.
- All `/usr/local` writes: Run as root inside ECS deploy context (start script executes as root via Cloud Assistant). Outside ECS, prepend sudo.| Language | Check | Install Runtime (RHEL/yum) | Install Runtime (Debian/apt) | Install Deps | Start Command |
|---|---|---|---|---|---|
| Python | command -v pip3 | $PKG_MGR install -y python3 python3-pip | apt-get update -qq && apt-get install -y -qq python3 python3-pip python3-venv | pip3 install -r requirements.txt -q or pip3 install -e . -q | python3 main.py |
| Node.js | command -v node | `curl --connect-timeout 30 --max-time 120 -fsSL https://rpm.nodesource.com/setup_22.x \ | bash - && $PKG_MGR install -y nodejs` (HTTPS official NodeSource; prefer distro package for stricter envs) | `curl --connect-timeout 30 --max-time 120 -fsSL https://deb.nodesource.com/setup_22.x \ | bash - && apt-get install -y -qq nodejs` |
| Java | command -v java | $PKG_MGR install -y java-17-openjdk | apt-get update -qq && apt-get install -y -qq default-jdk | N/A (pre-built JAR) | `java -jar $(find $APP_DIR -name "*.jar" \ |
| Go | command -v go | See Go install snippet below (with SHA256 verification) | (same) | go build -o app . (if source) or N/A (pre-compiled) | ./app or `$(find $APP_DIR -type f -perm /111 -not -name "*.sh" \ |
| PHP | command -v php | $PKG_MGR install -y php php-cli php-mbstring php-xml + see Composer install snippet below (with signature verification) | apt-get update -qq && apt-get install -y -qq php php-cli php-mbstring php-xml composer | composer install --no-dev --optimize-autoloader | php artisan serve --host=0.0.0.0 --port=8080 |
| Docker | (pre-installed on ECS) | N/A | N/A | N/A | docker compose up -d (no PID/nohup needed) |
Pattern: Wrap runtime install inif ! {Check} &>/dev/null; then ... fifor idempotency. For Go on China ECS, MUST usegolang.google.cnmirror and setGOPROXY=https://goproxy.cn,direct.
Go install snippet (with SHA256 verification)
GO_VERSION=1.22.0
GO_TGZ=go${GO_VERSION}.linux-amd64.tar.gz
# SHA256 from https://go.dev/dl/ (update when bumping GO_VERSION)
GO_SHA256=f6c8a87aa03b92c4b0bf3d558e28ea03006eb29db78917daec5cfb6ec1046265
curl --connect-timeout 30 --max-time 120 -fsSLO https://golang.google.cn/dl/${GO_TGZ}
echo "${GO_SHA256} ${GO_TGZ}" | sha256sum -c - || { echo "Go checksum mismatch — refusing to install" >&2; exit 1; }
tar -C /usr/local -xzf ${GO_TGZ} && rm -f ${GO_TGZ}
export PATH=$PATH:/usr/local/go/bin
export GOPROXY=https://goproxy.cn,directComposer install snippet (with signature verification)
Follows official guidance at <https://getcomposer.org/download/>:
EXPECTED_CHECKSUM=$(curl --connect-timeout 30 --max-time 60 -fsS https://composer.github.io/installer.sig)
curl --connect-timeout 30 --max-time 60 -fsSO https://getcomposer.org/installer
ACTUAL_CHECKSUM=$(php -r "echo hash_file('sha384', 'installer');")
if [ "$EXPECTED_CHECKSUM" != "$ACTUAL_CHECKSUM" ]; then
echo "Composer installer signature mismatch — aborting" >&2
rm -f installer
exit 1
fi
php installer --install-dir=/usr/local/bin --filename=composer
rm -f installerStop Script Template
CRITICAL: Stop script MUST NOT containexit 0or anyexitstatement. The deploy system concatenates stop+start into a single shell execution. If stop script hasexit, the start script will NEVER run and deployment will produce zero logs.
Safety notes:
- Graceful-then-force termination: The script first sendsSIGTERM(kill "$PID") and waits 3 seconds for the process to flush state and exit cleanly.kill -9(SIGKILL) is only used as a fallback when graceful termination fails. Do NOT remove the 3-second grace window — long-running processes may need time to flush data.
- Destructive cleanup guard:rm -rf "$APP_DIR"is dangerous if$APP_DIRis empty or set to a wrong path (e.g./). The template includes hard guards:[ -n "$APP_DIR" ],$APP_DIRlength check, and a strict prefix check (/root/<app_name>). Do NOT loosen these.
#!/bin/bash
PID_FILE=/root/app.pid
APP_DIR=/root/{app_name}
if [ -f "$PID_FILE" ]; then
PID=$(cat "$PID_FILE")
if kill -0 "$PID" 2>/dev/null; then
# Graceful shutdown first — give the process 3s to flush state
kill "$PID"
sleep 3
# Fallback: force-kill ONLY if still alive after grace period
kill -0 "$PID" 2>/dev/null && kill -9 "$PID"
fi
rm -f "$PID_FILE"
fi
# Clean up project directory for re-deploy.
# Hard guards prevent catastrophic deletion if APP_DIR is empty or misconfigured.
if [ -n "$APP_DIR" ] && [ "${#APP_DIR}" -gt 6 ] && [[ "$APP_DIR" == /root/* ]] && [ -d "$APP_DIR" ]; then
rm -rf "$APP_DIR"
fi
# DO NOT add "exit 0" here — it will kill the entire deployment processWriting Scripts to config.yaml
After generating scripts, the Agent MUST write them into .appmanager/config.yaml under common.scripts:
CRITICAL: The deploy system ONLY readscommon.scripts.startandcommon.scripts.stop.
A top-level scripts: key is IGNORED. If scripts are placed at the wrong level, deployment will use the auto-generated default scripts (which will fail).Recommended method — use Python yaml library (avoids YAML formatting issues):
import yaml
config_path = '.appmanager/config.yaml'
with open(config_path, 'r') as f:
config = yaml.safe_load(f)
config['common']['scripts'] = {
'start': '#!/bin/bash\nset -e\n...',
'stop': '#!/bin/bash\n...'
}
with open(config_path, 'w') as f:
yaml.dump(config, f, default_flow_style=False, allow_unicode=True)Resulting YAML structure (correct):
common:
deployment:
ecsInstanceType: ecs.u1-c1m2.large
...
scripts:
start: |
#!/bin/bash
set -e
APP_DIR=/root/my-app
...
stop: |
#!/bin/bash
PID_FILE=/root/app.pid
...WRONG structure (deploy system IGNORES this):
common:
deployment: ...
scripts: # ← WRONG! Top-level key, NOT read by deploy system
start: ...
stop: ...Docker Image Accessibility Check (MANDATORY for Docker projects)
When a project contains docker-compose.yml or Dockerfile, the Agent MUST check whether the required Docker images are accessible from China ECS with mirror acceleration before choosing the Docker deployment path.
Step 1: Identify required images
Scan Dockerfile for FROM directives and docker-compose.yml for image: fields. Extract all image references (e.g., node:24-bookworm, oven/bun:1.3.13, python:3.12-slim).
Step 2: Assess China accessibility
| Image Source | Accessible via China Mirrors? | Action |
|---|---|---|
Official Docker Hub images (library/* like node, python, nginx, redis, postgres) | YES — available on Aliyun/Tencent mirrors | Use Docker with mirror config |
Popular third-party images (mysql, mongo, elasticsearch) | LIKELY YES | Use Docker with mirror config |
Niche/uncommon images (oven/bun, custom registries, ghcr.io/*, quay.io/*) | NO — China mirrors don't mirror these | Fallback to native build |
Images pinned by SHA256 digest (image@sha256:abc...) | RISKY — mirrors may not resolve digests | Fallback to native build |
Step 3: Decision
- If ALL images are accessible → Use Docker Compose / Dockerfile deployment with China mirror configuration.
- If ANY image is NOT accessible → Fallback to native build (install runtime, build from source, run directly).
Docker mirror configuration (MUST include in start script when using Docker):
⚠️ System config modification: This step writes to/etc/docker/daemon.json(system-level, requires root). The snippet below performs a safe merge that preserves any existing keys (e.g.data-root,log-driver) and creates a timestamped backup before any change. Do NOT use a naiveprintf > daemon.jsonthat would clobber existing config.
# Configure China Docker registry mirrors (safe merge, preserves existing config)
mkdir -p /etc/docker
DAEMON_JSON=/etc/docker/daemon.json
MIRRORS='["https://registry.cn-hangzhou.aliyuncs.com", "https://mirror.ccs.tencentyun.com"]'
if [ -f "$DAEMON_JSON" ]; then
# Backup existing config with timestamp
cp -p "$DAEMON_JSON" "${DAEMON_JSON}.bak.$(date +%Y%m%d%H%M%S)"
# Merge: only add registry-mirrors if missing or empty
python3 -c "
import json, sys
p = '$DAEMON_JSON'
try:
with open(p) as f: cfg = json.load(f)
except Exception:
cfg = {}
mirrors = json.loads('$MIRRORS')
existing = cfg.get('registry-mirrors') or []
# Union without duplicates, preserve order
for m in mirrors:
if m not in existing:
existing.append(m)
cfg['registry-mirrors'] = existing
with open(p, 'w') as f: json.dump(cfg, f, indent=2)
"
else
printf '{"registry-mirrors": %s}\n' "$MIRRORS" > "$DAEMON_JSON"
fi
# Reload Docker only if config actually changed
systemctl restart docker
sleep 3IMPORTANT: Even with mirrors configured, SHA256-pinned images and niche registries (oven/bun, ghcr.io) will FAIL. Always fallback to native build in those cases.
Step 0: Resolve $SKILL_DIR — Cross-Platform Path
Why: This skill ships a Python toolkit at <skill-root>/scripts/deploy_toolkit.py. Different agent platforms install skills to different locations:- Qoder:~/.qoder/skills/alibabacloud-ecs-code-deploy/(or alias~/.qoder/skills/deploy-to-ecs/)
- Claude Code:~/.claude/skills/<name>/(user-scope) or<project>/.claude/skills/<name>/(project-scope)
- Qwen:~/.qwen/skills/<name>/or<project>/.qwen/skills/<name>/
- Other / custom: anywhere reachable via $SKILLS_HOME or explicit env var>
The Agent MUST resolve the absolute skill root once at session start and reuse it everywhere$SKILL_DIRappears inSKILL.md. Hardcoding `~/.qoder/...` or any platform-specific path is FORBIDDEN.
Resolution algorithm — use the FIRST path that exists
The Agent MUST check these candidates in order and pick the first one whose scripts/deploy_toolkit.py exists:
1. The directory the Agent loaded THIS `SKILL.md` from (PRIMARY — Agent runtime metadata; most accurate, platform-independent) 2. $ALIBABACLOUD_ECS_CODE_DEPLOY_SKILL_DIR (explicit override env var) 3. $SKILLS_HOME/alibabacloud-ecs-code-deploy (generic skills home env var) 4. ~/.qoder/skills/alibabacloud-ecs-code-deploy (Qoder default) 5. ~/.qoder/skills/deploy-to-ecs (Qoder alias) 6. ~/.claude/skills/alibabacloud-ecs-code-deploy (Claude Code user-scope) 7. ./.claude/skills/alibabacloud-ecs-code-deploy (Claude Code project-scope, relative to CWD) 8. ~/.qwen/skills/alibabacloud-ecs-code-deploy (Qwen user-scope) 9. ./.qwen/skills/alibabacloud-ecs-code-deploy (Qwen project-scope, relative to CWD) 10. ~/.config/skills/alibabacloud-ecs-code-deploy (XDG-style fallback)
Export and verify (run ONCE at session start, before Step 1)
# Replace <ABSOLUTE_PATH> with the path resolved above (NEVER guess — verify it exists first)
export SKILL_DIR="<ABSOLUTE_PATH>"
# Sanity check — script file must exist
test -f "$SKILL_DIR/scripts/deploy_toolkit.py" || {
echo "❌ Toolkit script not found at: $SKILL_DIR/scripts/deploy_toolkit.py"
echo " Agent: ask the user where the skill is installed, OR fall back to manual CLI commands."
exit 1
}
echo "✅ SKILL_DIR=$SKILL_DIR"Usage convention
All SKILL.md commands write python3 "$SKILL_DIR/scripts/deploy_toolkit.py" <subcmd>. The Agent must turn that template into a real, working command using ONE of the two patterns below. A third pattern that LOOKS correct but silently breaks is documented as a forbidden anti-pattern.
✅ Pattern A — persistent shell (recommended when the platform reuses one shell)
# Run ONCE at session start (e.g. after Step 0 verification)
export SKILL_DIR="/absolute/path/to/skill"
# Then every later command can reference $SKILL_DIR normally
python3 "$SKILL_DIR/scripts/deploy_toolkit.py" check✅ Pattern B — fresh shell per tool call (recommended when each command is a NEW shell)
Inline the absolute path directly. Do NOT use `$SKILL_DIR` in this case.
python3 "/home/user/.qwen/skills/alibabacloud-ecs-code-deploy/scripts/deploy_toolkit.py" checkIf you really want a variable for readability, set + use it inside ONE shell invocation:
bash -c 'SKILL_DIR="/home/user/.qwen/skills/alibabacloud-ecs-code-deploy"; python3 "$SKILL_DIR/scripts/deploy_toolkit.py" check'⛔ Anti-pattern — DO NOT USE (silently fails)
# THIS DOES NOT WORK. $SKILL_DIR is expanded by the OUTER shell BEFORE the
# command-prefix assignment takes effect, so it expands to the empty string and
# python3 ends up trying to open "/scripts/deploy_toolkit.py" → ENOENT.
SKILL_DIR="/home/user/.qwen/skills/alibabacloud-ecs-code-deploy" \
python3 "$SKILL_DIR/scripts/deploy_toolkit.py" checkWhy it fails: in POSIX shells, command-prefix variable assignments (VAR=value command ...) only populate the child process's environment. Quoted "$VAR" on the same line is expanded by the parent shell before the assignment is applied — at which point $VAR is still unset/empty. The error you'll see looks like:
python3: can't open file '/scripts/deploy_toolkit.py': [Errno 2] No such file or directoryIf you ever see that exact error, the cause is this anti-pattern — switch to Pattern A or B.
Fallback
If none of the candidates above contain scripts/deploy_toolkit.py, the Agent MUST stop and either ask the user where the skill is installed, or follow the manual CLI flow documented in SKILL.md Task 1/Task 2. Do NOT silently re-implement the toolkit logic with raw commands.
Step-by-Step Tutorial: Deploy a Python Flask App
A concrete walk-through that satisfies SHOULD 1.2.4. The example shows the inputs the Agent should send and the expected outputs at each step. Use this together with the workflow rules in SKILL.md.
Prerequisites
- Local project at
~/projects/my-flask-app/containingapp.pyandrequirements.txt. - Alibaba Cloud account with the default credential chain configured (RAM Role / env vars /
~/.aliyun/config.json). python3available; thealiyunCLI may or may not be installed (Step 2 takes care of it).
Step 1: Enter the project directory
Input:
cd ~/projects/my-flask-app && lsExpected output:
Dockerfile README.md app.py requirements.txtStep 2: Resolve $SKILL_DIR and run environment check
Input:
export SKILL_DIR="$HOME/.qoder/skills/alibabacloud-ecs-code-deploy"
test -f "$SKILL_DIR/scripts/deploy_toolkit.py" && echo OK
python3 "$SKILL_DIR/scripts/deploy_toolkit.py" checkExpected output (success path):
OK
=== Environment Check ===
✅ aliyun CLI: 3.3.19 (>=3.3.19) [active: /usr/local/bin/aliyun]
✅ appmanager-cli: 1.1.1 (>=1.1.1)
✅ credentials: profile=default region=cn-beijing ak=LTAI***abcd
=== Environment Check Done ===
✅ All checks passed. Ready to deploy.If any check exits 1, follow the script's → AGENT: DO NOT stop. ASK user ... hint verbatim before proceeding.
Step 3: Initialize .appmanager/config.yaml
Ask the user for region + ECS target (see Task 3 in SKILL.md), then run:
aliyun appmanager init --non-interactive \
--name my-flask-app \
--type app \
--region cn-beijing \
--port 8080Expected: .appmanager/config.yaml is created. Edit it to add common.scripts.start / common.scripts.stop. Key fragment:
metadata:
name: my-flask-app
type: app
groupName: default-cn-beijing
regionId: cn-beijing
common:
deployment:
ecsInstanceType: ecs.u1-c1m2.large
systemDiskSize: 40
internetMaxBandwidthOut: 5
scripts:
start: |
#!/bin/bash
set -e
command -v unzip >/dev/null || yum install -y unzip
ZIP=$(find /root -maxdepth 2 -name 'my-flask-app*.zip' | head -1)
mkdir -p /root/my-flask-app && unzip -o "$ZIP" -d /root/my-flask-app
cd /root/my-flask-app
command -v python3 >/dev/null || yum install -y python3
pip3 install -r requirements.txt
[ -f /root/app.pid ] && kill "$(cat /root/app.pid)" 2>/dev/null || true
nohup python3 app.py >> /root/app.log 2>&1 &
echo $! > /root/app.pid
sleep 3 && cat /root/app.log
stop: |
#!/bin/bash
[ -f /root/app.pid ] && kill "$(cat /root/app.pid)" 2>/dev/null || trueStep 4: Pre-deploy price check + user confirmation
Input:
python3 "$SKILL_DIR/scripts/deploy_toolkit.py" price --config .appmanager/config.yamlExpected output (excerpt — the Agent must relay both the price block and the OSS notice to the user):
==================================================
📊 Deployment Price Estimate
==================================================
Region : cn-beijing
...
💰 Total: CNY 0.06000/hour
Monthly estimate: CNY 43.20/month (30 days x 24 hours)
==================================================
📦 OSS extra billing (not covered by `appmanager price`; relay to the user):
- OSS standard storage: ~CNY 0.12/GB/month ...
=== AGENT_CONFIRM_REQUIRED ===Agent then asks the user (example wording — see Task 4.5 in SKILL.md): "Estimated cost: CNY 0.06/hour (~CNY 43.20/month); the deployment also incurs minor OSS storage/request fees. Confirm to continue?"
Step 5: Deploy and verify
Input:
python3 "$SKILL_DIR/scripts/deploy_toolkit.py" deploy \
--type app --name my-flask-app --group default-cn-beijing --region cn-beijing
python3 "$SKILL_DIR/scripts/deploy_toolkit.py" verify \
--type app --name my-flask-app --group default-cn-beijing --region cn-beijing --wait 10Expected (success):
--- Deploy command completed (exit 0) ---
✅ Deploy submitted. Use 'deploy_toolkit.py verify' to check if app is actually running.
...
=== Post-deploy Verification ===
ECS Public IP: 47.95.xxx.xxx
--- Application Log (source: cloud_assistant) ---
* Serving Flask app 'app'
* Running on http://0.0.0.0:8080
=== AGENT_ANALYZE_REQUIRED ===
log_source: cloud_assistant
ecs_instance: i-2zexxxxxxxxxxxxxxxxxxxThe Agent then prints the self-check report and the final output (console link + cost reminder + management commands).
Edge cases
| Situation | What to do |
|---|---|
ReleaseCancelled returned by deploy | The start script failed/timed out on ECS. Run verify -> read /root/app.log -> fix the start script -> redeploy (max 3 retries). |
NotEnoughBalance error | Pay-as-you-go ECS requires balance >= CNY 100. Direct the user to https://usercenter2.aliyun.com/finance/fund-management or switch to existing ECS. |
AccessDenied at upload_to_oss | OSS bucket name <app_name>-<region> is globally unique. Change --name to a more unique value, delete .appmanager/, and re-init + redeploy. |
| Existing-ECS impact warning | Ask the user explicitly: deploying may stop/overwrite other apps on the instance. STOP if user refuses. |
| Cloud Assistant log fetch fails | Surface the SSH fallback ssh root@<ECS_IP> 'tail -100 /root/app.log' and the HTTP port probe result printed by verify. |
PyYAML==6.0.2
Related skills
FAQ
What does it deploy by default?
Without a path or URL it deploys the current working directory; if given a git URL it clones and deploys that.
Does it verify the deployment?
Yes. It must run deploy_toolkit.py verify and fix issues before reporting success; skipping log verification is not allowed.