@clawhub-sdk-team-83914865ba
Alibaba Cloud OSS scheduled local-folder sync skill using aliyun CLI, including integrated ossutil commands for incremental upload. Use when the user wants t...
---
name: alibabacloud-oss-manage-cron-upload
description: |
Alibaba Cloud OSS scheduled local-folder sync skill using aliyun CLI, including integrated ossutil commands for incremental upload.
Use when the user wants to schedule recurring local-to-OSS uploads, validate OSS backup prerequisites,
set up cron or Task Scheduler for OSS sync, or clearly separate what stays on aliyun CLI
from what remains OS-local or manual.
Conditional write operations: creates the target bucket (PutBucket) only when the user confirms the bucket does not exist yet;
optionally deletes test objects (DeleteObject) only when the user explicitly requests cleanup after verification.
Triggers: "OSS scheduled sync", "定时同步到OSS", "aliyun ossutil cp --max-age", "aliyun ossutil cp -u",
"cron upload to OSS", "Task Scheduler OSS upload", "aliyun CLI OSS sync", "本地目录增量上传 OSS".
---
# OSS Scheduled Local Sync
Plan and validate scheduled local-folder-to-OSS uploads with an aliyun-CLI-first workflow.
## Scenario Description
This skill covers the case where a local folder changes over time and must be uploaded to OSS on a recurring schedule.
**Architecture**: `Local folder + aliyun CLI (integrated ossutil) + cron/Task Scheduler + OSS Bucket`
**Capability split**:
- `[aliyun CLI]` installation checks, profile verification, command discovery, OSS-side verification, and integrated `aliyun ossutil` upload/list commands.
- `[OS-local]` cron or Windows Task Scheduler configuration.
- `[Manual/Console]` RAM policy attachment and optional visual verification in the OSS Console.
## Installation
> **Pre-check: Aliyun CLI >= 3.3.3 required**
> Run `aliyun version` to verify `>= 3.3.3`. If not installed or version too low,
> see `references/cli-installation-guide.md` for installation instructions.
> Then run `aliyun configure set --auto-plugin-install true`.
> At the **start** of the Core Workflow (before any CLI invocation):
> **[MUST] Enable AI-Mode** — AI-mode is required for Agent Skill execution.
> Run the following commands before any CLI invocation:
> ```bash
> aliyun configure ai-mode enable
> aliyun configure ai-mode set-user-agent --user-agent "AlibabaCloud-Agent-Skills/alibabacloud-oss-manage-cron-upload"
> ```
> **[MUST] Disable AI-Mode at EVERY exit point** — Before delivering the final response for ANY reason, always disable AI-mode first. This applies to ALL exit paths: workflow success, workflow failure, error/exception, user cancellation, session end, or any other scenario where no further CLI commands will be executed.
> AI-mode is only used for Agent Skill invocation scenarios and MUST NOT remain enabled after the skill stops running.
> ```bash
> aliyun configure ai-mode disable
> ```
> **[MUST] CLI User-Agent** — Every `aliyun` CLI command invocation must include:
> `--user-agent AlibabaCloud-Agent-Skills/alibabacloud-oss-manage-cron-upload`
Required local tools:
| Tool | Required | Purpose | Verify |
| --- | --- | --- | --- |
| `aliyun` CLI | Yes | Credential gate, command discovery, and integrated `ossutil` upload/list surface | `aliyun version` and `aliyun ossutil --help` |
| `cron` or `schtasks` | Yes | Local recurring execution | `crontab -l` or `schtasks /Query /TN "OSS Scheduled Sync"` |
Use `references/cli-installation-guide.md` only for CLI installation and plugin setup. For this skill, use the integrated `aliyun ossutil` command surface — do **not** require standalone `ossutil` installation or bare `ossutil` commands.
## Environment Variables
No extra cloud-specific environment variables are required beyond an already configured Alibaba Cloud profile.
Optional local variables used in examples:
| Variable | Required/Optional | Description | Default Value |
| --- | --- | --- | --- |
| `ALIBABA_CLOUD_PROFILE` | Optional | Select a preconfigured Alibaba Cloud CLI profile | CLI current profile |
| `ALIYUN_BIN` | Optional | Absolute path to `aliyun` if it is not already in `PATH` | `aliyun` |
| `OSS_SYNC_LOG` | Optional | Log file path for scheduled execution | OS-specific local path |
## Parameter Confirmation
> **Parameter Extraction** — Extract all user-customizable parameters directly from the user's request.
> When the user's message already specifies values (such as region, bucket name, paths, schedule, or MaxAge),
> use those values directly without asking for re-confirmation.
> Only ask the user for clarification when a **required** parameter is genuinely missing from their request
> and cannot be reasonably inferred from context.
| Parameter Name | Required/Optional | Description | Validation Pattern | Default Value |
| --- | --- | --- | --- | --- |
| `RegionId` | Required | OSS region such as `cn-hangzhou` | `^[a-z]{2}-[a-z]+(|-[0-9]+)$` | None |
| `BucketName` | Required | Target OSS bucket name | `^[a-z0-9][a-z0-9-]{1,61}[a-z0-9]$` | None |
| `TargetOssPrefix` | Required | Bucket-relative target OSS prefix such as `backup/photos/` (confirm without a leading `/`) | `^[A-Za-z0-9/_.-]*$` (no leading `/`) | None |
| `LocalSourcePath` | Required | Local folder to upload | Absolute path, no `~`, `$`, backtick, or `;` | None |
| `Schedule` | Required | Cron expression or Windows schedule time/frequency | Standard 5-field cron or `schtasks` time | None |
| `MaxAge` | Required | `aliyun ossutil --max-age` window such as `7d` or `24h` | `^[0-9]+[dhm]$` | None |
| `OperatingSystem` | Required | `linux`, `macos`, or `windows` | `^(linux|macos|windows)$` | None |
| `BucketAlreadyExists` | Required | Whether the target bucket already exists | `^(yes|no)$` | None |
| `AliyunBinaryPath` | Optional | Absolute path to `aliyun` for scheduler use | Absolute path, no `$`, backtick, or `;` | `aliyun` |
| `LogPath` | Optional | Local log path for the scheduled job | Absolute path, no `$`, backtick, or `;` | OS-specific local path |
> **Input Validation — All parameters must be validated before use.**
> Treat all inputs (including values extracted from user messages) as untrusted. Before substituting any parameter into a shell command:
> 1. Validate the value against the **Validation Pattern** column above. Reject values that do not match.
> 2. `BucketName` must contain only lowercase letters, digits, and hyphens (`[a-z0-9-]`), be 3–63 characters, and must not start or end with a hyphen.
> 3. `RegionId` must match the Alibaba Cloud region format (e.g., `cn-hangzhou`, `us-west-1`, `ap-southeast-5`).
> 4. `MaxAge` must be a positive integer followed by `d` (days), `h` (hours), or `m` (minutes).
> 5. `LocalSourcePath`, `AliyunBinaryPath`, and `LogPath` must be absolute paths and must **not** contain shell metacharacters (`$`, `` ` ``, `$(`, `;`, `|`, `&`, `>`, `<`, `\n`).
> 6. `TargetOssPrefix` must contain only alphanumeric characters, `/`, `_`, `.`, and `-`, and must not start with `/`.
> 7. If any parameter fails validation, **stop and report the error** to the user. Do not attempt to sanitize or escape invalid values — reject them outright.
## Authentication
> **Pre-check: Alibaba Cloud Credentials Required**
>
> **Security Rules:**
> - **NEVER** read, echo, or print AK/SK values (e.g., `echo $ALIBABA_CLOUD_ACCESS_KEY_ID` is FORBIDDEN)
> - **NEVER** read or `cat` credential files such as `~/.aliyun/config.json`, `~/.ossutil/config`, or any file that may contain secrets
> - **NEVER** ask the user to input AK/SK directly in the conversation or command line
> - **NEVER** use `aliyun configure set` with literal credential values
> - **ONLY** use `aliyun configure list` to check credential status
>
> ```bash
> aliyun configure list
> ```
> Check the output for a valid profile (AK, STS, or OAuth identity).
>
> **If no valid profile exists, STOP here.**
> 1. Obtain credentials from [Alibaba Cloud Console](https://ram.console.aliyun.com/manage/ak)
> 2. Configure credentials **outside of this session** (via `aliyun configure` in terminal or environment variables in shell profile)
> 3. Return and re-run after `aliyun configure list` shows a valid profile
Reuse the active CLI profile for all `aliyun ossutil` commands. Do not print or hardcode secrets. Do not replace this gate with `ossutil config` or any other secret-entry flow.
## RAM Policy
The default workflow needs least-privilege access for bucket discovery, bucket metadata verification, and object upload under the confirmed prefix.
| Scope | Required Actions |
| --- | --- |
| Account-level verification | `oss:ListBuckets` |
| Target bucket verification | `oss:GetBucketInfo` |
| Incremental upload to target prefix | `oss:PutObject`, `oss:GetObject`, `oss:ListObjects` |
| Optional test cleanup | `oss:DeleteObject` |
Use `references/ram-policies.md` for the policy JSON and the prefix-scoped resource examples.
Do **not** redefine the default minimum set around `oss:AbortMultipartUpload`. In this skill, the default least-privilege path stays anchored on bucket discovery, bucket metadata verification, and prefix-scoped upload/list/read actions. Multipart-cleanup permissions are follow-up work only when the user explicitly asks for them.
## Core Workflow
> **Execute, don't just document.** Run each step's commands directly in the environment. Do not only write solution documents or scripts — actually execute `aliyun version`, `aliyun configure list`, `aliyun ossutil cp`, etc. against the live environment.
>
> Extract `RegionId`, `BucketName`, `TargetOssPrefix`, `LocalSourcePath`, `Schedule`, `MaxAge`, `OperatingSystem`, and `BucketAlreadyExists` from the user's request. Only ask the user if a required parameter is genuinely missing.
### Step 1: Verify CLI and credentials `[aliyun CLI]`
```bash
aliyun version
aliyun configure list
aliyun configure ai-mode enable
```
Verify that:
- `aliyun` version is `>= 3.3.3`
- at least one valid profile is present
- AI safety mode is enabled (dangerous operations will be blocked)
If the version is too low or `aliyun` is missing, see `references/cli-installation-guide.md`. Do not work around a missing CLI by switching to standalone `ossutil` or `aliyun ossutil sync`.
### Step 2: Verify or create the bucket prerequisite `[aliyun CLI]`
Always start by checking the candidate bucket inventory:
```bash
aliyun ossutil api list-buckets --output-format json \
--read-timeout 60 --connect-timeout 30 \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-oss-manage-cron-upload
```
If `BucketAlreadyExists=yes`, verify the selected bucket explicitly:
```bash
aliyun ossutil stat "oss://BucketName" --region "RegionId" --output-format json \
--read-timeout 60 --connect-timeout 30 \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-oss-manage-cron-upload
```
> **Cross-region note**: When the active CLI profile's region (shown by `aliyun configure list`) differs from the target bucket's `RegionId`, you **must** add `--region "RegionId"` to `stat`, `ls`, and `cp` commands. Using `--endpoint` alone is insufficient because the request signing region must also match. The `--region` flag overrides both the endpoint and the signing region in a single step.
What to confirm:
- the bucket name is present in the account inventory
- the bucket region matches `RegionId`
- the bucket is reachable with the active profile
- if multiple existing buckets can satisfy the same backup target, you can remind the user that a bucket with versioning enabled is preferable for backup safety, but this is only a recommendation and does not block using the confirmed existing bucket
If `BucketAlreadyExists=no`, use the **check-then-act** idempotent pattern:
1. First run `list-buckets` (above) to confirm the bucket truly does not exist in the account — if it already exists, skip creation and go directly to `stat` verification.
2. Only if the bucket is confirmed absent, create it by following the existing creation flow of this skill.
3. After creation, immediately re-run `stat` to verify:
```bash
aliyun ossutil stat "oss://BucketName" --region "RegionId" --output-format json \
--read-timeout 60 --connect-timeout 30 \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-oss-manage-cron-upload
```
Optional recommendation for recurring backup scenarios:
- if multiple candidate buckets exist and one already has versioning enabled, mention that it is preferable for backup rollback safety
- if the confirmed existing bucket does not have versioning enabled, it can still be used for this workflow; enabling versioning is only an optional hardening suggestion, not a prerequisite
Keep `aliyun ossutil` as the canonical surface for upload and verification commands such as `cp`, `ls`, and `stat`. For bucket creation, follow the existing creation flow already documented by this skill instead of inventing a new command family here. Do **not** fabricate success, extra deployment files, or fake local artifacts just to cover a missing prerequisite.
### Step 3: Run the canonical incremental upload test `[aliyun CLI / integrated ossutil]`
Use the official data-plane command family for the actual scheduled upload job through `aliyun ossutil`:
```bash
aliyun ossutil cp "LocalSourcePath" "oss://BucketName/TargetOssPrefix" \
-r -u \
--max-age "MaxAge" \
--region "RegionId" \
--read-timeout 300 --connect-timeout 30 \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-oss-manage-cron-upload
```
Key rules for this command:
- `-u` is mandatory: uploads only when the target object is missing or the source file is newer than the existing OSS object
- `-r -u --max-age` must stay together as the canonical flag set
- `--region "RegionId"` ensures both endpoint and signing region are correct
- `--read-timeout 300 --connect-timeout 30` prevents the command from hanging indefinitely; adjust `--read-timeout` upward for very large files if needed
- Add `-f` only for unattended runs (cron, Task Scheduler, CI)
- Use absolute paths for `LocalSourcePath` (never `~`)
- Normalize `TargetOssPrefix` without a leading `/`
- Do **not** substitute with bare `ossutil`, `aliyun ossutil sync`, or `Cache-Control` metadata rewrites
If `TargetOssPrefix` is empty, use `oss://BucketName/` (with trailing slash). Otherwise use `oss://BucketName/TargetOssPrefix` after prefix normalization.
> **If `LocalSourcePath` does not exist** in the current environment (e.g., container or CI runner), create it under the current working directory with a small test file, then run the upload command against it and verify with `aliyun ossutil ls`. This proves the upload path works end-to-end. Do **not** skip the upload test just because the directory is absent — create it and validate connectivity, permissions, and command correctness:
> ```bash
> mkdir -p "LocalSourcePath" && echo "test" > "LocalSourcePath/test.txt"
> aliyun ossutil cp "LocalSourcePath" "oss://BucketName/TargetOssPrefix" \
> -r -u --max-age "MaxAge" --region "RegionId" \
> --read-timeout 300 --connect-timeout 30 \
> --user-agent AlibabaCloud-Agent-Skills/alibabacloud-oss-manage-cron-upload
> aliyun ossutil ls "oss://BucketName/TargetOssPrefix" --region "RegionId" \
> --read-timeout 60 --connect-timeout 30 \
> --user-agent AlibabaCloud-Agent-Skills/alibabacloud-oss-manage-cron-upload
> ```
### Step 4: Wrap the upload in a local script `[aliyun CLI + OS-local]`
Minimal script template:
```bash
#!/usr/bin/env bash
set -euo pipefail
ALIYUN_BIN="-aliyun"
LOCAL_SOURCE_PATH="LocalSourcePath" # MUST be an absolute path, never use ~
BUCKET_NAME="BucketName"
TARGET_OSS_PREFIX="TargetOssPrefix#/"
MAX_AGE="MaxAge"
REGION_ID="RegionId"
LOG_FILE="-$HOME/oss-sync.log"
READ_TIMEOUT="-600"
CONNECT_TIMEOUT="-30"
# --- Input validation ---
[[ "BUCKET_NAME" =~ ^[a-z0-9][a-z0-9-]{1,61}[a-z0-9]$ ]] || { echo "ERROR: Invalid BucketName: BUCKET_NAME" >&2; exit 1; }
[[ "REGION_ID" =~ ^[a-z]{2}-[a-z]+(|-[0-9]+)$ ]] || { echo "ERROR: Invalid RegionId: REGION_ID" >&2; exit 1; }
[[ "MAX_AGE" =~ ^[0-9]+[dhm]$ ]] || { echo "ERROR: Invalid MaxAge: MAX_AGE" >&2; exit 1; }
[[ "TARGET_OSS_PREFIX" =~ ^[A-Za-z0-9/_.-]*$ ]] || { echo "ERROR: Invalid TargetOssPrefix: TARGET_OSS_PREFIX" >&2; exit 1; }
[[ "LOCAL_SOURCE_PATH" == /* ]] || { echo "ERROR: LocalSourcePath must be absolute: LOCAL_SOURCE_PATH" >&2; exit 1; }
TARGET_URI="oss://BUCKET_NAME/"
if [ -n "TARGET_OSS_PREFIX" ]; then
TARGET_URI="oss://BUCKET_NAME/TARGET_OSS_PREFIX"
fi
"ALIYUN_BIN" ossutil cp "LOCAL_SOURCE_PATH" "TARGET_URI" \
-r -u -f \
--max-age "MAX_AGE" \
--region "REGION_ID" \
--read-timeout "READ_TIMEOUT" --connect-timeout "CONNECT_TIMEOUT" \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-oss-manage-cron-upload >> "LOG_FILE" 2>&1
```
> **Note**: The `-f` flag is included in the script template because the script is intended for unattended cron/Task Scheduler execution where interactive prompts must not block the job. The `--region` flag is preferred over `--endpoint` because it sets both the endpoint and signing region correctly, which is required when the CLI profile's default region differs from the target bucket's region.
### Step 5: Configure the scheduler `[OS-local]`
**Linux/macOS cron**:
For the default Linux/macOS path in this skill, keep `cron` / `crontab` as the documented scheduler surface. Do **not** silently swap the answer to `launchd` unless the user explicitly asks for a launchd-specific variant.
> **If `crontab` is not found**: In container or minimal environments, `crontab` may not be pre-installed. Install the `cronie` package first:
> - CentOS/Alibaba Cloud Linux/RHEL: `yum install -y cronie`
> - Debian/Ubuntu: `apt-get install -y cron`
>
> If `systemctl start crond` fails (e.g., no systemd in containers), you can still add cron entries via `crontab` — the cron daemon is not strictly required for entry registration, only for actual execution. In such cases, document the cron entry for the user to deploy on their production host, and do **not** let the missing daemon block the rest of the workflow.
```bash
crontab -e
```
Example entry (use `echo ... | crontab -` for non-interactive installation):
```cron
0 3 * * * /usr/local/bin/oss-sync-upload.sh >> /var/log/oss-sync-cron.log 2>&1
```
**Windows Task Scheduler** via local CLI:
```bat
schtasks /Create /SC DAILY /ST 03:00 /TN "OSS Scheduled Sync" /TR "C:\tools\oss-sync-upload.bat"
```
Label this step clearly as OS-local. It is not an Alibaba Cloud API action. Keep the scheduler output minimal and directly actionable; do not explode this step into extra README files, XML exports, PowerShell wrappers, demo payloads, or other auxiliary artifacts unless the user explicitly asks for them.
### Step 6: Verify the upload target `[aliyun CLI / integrated ossutil]`
Always run this verification after any upload (including test uploads from Step 3):
```bash
aliyun ossutil ls "oss://BucketName/TargetOssPrefix" --region "RegionId" \
--read-timeout 60 --connect-timeout 30 \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-oss-manage-cron-upload
```
Confirm that the expected objects appear under the target prefix. Do **not** skip this step — it proves end-to-end connectivity and permissions.
If the user wants a manual visual check, label it clearly as `[Manual/Console]` and confirm the target prefix in the OSS Console.
### Step 7: State the capability boundary clearly
Always state these limitations when relevant:
- **The actual incremental sync step runs through `aliyun ossutil`.** This skill stays on the `aliyun` CLI surface and does not require a separate standalone `ossutil` installation.
- **Scheduler setup is OS-local.** Cron and Task Scheduler are configured on the host OS, not through Alibaba Cloud APIs.
- **RAM policy attachment is typically manual or follows the user's existing IAM workflow.**
- **Bucket creation should happen before scheduled upload when the target bucket is missing.** Follow the existing creation flow of this skill for that prerequisite.
- **If multiple equivalent existing buckets are available, it is fine to remind the user that a versioning-enabled bucket is preferable for backup safety.** If no versioned bucket is available, continue with the confirmed existing bucket instead of blocking the workflow.
- **Optional OSS Console checks are manual.**
- **Do not simulate success.** When a prerequisite is missing, say so plainly instead of creating fake local test data, pretend execution logs, or extra packaging artifacts.
## Success Verification Method
Use `references/verification-method.md` as the authoritative checklist.
Minimum pass conditions:
1. `aliyun configure list` shows a valid profile.
2. `aliyun ossutil cp --help` succeeds.
3. the canonical `aliyun ossutil cp ... -r -u --max-age ... --region ...` command completes without permission or endpoint errors.
4. `aliyun ossutil ls ... --region ...` shows the expected uploaded objects under the confirmed prefix.
5. the upload command keeps `-u`, meaning it uploads only when the target object is missing or the local source file is newer than the existing OSS object.
6. the local scheduler entry is visible through `crontab -l` or Task Scheduler history/query, or is documented for the user when crontab is not available in the current environment.
## Cleanup
Cleanup is optional because this skill is intended for recurring sync, but test artifacts and scheduler entries can be removed safely.
**Linux/macOS cron** `[OS-local]`:
- remove the cron line with `crontab -e`
- delete the local script and log file only if the user explicitly wants rollback
**Windows Task Scheduler** `[OS-local]`:
```bat
schtasks /Delete /TN "OSS Scheduled Sync" /F
```
**Optional OSS test cleanup** `[aliyun CLI / integrated ossutil]`:
```bash
aliyun ossutil rm "oss://BucketName/TargetOssPrefixtest-object.txt" --region "RegionId" \
--read-timeout 60 --connect-timeout 30 \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-oss-manage-cron-upload
```
Do not delete the bucket or production objects unless the user explicitly asks for that cleanup scope.
**Disable AI safety mode** `[aliyun CLI]`:
After all tasks are completed, disable AI safety mode to restore normal CLI behavior:
```bash
aliyun configure ai-mode disable
```
## API and Command Tables
See `references/related-apis.md` for the command inventory, OSS capability notes, and validation notes. That file is reference metadata only.
## Best Practices
1. Keep `aliyun` for pre-checks, command discovery, bucket verification, and integrated `aliyun ossutil cp` for the actual scheduled upload.
2. Use `--region "RegionId"` on all `aliyun ossutil` commands (`stat`, `cp`, `ls`, `rm`) to ensure both endpoint and signing region are correct. This is especially important when the CLI profile's default region differs from the target bucket's region. Do **not** rely on `--endpoint` alone, as it does not override the signing region and will fail with "Invalid signing region in Authorization header" errors when using STS tokens across regions.
3. Keep scheduler steps labeled as OS-local so the user understands they are outside Alibaba Cloud APIs.
4. Use the narrowest RAM policy possible: bucket inventory at account scope, bucket info on the target bucket, and object upload only on the confirmed prefix.
5. Run `aliyun version` and `aliyun configure list` on the target machine before live execution.
6. Never print AK/SK values, never hardcode them in scripts, never read credential files like `~/.aliyun/config.json`, and never replace the credential gate with inline secret handling.
7. If the bucket does not exist, create it first before configuring scheduled upload. If multiple existing buckets can satisfy the same backup target, you may remind the user that a versioning-enabled bucket is preferable for backup safety, but if no such bucket exists, continue with the confirmed existing bucket.
8. Always use absolute paths for `LocalSourcePath` in commands and scripts. Do not use `~` (tilde) because it may not expand inside quoted strings, causing "not a directory" errors.
9. In generated scripts intended for cron or Task Scheduler, include the `-f` flag to prevent interactive confirmation prompts from blocking unattended execution.
## Reference Links
| Reference | Description |
| --- | --- |
| `references/cli-installation-guide.md` | Required CLI installation guide copied from the creator skill asset |
| `references/verification-method.md` | Pre-check, upload, scheduler, and manual verification checklist |
| `references/related-apis.md` | `aliyun` and integrated `ossutil` command inventory with OSS API mapping |
| `references/ram-policies.md` | Least-privilege RAM policy guidance for verification and upload |
| `references/acceptance-criteria.md` | Correct and incorrect command patterns for this scenario |
FILE:references/acceptance-criteria.md
# Acceptance Criteria: alibabacloud-oss-manage-cron-upload
**Scenario**: `Scheduled incremental sync from a local folder to OSS`
**Purpose**: Verify that the skill stays aliyun-CLI-first, preserves the canonical `aliyun ossutil cp` upload command, and clearly labels manual or OS-local steps.
---
# Correct CLI Command Patterns
## 1. Aliyun plugin-mode command shape
#### ✅ CORRECT
```bash
aliyun oss --help
aliyun ossutil api list-buckets --output-format json --user-agent AlibabaCloud-Agent-Skills
aliyun ossutil stat "oss://example-bucket" --output-format json --user-agent AlibabaCloud-Agent-Skills
```
Why it is correct:
- product and subcommands are lowercase plugin-mode commands
- every live `aliyun` command stays on the `aliyun` CLI surface documented by this skill
#### ❌ INCORRECT
```bash
aliyun OSS Help
aliyun ossutil api ListBuckets
aliyun ossutil stat "oss://example-bucket"
```
Why it is incorrect:
- uses non-plugin command shapes or mixed casing
- drifts away from the documented CLI form
## 2. Credential verification gate
#### ✅ CORRECT
```bash
aliyun configure list
```
Why it is correct:
- verifies profile availability without printing secrets
- matches the skill's safe authentication rule
#### ❌ INCORRECT
```bash
echo "$ALIBABA_CLOUD_ACCESS_KEY_ID"
aliyun configure set --access-key-id YOUR_ID --access-key-secret YOUR_SECRET
```
Why it is incorrect:
- prints or inlines credentials
- bypasses the required credential gate
## 3. Canonical incremental upload command
#### ✅ CORRECT
```bash
aliyun ossutil cp "LocalSourcePath" "oss://BucketName/TargetOssPrefix" \
-r -u \
--max-age "MaxAge" \
--region "RegionId" \
--read-timeout 300 --connect-timeout 30 \
--user-agent AlibabaCloud-Agent-Skills
```
Why it is correct:
- keeps the official `ossutil cp` workflow through `aliyun` CLI
- keeps the canonical incremental flags together
- `-u` means upload only when the target object is missing or the local source file is newer than the existing OSS object
- `-f` is optional and should be added only for explicitly requested non-interactive unattended runs such as cron, Task Scheduler, or CI
- `--region` sets both the endpoint and signing region correctly, which is required when the CLI profile's default region differs from the target bucket's region
- assumes a bucket-relative target prefix rather than an absolute OSS path
Using `--endpoint "oss-RegionId.aliyuncs.com"` in addition to `--region` is also acceptable but not required, since `--region` alone is sufficient and handles cross-region signing correctly.
#### ❌ INCORRECT
```bash
ossutil cp "LocalSourcePath" "oss://BucketName/TargetOssPrefix" -r -u --max-age "MaxAge" --endpoint "oss-RegionId.aliyuncs.com"
ossutil config
aliyun ossutil sync "LocalSourcePath" "oss://BucketName/TargetOssPrefix"
aliyun oss sync "LocalSourcePath" "oss://BucketName/TargetOssPrefix"
aliyun ossutil cp "LocalSourcePath" "oss://BucketName/TargetOssPrefix" -r -u --endpoint "https://oss-RegionId.aliyuncs.com"
aliyun ossutil cp "LocalSourcePath" "oss://BucketName/TargetOssPrefix" --recursive --update --meta "Cache-Control:max-age=604800"
aliyun ossutil cp "LocalSourcePath" "oss://BucketName/TargetOssPrefix" -r -u
aliyun ossutil cp "LocalSourcePath" "oss://BucketName/TargetOssPrefix" -r -u --endpoint "oss-RegionId.aliyuncs.com"
cat ~/.aliyun/config.json
```
Why it is incorrect:
- uses bare `ossutil` instead of the integrated `aliyun ossutil` surface required by this skill
- reintroduces `ossutil config`, which this skill must not use as the in-session auth flow
- replaces the documented `cp` workflow with `sync`
- omits `--max-age`
- rewrites the requested incremental window into unrelated object metadata
- uses `https://` prefix in endpoint which is not the documented format
- uses only `--endpoint` without `--region`, which fails with "Invalid signing region" when the CLI profile region differs from the target bucket region (STS token signing mismatch)
- omits both `--max-age` and `--region`
- reads credential files directly, exposing AK/SK values
## 4. Bucket prerequisite and versioning preference
#### ✅ CORRECT
```text
Use the existing bucket-creation flow documented by this skill, then continue with the verified `aliyun ossutil` upload path.
```
Why it is correct:
- if the bucket is missing, it is created before scheduled upload is configured
- if the bucket already exists, the answer may mention that versioning is preferable for backup safety, but does not block the workflow when no versioned bucket is available
- keeps bucket-management guidance on the `aliyun` CLI surface instead of drifting to unrelated tools
#### ❌ INCORRECT
```text
When the bucket is missing, stop permanently and refuse to show any bucket-creation path.
Never mention that bucket versioning can be beneficial for recurring backup scenarios even when the user asks for safer rollback options.
Treat a non-versioned existing bucket as unusable and block the workflow even though the user already confirmed that bucket.
```
Why it is incorrect:
- leaves the workflow incomplete when the missing-bucket step can be handled first
- drops a key backup-safety preference for recurring sync scenarios
- fails to encode the repository's new bucket-selection priority
## 5. Integrated `ossutil` through `aliyun` CLI
#### ✅ CORRECT
```text
Use aliyun CLI for installation checks, credential verification, help discovery, bucket verification, and the `aliyun ossutil cp` scheduled upload command.
```
Why it is correct:
- matches the user's CLI-only requirement for this skill
- keeps the upload flow on the integrated `aliyun ossutil` surface
#### ❌ INCORRECT
```text
Require a separate standalone `ossutil` installation or document bare `ossutil` commands as the primary path for this skill.
Tell the user to run `brew install ossutil` or `ossutil config` for the default workflow.
```
Why it is incorrect:
- drifts away from the required `aliyun` CLI surface
- reintroduces a separate local dependency that this skill should avoid
- swaps the required `aliyun configure list` gate for an unsupported credential flow
## 6. Scheduler labeling
#### ✅ CORRECT
```text
[OS-local] Configure cron with crontab or configure Windows Task Scheduler with schtasks or the Task Scheduler UI.
```
Why it is correct:
- labels the scheduler as host-level configuration
- makes it clear this is outside Alibaba Cloud APIs
#### ❌ INCORRECT
```text
Use aliyun CLI to create the cron job in OSS.
Use launchd as the default macOS answer even though the requested skill flow is documented around cron.
```
Why it is incorrect:
- misclassifies local scheduler setup as a cloud API operation
- drifts away from the skill's documented cron-first macOS path
## 7. Manual and unvalidated steps
#### ✅ CORRECT
```text
If the bucket is missing, create it first through the existing creation flow of this skill. If the bucket already exists, it is fine to mention that a versioning-enabled bucket is preferable for backup safety, but the confirmed existing bucket can still be used directly.
```
Why it is correct:
- avoids inventing unverified commands
- keeps the user informed about capability boundaries
#### ❌ INCORRECT
```text
Claim that bucket creation, RAM policy attachment, and scheduler setup are fully validated in this repository even though aliyun was not installed locally.
Mark the normal `aliyun ossutil cp ... --max-age ...` upload flow itself as unvalidated and replace it with a placeholder-only local filtering script.
Generate fake success artifacts such as sample upload logs, demo test files, or placeholder execution traces when the real prerequisite is still missing.
```
Why it is incorrect:
- overstates what was actually verified
- hides important operational limits
- blurs the line between truly unvalidated steps and the canonical upload pattern already required by the skill
- encourages simulated success instead of accurate boundary reporting
---
# Validation Checklist
The generated skill passes only if all of the following are true:
1. every live `aliyun` command shown by the skill stays on the documented `aliyun` CLI surface
2. the credential gate uses `aliyun configure list` rather than printing or setting secrets inline
3. the scheduled upload step uses `aliyun ossutil cp` with `-r -u --max-age`
4. the answer explains that `-u` uploads only when the target object is missing or the local source file is newer than the existing OSS object
5. if `-f` is mentioned, it is framed only as an optional flag for explicitly requested non-interactive unattended runs
6. the endpoint format is `oss-RegionId.aliyuncs.com` without `https://`
7. scheduler setup is labeled OS-local
8. if the bucket is missing, the answer creates it first following the existing creation flow of this skill
9. if the bucket already exists, the answer may mention that a versioned bucket is preferable for backup safety, but does not treat versioning as a hard prerequisite
10. macOS default scheduling guidance stays on `cron` / `crontab` unless the user explicitly asks for `launchd`
11. the answer does not replace the canonical upload command with bare `ossutil`, `ossutil config`, `Cache-Control` metadata mapping, or placeholder-only filtering scripts
FILE:references/cli-installation-guide.md
# Aliyun CLI Installation & Configuration Guide
Complete guide for installing and configuring Aliyun CLI.
> **Aliyun CLI 3.3.3+**: Supports installing and using all published Alibaba Cloud product plugins. Make sure to upgrade to 3.3.3 or later for full plugin ecosystem coverage.
## Installation
### macOS
**Using Homebrew (Recommended)**
```bash
brew install aliyun-cli
# Upgrade to latest
brew upgrade aliyun-cli
# Verify version (>= 3.3.3)
aliyun version
```
**Using Binary**
```bash
# Download
wget https://aliyuncli.alicdn.com/aliyun-cli-macosx-latest-amd64.tgz
# Extract
tar -xzf aliyun-cli-macosx-latest-amd64.tgz
# Move to PATH
sudo mv aliyun /usr/local/bin/
# Verify
aliyun version
```
### Linux
**Debian/Ubuntu**
```bash
# Download
wget https://aliyuncli.alicdn.com/aliyun-cli-linux-latest-amd64.tgz
# Extract and install
tar -xzf aliyun-cli-linux-latest-amd64.tgz
sudo mv aliyun /usr/local/bin/
# Verify
aliyun version
```
**CentOS/RHEL**
```bash
# Download
wget https://aliyuncli.alicdn.com/aliyun-cli-linux-latest-amd64.tgz
# Extract and install
tar -xzf aliyun-cli-linux-latest-amd64.tgz
sudo mv aliyun /usr/local/bin/
# Verify
aliyun version
```
**ARM64 Architecture**
```bash
# Download ARM64 version
wget https://aliyuncli.alicdn.com/aliyun-cli-linux-latest-arm64.tgz
# Extract and install
tar -xzf aliyun-cli-linux-latest-arm64.tgz
sudo mv aliyun /usr/local/bin/
```
### Windows
**Using Binary**
1. Download from: https://aliyuncli.alicdn.com/aliyun-cli-windows-latest-amd64.zip
2. Extract the ZIP file
3. Add the directory to your PATH environment variable
4. Open new Command Prompt or PowerShell
5. Verify: `aliyun version`
**Using PowerShell**
```powershell
# Download
Invoke-WebRequest -Uri "https://aliyuncli.alicdn.com/aliyun-cli-windows-latest-amd64.zip" -OutFile "aliyun-cli.zip"
# Extract
Expand-Archive -Path aliyun-cli.zip -DestinationPath C:\aliyun-cli
# Add to PATH (requires admin privileges)
$env:Path += ";C:\aliyun-cli"
[Environment]::SetEnvironmentVariable("Path", $env:Path, [System.EnvironmentVariableTarget]::Machine)
# Verify
aliyun version
```
## Configuration
> **SECURITY WARNING — For human operators only, NOT for agent execution.**
> The credential configuration examples below are reference documentation for users to run **outside of agent sessions**. Agents must **NEVER** execute `aliyun configure set` with `--access-key-id` or `--access-key-secret` flags. During skill execution, agents should **ONLY** use `aliyun configure list` to verify that a valid profile already exists.
### Quick Start
The user should run the following command **outside of the agent session** (e.g., in a separate terminal):
```bash
aliyun configure set \
--mode AK \
--access-key-id <your-access-key-id> \
--access-key-secret <your-access-key-secret> \
--region cn-hangzhou
```
All `aliyun configure` commands support non-interactive flags, which is the recommended approach —
it works in scripts, CI/CD pipelines, and agent-driven automation without hanging on stdin prompts.
**Enable AI Safety Mode (Required for agent-driven workflows)**
After configuring credentials, enable AI safety mode to prevent dangerous operations:
```bash
aliyun configure ai-mode enable
```
**Where to Get Access Keys**
1. Log in to Aliyun Console: https://ram.console.aliyun.com/
2. Navigate to: AccessKey Management
3. Create a new AccessKey pair
4. Save the secret immediately — it's only shown once
### Configuration Modes
Aliyun CLI supports 6 authentication modes. All examples below use non-interactive flags.
> **Note**: All credential configuration examples in this section are for **human operators to run outside of agent sessions**. Agents must NEVER execute these commands.
#### 1. AK Mode (Access Key)
Most common mode for personal accounts and scripts.
```bash
aliyun configure set \
--mode AK \
--access-key-id LTAI5tXXXXXXXX \
--access-key-secret 8dXXXXXXXXXXXXXXXXXXXXXXXX \
--region cn-hangzhou \
```
Configuration is stored in `~/.aliyun/config.json`:
```json
{
"current": "default",
"profiles": [
{
"name": "default",
"mode": "AK",
"access_key_id": "LTAI5tXXXXXXXX",
"access_key_secret": "8dXXXXXXXXXXXXXXXXXXXXXXXX",
"region_id": "cn-hangzhou",
"output_format": "json",
"language": "en"
}
]
}
```
#### 2. StsToken Mode (Temporary Credentials)
For short-lived access (tokens expire in 1-12 hours).
```bash
aliyun configure set \
--mode StsToken \
--access-key-id LTAI5tXXXXXXXX \
--access-key-secret 8dXXXXXXXXXXXXXXXXXXXXXXXX \
--sts-token v1.0:XXXXXXXXXXXXXXXX \
--region cn-hangzhou \
```
Use cases: CI/CD pipelines, temporary access for external contractors, cross-account access.
#### 3. RamRoleArn Mode (Assume RAM Role)
Assume a RAM role for elevated or cross-account access.
```bash
aliyun configure set \
--mode RamRoleArn \
--access-key-id LTAI5tXXXXXXXX \
--access-key-secret 8dXXXXXXXXXXXXXXXXXXXXXXXX \
--ram-role-arn acs:ram::123456789012:role/AdminRole \
--role-session-name my-session \
--region cn-hangzhou \
```
Use cases: cross-account resource access, temporary elevated privileges, role-based access control.
#### 4. EcsRamRole Mode (ECS Instance RAM Role)
Use the RAM role attached to an ECS instance — no credentials needed.
```bash
aliyun configure set \
--mode EcsRamRole \
--ram-role-name MyEcsRole \
--region cn-hangzhou \
```
Requirements: must be running on an ECS instance with a RAM role attached.
Use cases: scripts and automation running on ECS instances.
#### 5. RsaKeyPair Mode (RSA Key Pair)
Use RSA key pair for authentication (generate key pair in Aliyun Console first).
```bash
aliyun configure set \
--mode RsaKeyPair \
--private-key /path/to/private-key.pem \
--key-pair-name my-key-pair \
--region cn-hangzhou \
```
#### 6. RamRoleArnWithEcs Mode (ECS + RAM Role)
Combine ECS instance role with RAM role assumption for cross-account access from ECS.
```bash
aliyun configure set \
--mode RamRoleArnWithEcs \
--ram-role-name MyEcsRole \
--ram-role-arn acs:ram::123456789012:role/TargetRole \
--role-session-name my-session \
--region cn-hangzhou \
```
### Environment Variables
**Highest priority** - overrides config file
**Access Key Mode**
```bash
export ALIBABA_CLOUD_ACCESS_KEY_ID=your_access_key_id
export ALIBABA_CLOUD_ACCESS_KEY_SECRET=your_access_key_secret
export ALIBABA_CLOUD_REGION_ID=cn-hangzhou
```
**STS Token Mode**
```bash
export ALIBABA_CLOUD_ACCESS_KEY_ID=your_access_key_id
export ALIBABA_CLOUD_ACCESS_KEY_SECRET=your_access_key_secret
export ALIBABA_CLOUD_SECURITY_TOKEN=your_sts_token
export ALIBABA_CLOUD_REGION_ID=cn-hangzhou
```
**ECS RAM Role Mode**
```bash
export ALIBABA_CLOUD_ECS_METADATA=role_name
```
**Use Case**:
- CI/CD pipelines
- Docker containers
- Temporary credential override
### Managing Multiple Profiles
**Create Named Profiles**
```bash
aliyun configure set --profile projectA \
--mode AK \
--access-key-id LTAI5tAAAAAAAA \
--access-key-secret 8dAAAAAAAAAAAAAAAAAAAAAAAA \
--region cn-hangzhou
aliyun configure set --profile projectB \
--mode AK \
--access-key-id LTAI5tBBBBBBBB \
--access-key-secret 8dBBBBBBBBBBBBBBBBBBBBBBBB \
--region cn-shanghai \
```
**Use Specific Profile**
```bash
aliyun ecs describe-instances --user-agent AlibabaCloud-Agent-Skills --profile projectA
export ALIBABA_CLOUD_PROFILE=projectA
aliyun ecs describe-instances --user-agent AlibabaCloud-Agent-Skills # Uses projectA
```
**List and Switch Profiles**
```bash
aliyun configure list # List all profiles
aliyun configure set --current projectA # Switch default profile
```
### Credential Priority
Credentials are loaded in this order (first found wins):
1. **Command-line flag**: `--profile <name>`
2. **Environment variable**: `ALIBABA_CLOUD_PROFILE`
3. **Environment credentials**: `ALIBABA_CLOUD_ACCESS_KEY_ID`, etc.
4. **Configuration file**: `~/.aliyun/config.json` (current profile)
5. **ECS Instance RAM Role**: If running on ECS with attached role
## Verification
### Test Authentication
```bash
# Basic test - list regions
aliyun ecs describe-regions --user-agent AlibabaCloud-Agent-Skills
# Expected output: JSON array of regions
```
**If successful**, you'll see:
```json
{
"Regions": {
"Region": [
{
"RegionId": "cn-hangzhou",
"RegionEndpoint": "ecs.cn-hangzhou.aliyuncs.com",
"LocalName": "华东 1(杭州)"
},
...
]
},
"RequestId": "..."
}
```
**If failed**, you'll see error messages:
- `InvalidAccessKeyId.NotFound` - Wrong Access Key ID
- `SignatureDoesNotMatch` - Wrong Access Key Secret
- `InvalidSecurityToken.Expired` - STS token expired (for StsToken mode)
- `Forbidden.RAM` - Insufficient permissions
### Debug Configuration
```bash
# Show current configuration
aliyun configure get
# Test with debug logging
aliyun ecs describe-regions --user-agent AlibabaCloud-Agent-Skills --log-level=debug
# Check credential provider
aliyun configure get mode
```
## Security Best Practices
### 1. Use RAM Users (Not Root Account)
❌ **Don't**: Use Aliyun root account credentials
✅ **Do**: Create RAM users with specific permissions
```bash
# Create RAM user in console
# Attach only necessary policies
# Use RAM user's access keys
```
### 2. Principle of Least Privilege
Grant only the minimum permissions needed:
```bash
# Example: Read-only ECS access
# Attach policy: AliyunECSReadOnlyAccess
```
### 3. Rotate Access Keys Regularly
```bash
# Create new access key in RAM Console, then update configuration (run outside of agent session)
aliyun configure set --access-key-id NEW_KEY --access-key-secret NEW_SECRET
# Delete old access key from console
```
### 4. Use STS Tokens for Temporary Access
```bash
# Run outside of agent session
aliyun configure set --mode StsToken \
--access-key-id XXXX --access-key-secret XXXX \
--sts-token XXXX --region cn-hangzhou
```
### 5. Use ECS RAM Roles When Possible
```bash
# Run outside of agent session
aliyun configure set --mode EcsRamRole --ram-role-name MyRole --region cn-hangzhou
```
### 6. Never Commit Credentials
```bash
# Add to .gitignore
echo "~/.aliyun/config.json" >> .gitignore
# Use environment variables in CI/CD instead
```
### 7. Secure Config File
```bash
# Restrict permissions
chmod 600 ~/.aliyun/config.json
```
## Troubleshooting
### Issue: Command Not Found
```bash
# Check installation
which aliyun
# Check PATH
echo $PATH
# Reinstall or add to PATH
```
### Issue: Authentication Failed
```bash
# Verify configuration
aliyun configure get
# Test with debug
aliyun ecs describe-regions --user-agent AlibabaCloud-Agent-Skills --log-level=debug
# Check credentials in console
# Verify access key is active
```
### Issue: Permission Denied
```bash
# Error: Forbidden.RAM
# Check RAM user permissions
# Attach necessary policies in RAM console
# Example: AliyunECSFullAccess for ECS operations
```
### Issue: STS Token Expired
```bash
# Error: InvalidSecurityToken.Expired
# Reconfigure with new token (run outside of agent session)
aliyun configure set --mode StsToken \
--access-key-id XXXX --access-key-secret XXXX \
--sts-token NEW_TOKEN --region cn-hangzhou
```
### Issue: Wrong Region
```bash
# Some resources may not exist in the specified region
# Check available regions
aliyun ecs describe-regions --user-agent AlibabaCloud-Agent-Skills
# Update default region
aliyun configure set region cn-shanghai
```
## Advanced Configuration
### Custom Endpoint
```bash
# Use custom or private endpoint
export ALIBABA_CLOUD_ECS_ENDPOINT=ecs-vpc.cn-hangzhou.aliyuncs.com
```
### Proxy Settings
```bash
# HTTP proxy
export HTTP_PROXY=http://proxy.example.com:8080
export HTTPS_PROXY=http://proxy.example.com:8080
# No proxy for specific domains
export NO_PROXY=localhost,127.0.0.1,.aliyuncs.com
```
### Timeout Settings
```bash
# Connection timeout (default: 10s)
export ALIBABA_CLOUD_CONNECT_TIMEOUT=30
# Read timeout (default: 10s)
export ALIBABA_CLOUD_READ_TIMEOUT=30
```
## Next Steps
After installation and configuration:
1. **Install plugins** for services you need (v3.3.3+ supports all published product plugins):
```bash
aliyun plugin install --names ecs vpc rds
# List all available plugins
aliyun plugin list-remote
```
2. **Explore commands**:
```bash
aliyun ecs --help
aliyun fc --help
```
3. **Read documentation**:
- [Command Syntax Guide](./command-syntax.md)
- [Global Flags Reference](./global-flags.md)
- [Common Scenarios](./common-scenarios.md)
## References
- Official Documentation: https://help.aliyun.com/zh/cli/
- RAM Console: https://ram.console.aliyun.com/
- Access Key Management: https://ram.console.aliyun.com/manage/ak
- Plugin Repository: https://github.com/aliyun/aliyun-cli
FILE:references/ram-policies.md
# RAM Policies for OSS Scheduled Local Sync
## Overview
This scenario needs least-privilege permissions for four things:
1. account-level bucket discovery
2. target-bucket creation when the bucket is missing
3. target-bucket metadata verification
4. object upload under the confirmed OSS prefix
The default flow still does **not** require broad permissions such as full-bucket administration or account-wide object deletion.
## Required Permission Summary
**Account scope (Resource: `*`)**
- `oss:ListBuckets` — List all buckets under the current account to verify whether the target BucketName already exists
**Target bucket scope (Resource: `acs:oss:*:*:BucketName`)**
- `oss:GetBucketInfo` — Query target bucket metadata (e.g., region, storage class) to verify the bucket is in the correct region
- `oss:PutBucket` — Create the bucket (conditional: only required when `BucketAlreadyExists=no` and the user explicitly requests bucket creation)
**Target prefix scope (Resource: `acs:oss:*:*:BucketName/TargetOssPrefix*`)**
- `oss:PutObject` — Upload new or modified files to the target prefix
- `oss:GetObject` — Read existing object metadata; required by `aliyun ossutil cp -u` incremental upload to compare local files against remote objects
- `oss:ListObjects` — Enumerate existing objects under the target prefix for incremental upload comparison and post-upload verification
- `oss:DeleteObject` — Delete test objects (**optional**: only required when the user explicitly requests automated cleanup of test data)
## Minimal Policy Template
Replace `BucketName` and `TargetOssPrefix` with confirmed values before creating the policy.
Normalize `TargetOssPrefix` first so it is bucket-relative and does not start with `/`.
If `TargetOssPrefix` is empty, replace the object resource with `acs:oss:*:*:BucketName/*`.
```json
{
"Version": "1",
"Statement": [
{
"Effect": "Allow",
"Action": [
"oss:ListBuckets"
],
"Resource": "*"
},
{
"Effect": "Allow",
"Action": [
"oss:GetBucketInfo"
],
"Resource": [
"acs:oss:*:*:BucketName"
]
},
{
"Effect": "Allow",
"Action": [
"oss:PutObject",
"oss:GetObject",
"oss:ListObjects"
],
"Resource": [
"acs:oss:*:*:BucketName",
"acs:oss:*:*:BucketName/TargetOssPrefix*"
]
}
]
}
```
## Optional Cleanup Extension
Only add this if the user explicitly wants the skill to delete test objects after verification:
```json
{
"Effect": "Allow",
"Action": [
"oss:DeleteObject"
],
"Resource": [
"acs:oss:*:*:BucketName/TargetOssPrefix*"
]
}
```
## Bucket Creation Extension
If the bucket may be missing, include bucket-creation permissions in the reviewed policy scope.
> **Idempotent pattern**: Bucket creation must follow a **check-then-act** pattern — first call `list-buckets` to verify the bucket does not exist, then create it only if confirmed absent. This prevents duplicate creation attempts and ensures idempotency. The `aliyun ossutil cp -u` upload command is inherently idempotent (uploads only when the target object is missing or the source file is newer).
Bucket versioning is only an optional hardening suggestion in this repository. Do not add bucket-versioning permissions by default unless the user explicitly asks to manage versioning through CLI as part of the workflow.
## What Not to Grant by Default
Avoid these broad patterns unless the user explicitly asks for expanded scope:
- `AliyunOSSFullAccess`
- account-wide delete permissions
- bucket policy or ACL mutation permissions
- cross-prefix object administration unrelated to the confirmed upload target
- redefining the default minimum policy around `oss:AbortMultipartUpload` instead of the documented `ListBuckets` + `GetBucketInfo` + `PutObject` + `GetObject` + `ListObjects` set
## Attachment Guidance
Policy creation and attachment are usually handled through the RAM Console or the user's existing IAM workflow.
Label this step clearly as manual or existing-IAM-process work. Do not claim the default scenario is fully automated through `aliyun` CLI in this repository, and do not pad the answer with fake attachment scripts or simulated execution output when IAM prerequisites are still unresolved.
## Verification
After the policy is attached, verify with:
```bash
aliyun configure list
aliyun ossutil api list-buckets --output-format json \
--read-timeout 60 --connect-timeout 30 \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-oss-manage-cron-upload
aliyun ossutil ls "oss://BucketName/TargetOssPrefix" --region "RegionId" \
--read-timeout 60 --connect-timeout 30 \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-oss-manage-cron-upload
```
Expected behavior:
- the active profile is valid
- bucket inventory succeeds without `AccessDenied`
- prefix listing succeeds after the first upload test
- the documented minimum action set still matches `oss:ListBuckets`, `oss:GetBucketInfo`, `oss:PutObject`, `oss:GetObject`, and `oss:ListObjects`; if a draft answer swaps in `oss:AbortMultipartUpload` as part of the default minimum set, treat that as drift from this skill
FILE:references/related-apis.md
# Related APIs and CLI Commands
## Command Summary
| Surface | Command | Purpose | Validation Status |
| --- | --- | --- | --- |
| `aliyun` CLI | `aliyun version` | Verify CLI availability and version | Not validated locally because `aliyun` was not installed in this repository |
| `aliyun` CLI | `aliyun configure set --auto-plugin-install true` | Enable plugin auto-install | Not validated locally because `aliyun` was not installed in this repository |
| `aliyun` CLI | `aliyun configure ai-mode enable` | Enable AI safety mode to block dangerous operations | Not validated locally because `aliyun` was not installed in this repository |
| `aliyun` CLI | `aliyun configure ai-mode disable` | Disable AI safety mode after task completion | Not validated locally because `aliyun` was not installed in this repository |
| `aliyun` CLI | `aliyun configure list` | Verify credential profile state safely | Not validated locally because `aliyun` was not installed in this repository |
| `aliyun` CLI | `aliyun oss --help` | Discover OSS product command surface | Not validated locally because `aliyun` was not installed in this repository |
| `aliyun` CLI | `aliyun ossutil --help` | Discover integrated ossutil command surface | Not validated locally because `aliyun` was not installed in this repository |
| `aliyun` CLI | `aliyun ossutil api list-buckets --output-format json --read-timeout 60 --connect-timeout 30 --user-agent AlibabaCloud-Agent-Skills` | Enumerate buckets for prerequisite verification | Not validated locally because `aliyun` was not installed in this repository |
| `aliyun` CLI | `aliyun ossutil stat "oss://BucketName" --region "RegionId" --output-format json --read-timeout 60 --connect-timeout 30 --user-agent AlibabaCloud-Agent-Skills` | Verify bucket metadata and region | Not validated locally because `aliyun` was not installed in this repository |
| `aliyun` CLI | `aliyun ossutil cp --help` | Verify the integrated upload command surface | Not validated locally because `aliyun` was not installed in this repository |
| `aliyun` CLI | `aliyun ossutil cp "LocalSourcePath" "oss://BucketName/TargetOssPrefix" -r -u --max-age "MaxAge" --region "RegionId" --read-timeout 300 --connect-timeout 30 --user-agent AlibabaCloud-Agent-Skills` | Canonical incremental upload command via integrated ossutil | Not validated locally because `aliyun` was not installed in this repository, and not executed against a live bucket here |
| `aliyun` CLI | `aliyun ossutil ls "oss://BucketName/TargetOssPrefix" --region "RegionId" --read-timeout 60 --connect-timeout 30 --user-agent AlibabaCloud-Agent-Skills` | Verify uploaded objects under the target prefix | Not validated locally because `aliyun` was not installed in this repository, and not executed against a live bucket here |
| `aliyun` CLI | `aliyun ossutil rm "oss://BucketName/TargetOssPrefixtest-object.txt" --region "RegionId" --read-timeout 60 --connect-timeout 30 --user-agent AlibabaCloud-Agent-Skills` | Optional cleanup for test artifacts | Not validated locally because `aliyun` was not installed in this repository |
| Local OS | `crontab -l` | Verify cron registration on Linux/macOS | Validated locally |
| Local OS | `schtasks /Query /TN "OSS Scheduled Sync" /V /FO LIST` | Verify Task Scheduler registration on Windows | Not validated locally in this macOS repository |
## OSS Capability Notes
These notes explain which OSS-side capability each `aliyun ossutil` command relies on. They are documentation-only reference data for the skill package, not `eval` assertion fields, and do not mean the user-facing answer must present OpenAPI or POP gateway actions.
| Command | Related OSS capability | Notes |
| --- | --- | --- |
| `aliyun ossutil api list-buckets --output-format json` | Service-level bucket inventory | Used to confirm the bucket exists in the current account |
| `aliyun ossutil stat "oss://BucketName" --region ... --output-format json` | Bucket metadata lookup | Used to verify bucket metadata and region |
| `aliyun ossutil cp ... -r -u --max-age ... --region ...` | Object upload plus object comparison/listing for incremental behavior | Official scenario command through integrated `aliyun ossutil`; permissions align with object upload, read, and list needs |
| `aliyun ossutil ls "oss://BucketName/TargetOssPrefix" --region ...` | Object listing under the target prefix | Post-upload verification under the target prefix |
| `aliyun ossutil rm "oss://BucketName/TargetOssPrefixtest-object.txt" --region ...` | Object deletion | Optional cleanup for test artifacts only |
## RAM/IAM Notes
This skill references RAM policies for least-privilege guidance, but the default scenario does not require a validated `aliyun ram ...` command.
What is in scope:
- documenting the least-privilege policy actions needed for upload and verification
- attaching that policy through the user's existing IAM workflow or the RAM Console
What is out of scope for the default flow:
- inventing unvalidated `aliyun ram` automation commands in this repository
- assuming the operator wants policy creation or attachment automated
## Capability Split
| Task | Preferred Surface | Reason |
| --- | --- | --- |
| CLI installation checks | `aliyun` | Matches the creator skill contract and supports `--user-agent` tagging |
| Credential gate | `aliyun configure list` | Required by the creator skill contract |
| OSS-side bucket verification | `aliyun ossutil` | Best fit for CLI-first OSS verification where supported |
| Scheduled upload job | `aliyun ossutil` | Keeps the official `ossutil cp` workflow on the required `aliyun` CLI surface |
| Scheduler registration | Local OS tools | Cron and Task Scheduler are host-level, not Alibaba Cloud APIs |
| Visual bucket inspection | OSS Console | Optional manual verification |
## Important Limitations
1. The data-plane sync uses the integrated `aliyun ossutil` surface, but it still runs from the local host and is not an OSS-side scheduled service.
2. Bucket creation should follow the existing creation flow documented by this skill, while upload and verification stay on the integrated `aliyun ossutil` surface.
3. Scheduler configuration is OS-local and must be labeled separately from Alibaba Cloud CLI steps.
4. Any direct RAM API automation must be treated as optional follow-up work, not part of the default validated path.
5. Local authoring validation in this repository did not include a live upload or live object listing against a real OSS bucket.
6. Answers should not fill prerequisite gaps by inventing extra scripts, fake logs, sample local payloads, or standalone `ossutil` installation/configuration detours.
FILE:references/verification-method.md
# Verification Method for OSS Scheduled Local Sync
## Scope
This checklist verifies the CLI prerequisites, the OSS upload path, and the local scheduler.
## Pre-Execution Verification
Run the canonical preflight block from `SKILL.md` Step 1 and Step 2 before live execution.
Minimum checks:
```bash
aliyun version
aliyun configure list
aliyun configure ai-mode enable
```
Success criteria:
- `aliyun` version is `>= 3.3.3`.
- At least one valid profile is present.
- AI safety mode is enabled (dangerous operations will be blocked).
- No credentials are echoed manually.
- No separate standalone `ossutil` installation is required for this skill.
- The workflow does not drift into `ossutil config`, `brew install ossutil`, `aliyun ossutil sync`, or simulated local test-data creation.
## Bucket Prerequisite Verification
If the bucket is expected to exist already:
```bash
aliyun ossutil api list-buckets --output-format json \
--read-timeout 60 --connect-timeout 30 \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-oss-manage-cron-upload
aliyun ossutil stat "oss://BucketName" --region "RegionId" --output-format json \
--read-timeout 60 --connect-timeout 30 \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-oss-manage-cron-upload
```
Verify that:
- `BucketName` appears in the bucket inventory.
- the returned region matches `RegionId`.
- the active profile can read bucket metadata.
- `--region "RegionId"` is included when the CLI profile's default region differs from the target bucket's region.
If the bucket does not exist:
- create the bucket first before configuring scheduled upload
- follow the existing bucket-creation flow documented by this skill
- re-run `aliyun ossutil stat "oss://BucketName" --region "RegionId" --output-format json --read-timeout 60 --connect-timeout 30 --user-agent AlibabaCloud-Agent-Skills/alibabacloud-oss-manage-cron-upload` to confirm the bucket now exists
- do not generate fake upload logs, demo local payloads, placeholder batch/shell wrappers, or pretend success outputs to make the answer look complete
If the bucket already exists:
- continue with the confirmed existing bucket after `aliyun ossutil stat` succeeds
- optionally remind the user that a versioning-enabled bucket can be better for backup rollback safety when such a choice already exists
- do not block the workflow just because the confirmed existing bucket is not versioned
## Upload Verification
### 1. Run the canonical incremental upload once
```bash
aliyun ossutil cp "LocalSourcePath" "oss://BucketName/TargetOssPrefix" \
-r -u \
--max-age "MaxAge" \
--region "RegionId" \
--read-timeout 300 --connect-timeout 30 \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-oss-manage-cron-upload
```
Verify that:
- the command uses `cp`, not `sync`
- the canonical flags `-r -u --max-age` are present together
- `-u` is explained correctly: upload only when the target object is missing or the local source file is newer than the existing OSS object
- if `-f` is mentioned, it is framed only as an optional flag for explicitly requested non-interactive unattended runs such as cron, Task Scheduler, or CI
- `--region "RegionId"` is used to set both the endpoint and signing region correctly (using `--endpoint` alone without `--region` will fail with "Invalid signing region" when the CLI profile region differs from the target bucket region)
- `TargetOssPrefix` is normalized as a bucket-relative path without a leading `/` before the command is run
- the answer does not silently replace this command with a separate standalone `ossutil` install, `ossutil config` credential setup, `aliyun ossutil sync`, `Cache-Control:max-age=...` metadata mapping, or placeholder-only local filtering scripts
### 1.1 Verify the `-u` incremental behavior
After the first successful upload, verify the incremental semantics explicitly:
- re-run the same `aliyun ossutil cp ... -r -u --max-age ... --region ...` command without modifying local files and confirm unchanged files are not uploaded again
- update the last-modified time of one local source file, then re-run the same command and confirm only that newer file is uploaded
### 2. Verify uploaded objects
```bash
aliyun ossutil ls "oss://BucketName/TargetOssPrefix" --region "RegionId" \
--read-timeout 60 --connect-timeout 30 \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-oss-manage-cron-upload
```
Verify that:
- expected objects appear under the confirmed prefix
- the object path is correct and not duplicated accidentally
- the prefix does not begin with `/`
- the command succeeds without `AccessDenied`, endpoint-format, or signing-region errors
## Scheduler Verification
### Linux/macOS cron
```bash
crontab -l
```
Verify that:
- the expected cron line is present
- the script path matches the deployed script
- the schedule matches the confirmed `Schedule` value
- the answer did not silently switch the documented macOS path to `launchd` when the skill flow or user request called for `cron`
### Windows Task Scheduler
Verify one of the following:
- `schtasks /Query /TN "OSS Scheduled Sync" /V /FO LIST`
- Task Scheduler UI shows the task and last-run status
- Task Scheduler History records successful launches after the task is enabled
## Manual OSS Console Verification
Use this only when the user wants a visual check.
Manual steps:
1. Open the OSS Console.
2. Open `BucketName`.
3. Browse to `TargetOssPrefix`.
4. Confirm that the expected objects and timestamps are visible.
Label this verification clearly as manual.
## Failure Verification
The workflow should stop clearly in these cases:
1. `aliyun` is not installed.
2. the `aliyun ossutil` command surface is unavailable.
3. `aliyun configure list` does not show a valid profile.
4. bucket creation fails or the active identity lacks bucket-creation permissions.
5. `AccessDenied` indicates missing bucket-list, bucket-management, or upload permissions.
6. the endpoint was built incorrectly (for example by adding `https://`), or `--endpoint` was used without `--region` causing a signing-region mismatch.
7. the scheduler entry is missing after configuration.
8. the answer falls back to standalone `ossutil`, `ossutil config`, `aliyun ossutil sync`, or fake local test-data creation instead of reporting the real blocker.
## Validation Status for This Repository
This repository was generated in an environment where `aliyun` was not installed, so local `aliyun ... --help` and `aliyun ossutil ...` validation could not be completed here. The real upload and listing commands also were not executed against a live bucket in this repository.
What was validated locally in this repository:
- the documentation consistently keeps the upload and listing flow on `aliyun ossutil`
- the canonical flag combination (`-r -u --max-age --region`) remains consistent across the skill files
- `crontab -l` behavior when no user crontab exists
Re-run all `aliyun` verification commands on the target machine before live execution, and run the real `aliyun ossutil cp` and `aliyun ossutil ls` commands against the target bucket before treating the workflow as production-ready.
Alicloud Service Scenario-Based Skill. Use for diagnosing local-to-OSS network state, upload/download bandwidth, download time, and local symlink issues with...
---
name: alibabacloud-oss-manage-network-probe
description: |
Alicloud Service Scenario-Based Skill. Use for diagnosing local-to-OSS network state,
upload/download bandwidth, download time, and local symlink issues with `aliyun ossutil probe`.
Triggers: "aliyun ossutil probe", "OSS 网络探测", "OSS 带宽探测", "OSS 下载时间探测", "OSS 软链接探测".
---
# Detailed description of the scenario's application and purpose.
Diagnose network connectivity, upload/download bandwidth, download time, and local symlink anomalies between the local workstation and OSS using `ossutil 2.0` integrated with the Alibaba Cloud CLI.
**Architecture**: Local Workstation + Alibaba Cloud CLI 3.3.3+ + `aliyun ossutil` + OSS Bucket + Optional target object or presigned URL + Optional probe domain
| Scenario | Recommended Command | Output |
| --- | --- | --- |
| Upload connectivity probe | `aliyun ... ossutil probe --upload` | Upload duration, object name, log file |
| Download connectivity probe | `aliyun ... ossutil probe --download` | Download duration, local file path, log file |
| Upload bandwidth suggestion | `aliyun ... ossutil probe --probe-item upload-speed` | Suggested concurrency value |
| Download bandwidth suggestion | `aliyun ... ossutil probe --probe-item download-speed` | Suggested concurrency value |
| Download time measurement | `aliyun ... ossutil probe --probe-item download-time` | Concurrency/part-size/duration statistics |
| Symlink anomaly check | `aliyun ... ossutil probe --probe-item cycle-symlink` | Whether abnormal symlinks exist |
> **Important implementation boundary**
> - `probe` is a composite client-side diagnostic command provided by `aliyun ossutil`; there is no equivalent `aliyun oss api probe`.
> - `cycle-symlink` can only detect abnormal symlinks — it cannot safely auto-fix target paths.
> - Probe output can locate symptoms and suggest concurrency, but cannot guarantee an automatic precise root cause for all network anomalies.
> - `download-speed` requires a real existing object, and the official recommendation is objects larger than 5 MiB. If no suitable object exists, the user must first confirm an existing object path, or confirm a local file to upload via `aliyun ossutil cp` before probing.
## Installation
> **Pre-check: Aliyun CLI >= 3.3.3 required**
> Run `aliyun version` to verify >= 3.3.3. If not installed or version too low,
> see `references/cli-installation-guide.md` for installation instructions.
> Then run the credential gate `aliyun configure list`.
> **Only after `configure list` shows a valid profile**, run `aliyun configure set --auto-plugin-install true` and `aliyun ossutil version`.
Run the version and credential gate first:
```bash
aliyun version
aliyun configure list
```
Only after `configure list` confirms a valid profile, proceed:
```bash
aliyun configure set --auto-plugin-install true
aliyun configure ai-mode enable
aliyun configure ai-mode set-user-agent --user-agent "AlibabaCloud-Agent-Skills/alibabacloud-oss-manage-network-probe"
aliyun ossutil version
aliyun plugin update
```
> **AI safety mode**: `configure ai-mode enable` activates the CLI's built-in safety guard, which blocks dangerous operations (e.g. deleting critical resources) at the CLI level. This must be enabled before executing any ossutil commands.
**[MUST] CLI User-Agent** — Every `aliyun` CLI command invocation must include:
`--user-agent AlibabaCloud-Agent-Skills/alibabacloud-oss-manage-network-probe`
## Environment Variables
| Environment Variable | Required/Optional | Description | Default Value |
| --- | --- | --- | --- |
| `ALIBABA_CLOUD_PROFILE` | Optional | Specify which CLI profile to use | Current default profile |
| `HTTP_PROXY` | Optional | HTTP proxy address in proxied environments | None |
| `HTTPS_PROXY` | Optional | HTTPS proxy address in proxied environments | None |
| `NO_PROXY` | Optional | Proxy bypass list | None |
## Parameter Confirmation
> **IMPORTANT: Parameter Confirmation** — Before executing any command or API call,
> ALL user-customizable parameters (e.g., RegionId, instance names, CIDR blocks,
> passwords, domain names, resource specifications, etc.) MUST be confirmed with the
> user. Do NOT assume or use default values without explicit user approval.
| Parameter Name | Required/Optional | Description | Default Value |
| --- | --- | --- | --- |
| `profile` | Optional | CLI profile to use | Current default profile |
| `region_id` | Optional | Region where the bucket is located; use when auto-detection is unreliable or explicit specification is needed | None |
| `bucket_name` | Required for bucket-based probes | Target bucket name | None |
| `object_name` | Required for `download-speed` and `download-time`; optional for other bucket-based probes | Full object path, e.g. `dir/example.txt`; for `download-speed`, objects larger than 5 MiB are recommended for stable results | None |
| `local_path` | Optional | Local upload file path, symlink scan directory, or download save path | None |
| `download_url` | Required for URL-based download probe | Public-read URL or signed private URL | None |
| `endpoint` | Optional | Use only when the user explicitly provides it or the error message clearly points to a specific endpoint | None |
| `addr` | Optional | Domain for `--addr` network connectivity check | `www.aliyun.com` only if user explicitly accepts |
| `upmode` | Optional | Upload probe mode | `normal` |
| `runtime` | Optional | Max runtime in seconds for `upload-speed` / `download-speed` | CLI default |
| `parallel` | Optional | Single-file concurrency for `download-time` | `1` |
| `part_size` | Optional | Part size in bytes for `download-time` | CLI auto/default |
## Authentication
> **Pre-check: Alibaba Cloud Credentials Required**
>
> **Security Rules:**
> - **NEVER** read, echo, or print AK/SK values (e.g., `echo $ALIBABA_CLOUD_ACCESS_KEY_ID` is FORBIDDEN)
> - **NEVER** ask the user to input AK/SK directly in the conversation or command line
> - **NEVER** use `aliyun configure set` with literal credential values
> - **NEVER** read credential files such as `~/.aliyun/config.json`, or dump environment variables to inspect credentials
> - **NEVER** write a full presigned URL with query-string signature parameters into logs or final output; if you must mention it, redact everything after `?`
> - **ONLY** use `aliyun configure list` to check credential status
>
> ```bash
> aliyun configure list
> ```
> Check the output for a valid profile (AK, STS, or OAuth identity).
>
> **If no valid profile exists, STOP here.**
> 1. Obtain credentials from [Alibaba Cloud Console](https://ram.console.aliyun.com/manage/ak)
> 2. Configure credentials **outside of this session** (via `aliyun configure` in terminal or environment variables in shell profile)
> 3. Return and re-run after `aliyun configure list` shows a valid profile
If multiple profiles exist, explicitly add `--profile <profile>` in subsequent commands, placed after `aliyun` and before `ossutil`, e.g. `aliyun --profile <profile> ossutil version`.
## RAM Policy
The minimum OSS permissions required by this skill depend on the probe mode. Refer to `references/ram-polices.md` for per-scenario permission tables and policy examples.
- Upload probes, upload bandwidth probes, temporary object probes: require at least `oss:GetObject`, `oss:PutObject`, `oss:DeleteObject`
- Download probes, download bandwidth probes, download time probes: require at least `oss:GetObject`
- If using `aliyun ossutil cp` to pre-upload a test object: requires `oss:PutObject`
- If using `aliyun ossutil rm` to clean up an explicitly specified test object: requires `oss:DeleteObject`
## Core Workflow
### 1. Validate the CLI environment
Execute in the following order — do not skip steps:
1. Check CLI version first:
```bash
aliyun version
```
2. Then check credentials/profile:
```bash
aliyun configure list
```
3. **If `configure list` does not show a valid profile, or reports a missing config file, STOP immediately.**
- Do NOT proceed with `configure set --auto-plugin-install true`
- Do NOT proceed with `ossutil version`
- Do NOT fabricate bucket, object, profile, region, or probe success results
4. Only after the profile is valid, proceed to prepare the plugin, enable AI safety mode, and verify `ossutil`:
```bash
aliyun configure set --auto-plugin-install true
aliyun configure ai-mode enable
aliyun configure ai-mode set-user-agent --user-agent "AlibabaCloud-Agent-Skills/alibabacloud-oss-manage-network-probe"
aliyun ossutil version
```
### 1.1 Log file naming and command substitution
- When saving execution logs, use static strings for filenames (e.g. `probe_download_time.log`). **Do not use `$(date ...)`, `$(...)`, or backtick shell command substitutions in filenames**, because different execution environments have inconsistent shell interpolation support, which can easily cause syntax errors.
- Some execution environments block `$()` command substitution entirely. When you need to capture command output into a variable (e.g. for presigned URLs), **use the file+script pattern**: redirect output to a temporary file, then create a shell script that reads the file and uses the value. See §B for a concrete example.
### 2. Choose the probe mode
#### A. Upload connectivity probe
- If the user only wants network/upload connectivity diagnostics without keeping the object, omit `local_path` and `object_name` and let `probe` use a temporary file that is auto-cleaned after completion.
- If the user wants to verify a specific real file's upload path, confirm `local_path`.
- If the upload probe returns `AccessDenied`, quote the error as-is and explain that at least `oss:GetObject`, `oss:PutObject`, `oss:DeleteObject` are required; do not enumerate buckets, regions, or fall back to legacy command forms.
```bash
aliyun ossutil probe \
--upload "<LOCAL_PATH_IF_ANY>" \
--bucket "<BUCKET_NAME>" \
--object "<OBJECT_NAME_IF_USER_WANTS_TO_KEEP_IT>" \
--addr "<ADDR_IF_CONFIRMED>" \
--upmode "<UPMODE_IF_CONFIRMED>" \
--region "<REGION_ID_IF_NEEDED>" \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-oss-manage-network-probe
```
When `LOCAL_PATH_IF_ANY` is not provided, remove that positional parameter entirely — do not pass an empty string.
#### B. Download probe via URL
- Public-read objects: have the user confirm a directly accessible URL.
- Private objects: generate a presigned URL first, then run `probe --download --url`.
Generate a presigned URL, save it to a temporary file, then run the probe via a shell script. This two-step approach avoids exposing the full URL in command history and works in environments where `$()` command substitution is blocked.
**Step 1** — Generate the presigned URL and redirect output to a temporary file:
```bash
aliyun ossutil presign \
"oss://<BUCKET_NAME>/<OBJECT_NAME>" \
--expires-duration 1h \
--region "<REGION_ID_IF_NEEDED>" \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-oss-manage-network-probe > /tmp/_presign_url.txt
```
**Step 2** — Create a probe script that reads the URL from the file and runs the download probe:
```bash
cat > /tmp/_run_presign_probe.sh << 'PROBE_SCRIPT'
#!/bin/bash
PRESIGN_URL=$(cat /tmp/_presign_url.txt)
aliyun ossutil probe \
--download \
--url "$PRESIGN_URL" \
"<LOCAL_PATH_IF_USER_WANTS_TO_RENAME>" \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-oss-manage-network-probe
PROBE_SCRIPT
bash /tmp/_run_presign_probe.sh
```
> **Important — you MUST use `probe --download --url` with the presigned URL**:
> - **Never** copy-paste the full presigned URL directly into the `--url` parameter — use the file+script pattern above so the URL is never exposed in command history or execution logs.
> - If `/tmp/` is not writable, use the current workspace directory for the temporary file and script instead.
`--url` only accepts HTTP/HTTPS URLs — it cannot take `oss://bucket/object`.
- A successful `ossutil presign` only means the signed URL was generated; it does not guarantee the bucket or object exists, nor that the subsequent download will succeed.
- If you need to log the execution, do not persist the full presigned URL; at most keep the object address without the query string, or redact all signature parameters after `?`.
- If `probe --download --url` returns 404/403, quote the raw HTTP error first; if the bucket/object was already confirmed input, you may do one `ossutil stat` validation with the same `bucket + object + region`. Do not try to "guess" the root cause by listing buckets, trying random regions, or reading local credential files.
#### C. Download probe via Bucket/Object
- If the user confirmed `object_name`, the command will download that object directly.
- If the user does not provide `object_name`, `probe` will create a temporary object, download it, and delete the temporary object after completion.
```bash
aliyun ossutil probe \
--download \
--bucket "<BUCKET_NAME>" \
--object "<OBJECT_NAME_IF_ANY>" \
--addr "<ADDR_IF_CONFIRMED>" \
"<LOCAL_PATH_IF_USER_WANTS_TO_RENAME>" \
--region "<REGION_ID_IF_NEEDED>" \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-oss-manage-network-probe
```
- If the command reports `NoSuchBucket`, `NoSuchKey`, or other object-level errors, prefer running `ossutil stat "oss://<BUCKET_NAME>/<OBJECT_NAME>" --region "<REGION_ID_IF_NEEDED>"` for same-target validation.
- Do not list all buckets, try unconfirmed regions, or switch to `aliyun oss api` / `GetBucketLocation` or other commands outside this skill's scope to confirm whether the object exists.
#### D. Local symlink anomaly probe
This mode only checks local directory/file paths — it does not access OSS.
```bash
aliyun ossutil probe \
--probe-item cycle-symlink \
"<LOCAL_DIRECTORY_OR_FILE>" \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-oss-manage-network-probe
```
- If the command returns `stat <path>: no such file or directory`, explicitly state that the local path does not exist in the current execution environment; this is still a local-only flow with no OSS access.
- **When the local path does not exist, you must NEVER**:
- Interpret it as "this is a containerized/sandbox environment limitation"
- Automatically rewrite it as "the user should run on another machine/production environment"
- Generate a script file saying "run this command in the correct environment"
- Check the parent directory with `ls` and then give up
**Correct approach**: Quote the raw error `stat <path>: no such file or directory`, explicitly tell the user the path does not exist in the current environment, and ask whether they provided the correct path. Unless the user proactively states the current session is not on the target machine, do not make that judgment for them.
When reporting results of this probe, include at minimum:
- This is a local-only flow — no OSS access occurred
- Which symlinks are abnormal and which link chains were **directly verified**; if only partial chains can be verified, clearly distinguish "confirmed chain segments" from "anomaly points proven by probe errors", e.g. `loop-b -> loop-a`, and resolving `loop-a` reports `too many levels of symbolic links`
- If the probe output contains raw errors, quote at least one key error, e.g. `too many levels of symbolic links`
- Minimum fix prerequisites, e.g. break one of the cyclic links or re-point the abnormal link to a real target before retrying
If you need to clarify the abnormal link chain, you may perform read-only local forensics on the same path (e.g. `readlink`, `stat -f "%N -> %Y"`). Only write precise chains when these supplementary results are actually readable; if the supplementary forensics itself fails, report only verified segments — do not fabricate a complete cycle.
If the output lists abnormal symlinks, the user or a local script must fix them according to business semantics; this skill does not auto-rewrite symlink targets.
#### E. Upload bandwidth probe with suggested concurrency
Basic command:
```bash
aliyun ossutil probe \
--probe-item upload-speed \
--bucket "<BUCKET_NAME>" \
--region "<REGION_ID_IF_NEEDED>" \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-oss-manage-network-probe
```
To limit runtime, add:
```bash
aliyun ossutil probe \
--probe-item upload-speed \
--bucket "<BUCKET_NAME>" \
--runtime "<RUNTIME_IF_CONFIRMED>" \
--region "<REGION_ID_IF_NEEDED>" \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-oss-manage-network-probe
```
Successful output will contain `suggest parallel is <N>`.
#### F. Download bandwidth probe with suggested concurrency
- `object_name` is required.
- Official recommendation: target object should be larger than 5 MiB.
- If the user has no suitable object, first confirm a local file path, then upload a cleanable test object via `aliyun ossutil cp`.
Optional preparation step:
```bash
aliyun ossutil cp \
"<LOCAL_FILE_TO_UPLOAD>" \
"oss://<BUCKET_NAME>/<OBJECT_NAME>" \
--region "<REGION_ID_IF_NEEDED>" \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-oss-manage-network-probe
```
Run download bandwidth probe:
```bash
aliyun ossutil probe \
--probe-item download-speed \
--bucket "<BUCKET_NAME>" \
--object "<OBJECT_NAME>" \
--runtime "<RUNTIME_IF_CONFIRMED>" \
--region "<REGION_ID_IF_NEEDED>" \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-oss-manage-network-probe
```
#### G. Download time probe
Basic command:
```bash
aliyun ossutil probe \
--probe-item download-time \
--bucket "<BUCKET_NAME>" \
--object "<OBJECT_NAME>" \
--region "<REGION_ID_IF_NEEDED>" \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-oss-manage-network-probe
```
To explicitly control concurrency and part size, add:
```bash
aliyun ossutil probe \
--probe-item download-time \
--bucket "<BUCKET_NAME>" \
--object "<OBJECT_NAME>" \
--parallel "<PARALLEL_IF_CONFIRMED>" \
--part-size "<PART_SIZE_IF_CONFIRMED>" \
--region "<REGION_ID_IF_NEEDED>" \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-oss-manage-network-probe
```
`--parallel` and `--part-size` are only meaningful in the `download-time` scenario; do not misuse them with `upload-speed`.
### 3. Interpret the output
- When upload/download probes succeed, the output will contain `upload file:success` or `download file:success`
- When bandwidth probes succeed, the output will contain multiple `parallel:<N>` statistics and `suggest parallel is <N>`
- When download time probes succeed, the output will contain `total bytes`, `cost`, `avg speed`
- All probe modes typically generate a `logOssProbe*.log` local log file; **after probe execution, you must check whether `logOssProbe*.log` was generated in the current directory** and report the log path in the final answer
- If a real command returns an error or has no success marker, the final conclusion must **explicitly state failure/blocked and quote the raw error message** — do not write "task completed successfully" or describe a failure as successful verification
- When a command fails, the final answer must explicitly state the **termination reason** (e.g. "stopped due to AccessDenied", "stopped due to path not found") — do not end silently
- For errors like `The bucket you are attempting to access must be addressed using the specified endpoint`, this only means the current access endpoint does not match the bucket's requirements; **stop immediately**, ask the user to confirm the correct region/endpoint — do not infer or try other region/endpoints on your own
See `references/verification-method.md` for more detailed verification steps.
## Success Verification Method
Follow the steps in `references/verification-method.md` to confirm each item:
1. CLI version and profile are valid
2. Probe output contains success markers or suggested concurrency
3. **You must run `ls logOssProbe*.log` to check whether log files were generated locally**, and report the log path in the final answer; if no log files were generated, it means the probe may not have reached the actual probing stage
4. If an explicit test object was used, confirm whether it should be retained or enter the cleanup step
5. If any of the above steps fail, the final answer must explicitly state **failure** and quote the raw error with termination reason
## Cleanup
- Upload/download connectivity probes without an explicit `--object` will auto-clean temporary objects
- If you explicitly uploaded a test object in the `download-speed` preparation step, decide whether to delete it based on user confirmation after probing
Delete an OSS test object:
```bash
aliyun ossutil rm \
"oss://<BUCKET_NAME>/<OBJECT_NAME>" \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-oss-manage-network-probe
```
If a temporary test file was downloaded locally, it should also be deleted or retained based on user confirmation.
After all probe and cleanup steps are finished, disable AI safety mode:
```bash
aliyun configure ai-mode disable
```
## API and Command Tables
For all commands, underlying OSS capability mappings, and which steps are local client-side logic only, see `references/related-apis.md`.
## Best Practices
1. Always use `aliyun ossutil probe` — do not fabricate non-existent commands like `aliyun oss api probe`
2. Confirm all user-variable parameters before execution, especially `bucket_name`, `object_name`, `download_url`, `local_path`
3. Only retain probe objects when the user explicitly confirms; otherwise prefer temporary objects or explicit cleanup
4. For `download-speed`, choose a real object larger than 5 MiB for more stable results
5. In proxy, dedicated line, or custom domain scenarios, explicitly confirm `--addr`, `--region`, `--endpoint`
6. Use `suggest parallel is <N>` as an empirical baseline, then do small-scale validation combined with actual business concurrency
7. For `cycle-symlink`, only diagnose — do not auto-fix
8. After command failure, prefer same-target validation (e.g. `ossutil stat`) — do not expand into listing buckets, guessing regions, trying unsupported flags, or reading local credential files
9. Do not expose AK/SK, STS tokens, or full presigned URL query strings in logs or final results
10. A successful presign, resolvable DNS, or reachable ping/traceroute does not guarantee the object exists or that the probe will succeed; conclusions must be based on actual probe/validation results
## Reference Links
| Reference | Purpose |
| --- | --- |
| `references/cli-installation-guide.md` | Installing and upgrading Aliyun CLI |
| `references/verification-method.md` | Checking success by probe mode |
| `references/related-apis.md` | Command to underlying OSS capability/permission mapping |
| `references/ram-polices.md` | RAM permission checklist and policy examples |
| `references/acceptance-criteria.md` | Skill acceptance criteria and counter-examples |
| `references/implementation-boundaries.md` | Boundaries that cannot be fully automated via CLI or code |
FILE:references/acceptance-criteria.md
# Acceptance Criteria: alibabacloud-oss-manage-network-probe
**Scenario**: `Use aliyun ossutil probe to diagnose OSS network state, bandwidth, download time, and symlink issues`
**Purpose**: Skill testing acceptance criteria
---
# Correct CLI Command Patterns
## 1. Product and command structure
#### CORRECT
```bash
aliyun ossutil probe --help --user-agent AlibabaCloud-Agent-Skills
aliyun ossutil version
aliyun configure list
```
Why correct:
- Uses `aliyun` plugin-mode command structure
- Uses integrated `ossutil 2.0` entrypoint
- Includes the required `--user-agent AlibabaCloud-Agent-Skills`
#### INCORRECT
```bash
aliyun oss Probe
aliyun oss api probe
oss probe --bucket examplebucket
```
Why incorrect:
- `Probe` is not the supported command form
- `probe` is not an `aliyun oss api` OpenAPI action
- `oss` is the old command family; this skill targets `aliyun ossutil`
## 2. Credential and CLI pre-check
#### CORRECT
```bash
aliyun version
aliyun configure list
aliyun configure set --auto-plugin-install true
aliyun configure ai-mode enable
```
Why correct:
- Verifies CLI version
- Checks local profile validity without printing secrets
- Enables auto plugin install using a supported CLI flag
- Enables AI safety mode to block dangerous operations
#### INCORRECT
```bash
echo $ALIBABA_CLOUD_ACCESS_KEY_ID
aliyun configure set --access-key-id <ak> --access-key-secret <sk>
cat ~/.aliyun/config.json
```
Why incorrect:
- Exposes or handles secrets directly
- Violates the credential safety gate for this skill
#### ALSO INCORRECT
```bash
aliyun configure list --output json --user-agent AlibabaCloud-Agent-Skills
printenv | grep ALIBABA_CLOUD
```
Why incorrect:
- `configure list --output json` is not a valid command pattern for this skill's documented workflow
- Dumping environment variables to inspect credentials is treated as secret handling
## 3. Upload probe patterns
#### CORRECT
```bash
aliyun ossutil probe \
--upload \
--bucket "examplebucket" --user-agent AlibabaCloud-Agent-Skills
```
```bash
aliyun ossutil probe \
--upload \
"/tmp/test.bin" \
--bucket "examplebucket" \
--upmode multipart --user-agent AlibabaCloud-Agent-Skills
```
Why correct:
- `--upload` is present
- `--bucket` is provided
- Optional local file path is passed as a positional argument
- `--upmode` uses a documented enum value
#### INCORRECT
```bash
aliyun ossutil probe --upload --object test.bin --user-agent AlibabaCloud-Agent-Skills
aliyun ossutil probe --upload --bucket examplebucket --upmode parallel --user-agent AlibabaCloud-Agent-Skills
```
Why incorrect:
- Upload probe requires `--bucket`
- `parallel` is not a valid `--upmode` value; valid values are `normal`, `append`, `multipart`
## 4. Download probe patterns
#### CORRECT
```bash
aliyun ossutil probe \
--download \
--bucket "examplebucket" \
--object "dir/example.txt" --user-agent AlibabaCloud-Agent-Skills
```
```bash
aliyun ossutil probe \
--download \
--url "https://examplebucket.oss-cn-hangzhou.aliyuncs.com/example.txt" --user-agent AlibabaCloud-Agent-Skills
```
Why correct:
- Uses one of the two documented download modes
- URL mode supplies an HTTP/HTTPS URL
- Bucket mode uses bucket/object parameters correctly
#### INCORRECT
```bash
aliyun ossutil probe --download --url "oss://examplebucket/example.txt" --user-agent AlibabaCloud-Agent-Skills
aliyun ossutil probe --download --object "dir/example.txt" --user-agent AlibabaCloud-Agent-Skills
```
Why incorrect:
- `--url` does not accept `oss://` URIs
- Bucket-based download probe needs `--bucket`
## 5. Probe-item patterns
#### CORRECT
```bash
aliyun ossutil probe --probe-item cycle-symlink "/data/links" --user-agent AlibabaCloud-Agent-Skills
aliyun ossutil probe --probe-item upload-speed --bucket "examplebucket" --user-agent AlibabaCloud-Agent-Skills
aliyun ossutil probe --probe-item download-speed --bucket "examplebucket" --object "big/test.bin" --user-agent AlibabaCloud-Agent-Skills
aliyun ossutil probe --probe-item download-time --bucket "examplebucket" --object "big/test.bin" --parallel 3 --part-size 10000000 --user-agent AlibabaCloud-Agent-Skills
```
Why correct:
- `cycle-symlink`, `upload-speed`, `download-speed`, `download-time` are documented valid values
- `download-speed` and `download-time` provide bucket and object
- `--parallel` and `--part-size` are used on `download-time`
#### INCORRECT
```bash
aliyun ossutil probe --probe-item symlink-check "/data/links" --user-agent AlibabaCloud-Agent-Skills
aliyun ossutil probe --probe-item download-speed --bucket "examplebucket" --user-agent AlibabaCloud-Agent-Skills
aliyun ossutil probe --probe-item upload-speed --bucket "examplebucket" --parallel 3 --user-agent AlibabaCloud-Agent-Skills
```
Why incorrect:
- `symlink-check` is not a valid enum value
- `download-speed` requires `--object`
- `--parallel` is only meaningful for `download-time` in this documented workflow
## 6. Supporting command patterns
#### CORRECT
```bash
aliyun ossutil stat "oss://examplebucket/big/test.bin" --user-agent AlibabaCloud-Agent-Skills
aliyun ossutil presign "oss://examplebucket/private/test.bin" --expires-duration 1h --user-agent AlibabaCloud-Agent-Skills
aliyun ossutil cp "/tmp/test.bin" "oss://examplebucket/probe/test.bin" --user-agent AlibabaCloud-Agent-Skills
aliyun ossutil rm "oss://examplebucket/probe/test.bin" --user-agent AlibabaCloud-Agent-Skills
```
Why correct:
- All commands exist in `aliyun ossutil`
- Positional arguments and flags follow the CLI help
#### INCORRECT
```bash
aliyun ossutil stat --bucket examplebucket --object big/test.bin --user-agent AlibabaCloud-Agent-Skills
aliyun ossutil presign --bucket examplebucket --object private/test.bin --user-agent AlibabaCloud-Agent-Skills
aliyun ossutil ls --bucket examplebucket --user-agent AlibabaCloud-Agent-Skills
aliyun oss api GetBucketLocation --bucket examplebucket
```
Why incorrect:
- `stat` and `presign` use `oss://bucket/object` positional targets, not `--bucket` / `--object` flags
- `ossutil ls --bucket ...` is not the documented CLI shape
- `aliyun oss api ...` / `GetBucketLocation` is outside this skill's accepted command patterns
---
# Correct Common SDK Code Patterns (if applicable)
This skill uses `aliyun ossutil` as its primary tool; the current workflow does not require a Python Common SDK implementation.
#### CORRECT
- Clearly state that this scenario is powered by `aliyun ossutil probe`
- If supplementary scripts are needed, they should only wrap CLI invocations, parse output, and organize logs; do not fabricate a non-existent OSS OpenAPI `probe`
#### INCORRECT
```python
# Non-existent OSS OpenAPI example
client.probe_state(bucket='examplebucket')
```
Why incorrect:
- There is no documented OSS OpenAPI named `probe` or `probe_state` that can replace `ossutil probe`
---
# Success Output Expectations
#### CORRECT
- Upload probe output contains `upload file:success`
- Download probe output contains `download file:success`
- Bandwidth probe output contains `suggest parallel is <N>`
- Download time probe output contains `total bytes`, `cost`, `avg speed`
- After probe execution, `report log file:` or a local `logOssProbe*.log` file should be present
#### INCORRECT
- Only CLI help output is shown without actual probe results
- After an error, still claiming the probe succeeded, or describing a failure as "task completed successfully"
- Retaining or deleting user test objects without confirmation
- Writing the full presigned URL, STS token, or local credential file contents in logs or the final answer
- After `NoSuchBucket` / `AccessDenied`, enumerating unconfirmed regions, buckets, or endpoints and drawing conclusions from them
- In a `cycle-symlink` scenario, writing a complete cyclic chain as verified fact when supplementary forensics did not actually read a particular segment's target
---
# Boundary Acceptance Criteria
#### CORRECT
- Clearly state that `cycle-symlink` can only detect, not auto-fix
- Clearly state that `download-speed` requires an existing object; if none exists, a test object must be confirmed and uploaded first
- Clearly state that `probe` is a composite client-side command, not a standalone OpenAPI
#### INCORRECT
- Claiming the same workflow can be achieved via `aliyun oss api probe`
- Claiming all symlink anomalies can be auto-fixed
- Auto-creating and permanently retaining test objects without user confirmation
FILE:references/cli-installation-guide.md
# Aliyun CLI Installation & Configuration Guide
Complete guide for installing and configuring Aliyun CLI.
> **Aliyun CLI 3.3.3+**: Supports installing and using all published Alibaba Cloud product plugins. Make sure to upgrade to 3.3.3 or later for full plugin ecosystem coverage.
## Installation
### macOS
**Using Homebrew (Recommended)**
```bash
brew install aliyun-cli
# Upgrade to latest
brew upgrade aliyun-cli
# Verify version (>= 3.3.3)
aliyun version
```
**Using Binary**
```bash
# Download
wget https://aliyuncli.alicdn.com/aliyun-cli-macosx-latest-amd64.tgz
# Extract
tar -xzf aliyun-cli-macosx-latest-amd64.tgz
# Move to PATH
sudo mv aliyun /usr/local/bin/
# Verify
aliyun version
```
### Linux
**Debian/Ubuntu**
```bash
# Download
wget https://aliyuncli.alicdn.com/aliyun-cli-linux-latest-amd64.tgz
# Extract and install
tar -xzf aliyun-cli-linux-latest-amd64.tgz
sudo mv aliyun /usr/local/bin/
# Verify
aliyun version
```
**CentOS/RHEL**
```bash
# Download
wget https://aliyuncli.alicdn.com/aliyun-cli-linux-latest-amd64.tgz
# Extract and install
tar -xzf aliyun-cli-linux-latest-amd64.tgz
sudo mv aliyun /usr/local/bin/
# Verify
aliyun version
```
**ARM64 Architecture**
```bash
# Download ARM64 version
wget https://aliyuncli.alicdn.com/aliyun-cli-linux-latest-arm64.tgz
# Extract and install
tar -xzf aliyun-cli-linux-latest-arm64.tgz
sudo mv aliyun /usr/local/bin/
```
### Windows
**Using Binary**
1. Download from: https://aliyuncli.alicdn.com/aliyun-cli-windows-latest-amd64.zip
2. Extract the ZIP file
3. Add the directory to your PATH environment variable
4. Open new Command Prompt or PowerShell
5. Verify: `aliyun version`
**Using PowerShell**
```powershell
# Download
Invoke-WebRequest -Uri "https://aliyuncli.alicdn.com/aliyun-cli-windows-latest-amd64.zip" -OutFile "aliyun-cli.zip"
# Extract
Expand-Archive -Path aliyun-cli.zip -DestinationPath C:\aliyun-cli
# Add to PATH (requires admin privileges)
$env:Path += ";C:\aliyun-cli"
[Environment]::SetEnvironmentVariable("Path", $env:Path, [System.EnvironmentVariableTarget]::Machine)
# Verify
aliyun version
```
## Configuration
> **SECURITY WARNING — For manual user setup only**
>
> The credential configuration commands below are for **humans to run manually in their own terminal**, outside of any agent session.
> **Agents MUST NEVER execute `aliyun configure set` with literal credential values** (access-key-id, access-key-secret, sts-token).
> Within an agent session, only use `aliyun configure list` to verify that credentials are already configured.
### Quick Start
Run the following command **in your own terminal** (not via an agent):
```bash
aliyun configure set \
--mode AK \
--access-key-id <your-access-key-id> \
--access-key-secret <your-access-key-secret> \
--region cn-hangzhou
```
All `aliyun configure` commands support non-interactive flags, which is the recommended approach —
it works in scripts, CI/CD pipelines, and manual terminal setup without hanging on stdin prompts.
**Where to Get Access Keys**
1. Log in to Aliyun Console: https://ram.console.aliyun.com/
2. Navigate to: AccessKey Management
3. Create a new AccessKey pair
4. Save the secret immediately — it's only shown once
### Configuration Modes
Aliyun CLI supports 6 authentication modes. All examples below use non-interactive flags.
#### 1. AK Mode (Access Key)
Most common mode for personal accounts and scripts.
```bash
aliyun configure set \
--mode AK \
--access-key-id LTAI5tXXXXXXXX \
--access-key-secret 8dXXXXXXXXXXXXXXXXXXXXXXXX \
--region cn-hangzhou
```
Configuration is stored in `~/.aliyun/config.json`:
```json
{
"current": "default",
"profiles": [
{
"name": "default",
"mode": "AK",
"access_key_id": "LTAI5tXXXXXXXX",
"access_key_secret": "8dXXXXXXXXXXXXXXXXXXXXXXXX",
"region_id": "cn-hangzhou",
"output_format": "json",
"language": "en"
}
]
}
```
#### 2. StsToken Mode (Temporary Credentials)
For short-lived access (tokens expire in 1-12 hours).
```bash
aliyun configure set \
--mode StsToken \
--access-key-id LTAI5tXXXXXXXX \
--access-key-secret 8dXXXXXXXXXXXXXXXXXXXXXXXX \
--sts-token v1.0:XXXXXXXXXXXXXXXX \
--region cn-hangzhou
```
Use cases: CI/CD pipelines, temporary access for external contractors, cross-account access.
#### 3. RamRoleArn Mode (Assume RAM Role)
Assume a RAM role for elevated or cross-account access.
```bash
aliyun configure set \
--mode RamRoleArn \
--access-key-id LTAI5tXXXXXXXX \
--access-key-secret 8dXXXXXXXXXXXXXXXXXXXXXXXX \
--ram-role-arn acs:ram::123456789012:role/AdminRole \
--role-session-name my-session \
--region cn-hangzhou
```
Use cases: cross-account resource access, temporary elevated privileges, role-based access control.
#### 4. EcsRamRole Mode (ECS Instance RAM Role)
Use the RAM role attached to an ECS instance — no credentials needed.
```bash
aliyun configure set \
--mode EcsRamRole \
--ram-role-name MyEcsRole \
--region cn-hangzhou
```
Requirements: must be running on an ECS instance with a RAM role attached.
Use cases: scripts and automation running on ECS instances.
#### 5. RsaKeyPair Mode (RSA Key Pair)
Use RSA key pair for authentication (generate key pair in Aliyun Console first).
```bash
aliyun configure set \
--mode RsaKeyPair \
--private-key /path/to/private-key.pem \
--key-pair-name my-key-pair \
--region cn-hangzhou
```
#### 6. RamRoleArnWithEcs Mode (ECS + RAM Role)
Combine ECS instance role with RAM role assumption for cross-account access from ECS.
```bash
aliyun configure set \
--mode RamRoleArnWithEcs \
--ram-role-name MyEcsRole \
--ram-role-arn acs:ram::123456789012:role/TargetRole \
--role-session-name my-session \
--region cn-hangzhou
```
### Environment Variables
**Highest priority** - overrides config file
**Access Key Mode**
```bash
export ALIBABA_CLOUD_ACCESS_KEY_ID=your_access_key_id
export ALIBABA_CLOUD_ACCESS_KEY_SECRET=your_access_key_secret
export ALIBABA_CLOUD_REGION_ID=cn-hangzhou
```
**STS Token Mode**
```bash
export ALIBABA_CLOUD_ACCESS_KEY_ID=your_access_key_id
export ALIBABA_CLOUD_ACCESS_KEY_SECRET=your_access_key_secret
export ALIBABA_CLOUD_SECURITY_TOKEN=your_sts_token
export ALIBABA_CLOUD_REGION_ID=cn-hangzhou
```
**ECS RAM Role Mode**
```bash
export ALIBABA_CLOUD_ECS_METADATA=role_name
```
**Use Case**:
- CI/CD pipelines
- Docker containers
- Temporary credential override
### Managing Multiple Profiles
**Create Named Profiles**
```bash
aliyun configure set --profile projectA \
--mode AK \
--access-key-id LTAI5tAAAAAAAA \
--access-key-secret 8dAAAAAAAAAAAAAAAAAAAAAAAA \
--region cn-hangzhou
aliyun configure set --profile projectB \
--mode AK \
--access-key-id LTAI5tBBBBBBBB \
--access-key-secret 8dBBBBBBBBBBBBBBBBBBBBBBBB \
--region cn-shanghai
```
**Use Specific Profile**
```bash
aliyun ecs describe-instances --profile projectA
export ALIBABA_CLOUD_PROFILE=projectA
aliyun ecs describe-instances # Uses projectA
```
**List and Switch Profiles**
```bash
aliyun configure list # List all profiles
aliyun configure set --current projectA # Switch default profile
```
### Credential Priority
Credentials are loaded in this order (first found wins):
1. **Command-line flag**: `--profile <name>`
2. **Environment variable**: `ALIBABA_CLOUD_PROFILE`
3. **Environment credentials**: `ALIBABA_CLOUD_ACCESS_KEY_ID`, etc.
4. **Configuration file**: `~/.aliyun/config.json` (current profile)
5. **ECS Instance RAM Role**: If running on ECS with attached role
## Verification
### Test Authentication
```bash
# Basic test - list regions
aliyun ecs describe-regions
# Expected output: JSON array of regions
```
**If successful**, you'll see:
```json
{
"Regions": {
"Region": [
{
"RegionId": "cn-hangzhou",
"RegionEndpoint": "ecs.cn-hangzhou.aliyuncs.com",
"LocalName": "华东 1(杭州)"
},
...
]
},
"RequestId": "..."
}
```
**If failed**, you'll see error messages:
- `InvalidAccessKeyId.NotFound` - Wrong Access Key ID
- `SignatureDoesNotMatch` - Wrong Access Key Secret
- `InvalidSecurityToken.Expired` - STS token expired (for StsToken mode)
- `Forbidden.RAM` - Insufficient permissions
### Debug Configuration
```bash
# Show current configuration
aliyun configure get
# Test with debug logging
aliyun ecs describe-regions --log-level=debug
# Check credential provider
aliyun configure get mode
```
## Security Best Practices
### 1. Use RAM Users (Not Root Account)
❌ **Don't**: Use Aliyun root account credentials
✅ **Do**: Create RAM users with specific permissions
```bash
# Create RAM user in console
# Attach only necessary policies
# Use RAM user's access keys
```
### 2. Principle of Least Privilege
Grant only the minimum permissions needed:
```bash
# Example: Read-only ECS access
# Attach policy: AliyunECSReadOnlyAccess
```
### 3. Rotate Access Keys Regularly
Run in your own terminal (never via an agent):
```bash
# Create new access key in RAM Console, then update configuration
aliyun configure set --access-key-id NEW_KEY --access-key-secret NEW_SECRET
# Delete old access key from console
```
### 4. Use STS Tokens for Temporary Access
```bash
aliyun configure set --mode StsToken \
--access-key-id XXXX --access-key-secret XXXX \
--sts-token XXXX --region cn-hangzhou
```
### 5. Use ECS RAM Roles When Possible
```bash
aliyun configure set --mode EcsRamRole --ram-role-name MyRole --region cn-hangzhou
```
### 6. Never Commit Credentials
```bash
# Add to .gitignore
echo "~/.aliyun/config.json" >> .gitignore
# Use environment variables in CI/CD instead
```
### 7. Secure Config File
```bash
# Restrict permissions
chmod 600 ~/.aliyun/config.json
```
## Troubleshooting
### Issue: Command Not Found
```bash
# Check installation
which aliyun
# Check PATH
echo $PATH
# Reinstall or add to PATH
```
### Issue: Authentication Failed
```bash
# Verify configuration
aliyun configure get
# Test with debug
aliyun ecs describe-regions --log-level=debug
# Check credentials in console
# Verify access key is active
```
### Issue: Permission Denied
```bash
# Error: Forbidden.RAM
# Check RAM user permissions
# Attach necessary policies in RAM console
# Example: AliyunECSFullAccess for ECS operations
```
### Issue: STS Token Expired
Run in your own terminal (never via an agent):
```bash
# Error: InvalidSecurityToken.Expired
# Reconfigure with new token
aliyun configure set --mode StsToken \
--access-key-id XXXX --access-key-secret XXXX \
--sts-token NEW_TOKEN --region cn-hangzhou
```
### Issue: Wrong Region
```bash
# Some resources may not exist in the specified region
# Check available regions
aliyun ecs describe-regions
# Update default region
aliyun configure set region cn-shanghai
```
## Advanced Configuration
### Custom Endpoint
```bash
# Use custom or private endpoint
export ALIBABA_CLOUD_ECS_ENDPOINT=ecs-vpc.cn-hangzhou.aliyuncs.com
```
### Proxy Settings
```bash
# HTTP proxy
export HTTP_PROXY=http://proxy.example.com:8080
export HTTPS_PROXY=http://proxy.example.com:8080
# No proxy for specific domains
export NO_PROXY=localhost,127.0.0.1,.aliyuncs.com
```
### Timeout Settings
```bash
# Connection timeout (default: 10s)
export ALIBABA_CLOUD_CONNECT_TIMEOUT=30
# Read timeout (default: 10s)
export ALIBABA_CLOUD_READ_TIMEOUT=30
```
## Next Steps
After installation and configuration:
1. **Install plugins** for services you need (v3.3.3+ supports all published product plugins):
```bash
aliyun plugin install --names ecs vpc rds
# List all available plugins
aliyun plugin list-remote
```
2. **Explore commands**:
```bash
aliyun ecs --help
aliyun fc --help
```
3. **Read documentation**:
- [Command Syntax Guide](./command-syntax.md)
- [Global Flags Reference](./global-flags.md)
- [Common Scenarios](./common-scenarios.md)
## References
- Official Documentation: https://help.aliyun.com/zh/cli/
- RAM Console: https://ram.console.aliyun.com/
- Access Key Management: https://ram.console.aliyun.com/manage/ak
- Plugin Repository: https://github.com/aliyun/aliyun-cli
FILE:references/implementation-boundaries.md
# Implementation Boundaries: alibabacloud-oss-manage-network-probe
## Overview
This skill centers on `aliyun ossutil probe` and uses the Alibaba Cloud CLI to perform OSS network diagnostics.
However, there are clear boundaries: some capabilities are composite client-side behaviors, and some can only detect issues but cannot auto-fix them.
## Supported with Aliyun CLI
| Item | CLI/Code Status | Notes |
| --- | --- | --- |
| `aliyun ossutil probe --upload ... --user-agent AlibabaCloud-Agent-Skills/alibabacloud-oss-manage-network-probe` | Supported | Tests local-to-OSS link status via upload or temporary object |
| `aliyun ossutil probe --download ... --user-agent AlibabaCloud-Agent-Skills/alibabacloud-oss-manage-network-probe` | Supported | Supports URL download probe or Bucket/Object download probe |
| `aliyun ossutil probe --probe-item upload-speed ... --user-agent AlibabaCloud-Agent-Skills/alibabacloud-oss-manage-network-probe` | Supported | Outputs upload bandwidth and suggested concurrency |
| `aliyun ossutil probe --probe-item download-speed ... --user-agent AlibabaCloud-Agent-Skills/alibabacloud-oss-manage-network-probe` | Supported | Outputs download bandwidth and suggested concurrency |
| `aliyun ossutil probe --probe-item download-time ... --user-agent AlibabaCloud-Agent-Skills/alibabacloud-oss-manage-network-probe` | Supported | Outputs download time and throughput statistics |
| `aliyun ossutil probe --probe-item cycle-symlink ... --user-agent AlibabaCloud-Agent-Skills/alibabacloud-oss-manage-network-probe` | Supported for detection only | Local symlink anomaly detection only |
| `aliyun ossutil presign ... --user-agent AlibabaCloud-Agent-Skills/alibabacloud-oss-manage-network-probe` | Supported | Generates presigned URL for private object download probe |
| `aliyun ossutil cp ... --user-agent AlibabaCloud-Agent-Skills/alibabacloud-oss-manage-network-probe` | Supported | Prepares test objects for `download-speed` |
## Not a Single OpenAPI Primitive
| Item | Status | Why it matters |
| --- | --- | --- |
| `probe` | Not a single OpenAPI | There is no `aliyun oss api probe`; `probe` is a composite client-side diagnostic command in ossutil |
| `cycle-symlink` | Local-only logic | Detection occurs on the local filesystem, not via an OSS remote API |
| `--addr` network probing | Partially environment-dependent | Affected by local DNS, ICMP policies, proxies, and corporate network policies; failure does not necessarily indicate an OSS issue |
## Steps That Cannot Be Fully Automated Safely
| Item | CLI/Code Status | Reason |
| --- | --- | --- |
| Auto-fix abnormal symlinks | Not safely supported | Requires knowledge of the correct target path and business intent; cannot be safely guessed |
| Auto-determine root cause of all network issues | Partially supported | `probe` provides symptoms, throughput, and logs, but manual analysis of the network environment is still needed |
| Construct a `download-speed` test object without an existing object or local file | Not purely CLI-only | `download-speed` requires an existing object; if none is available, the user must confirm an existing object path or provide a local file to upload via `aliyun ossutil cp` |
| Auto-decide whether to retain test objects or local downloaded files | Requires user confirmation | This affects user data and cleanup strategy; confirmation is required first |
## Practical Guidance
1. If the user only needs link diagnostics, do not force creation of persistent objects; prefer using `probe`'s temporary object capability.
2. If the user wants to test `download-speed`, prefer asking the user to confirm an existing object larger than 5 MiB.
3. If `--addr` detection fails but OSS upload/download succeeds, do not conclude an OSS failure; suggest checking local network, proxy, DNS, and security policies.
4. If `cycle-symlink` detects anomalies, only report the abnormal paths and impact; do not auto-rewrite link targets.
5. If the user requests "implement everything via code", clarify that this scenario is covered by `ossutil` integrated with the Alibaba Cloud CLI, and there is no standalone OSS OpenAPI `probe` that can replace this command.
FILE:references/ram-polices.md
# RAM Policies: alibabacloud-oss-manage-network-probe
## Overview
The minimum permission set for this skill depends on the probe mode.
`aliyun ossutil probe` may directly access existing objects, or temporarily upload and delete objects for diagnostics.
Therefore, permissions should be granted per scenario at the minimum required level, rather than granting `oss:*`.
## Scenario Permission Matrix
| Scenario | Required RAM actions | Why |
| --- | --- | --- |
| CLI version / local config check | None | Local CLI behavior only |
| `probe --probe-item cycle-symlink <local_path>` | None | Local symlink check only |
| `probe --download --url <signed_or_public_url>` | `oss:GetObject` | Downloads OSS object content |
| `probe --download --bucket <bucket> --object <object>` | `oss:GetObject` | Downloads the specified object |
| `probe --download --bucket <bucket>` with temporary object | `oss:GetObject`, `oss:PutObject`, `oss:DeleteObject` | Creates a temporary object, downloads it, then cleans up |
| `probe --upload --bucket <bucket>` | `oss:GetObject`, `oss:PutObject`, `oss:DeleteObject` | Official docs require these three for upload bandwidth/upload probe |
| `probe --probe-item upload-speed --bucket <bucket>` | `oss:GetObject`, `oss:PutObject`, `oss:DeleteObject` | Repeatedly uploads for diagnostics and cleans up test objects |
| `probe --probe-item download-speed --bucket <bucket> --object <object>` | `oss:GetObject` | Repeatedly downloads the object and measures throughput |
| `probe --probe-item download-time --bucket <bucket> --object <object>` | `oss:GetObject` | Downloads and calculates elapsed time |
| `ossutil cp <local_file> oss://<bucket>/<object>` | `oss:PutObject` | Prepares test objects |
| `ossutil rm oss://<bucket>/<object>` | `oss:DeleteObject` | Cleans up explicitly created test objects |
| `ossutil stat oss://<bucket>/<object>` | `oss:GetObject` | Views object metadata |
| `ossutil ls oss://<bucket>/<prefix>` | `oss:ListObjects` | Lists objects to confirm paths |
| `ossutil presign oss://<bucket>/<object>` | Usually none extra for single object; `oss:ListObjects` if recursive/batch | Local signing; listing is required for recursive operations |
## Least-Privilege Recommendations
1. For symlink detection only, do not grant any OSS data permissions.
2. For download-only probes, prefer granting only `oss:GetObject`.
3. Only add `oss:PutObject` and `oss:DeleteObject` for upload probes, upload bandwidth probes, or temporary-object download probes.
4. Only add `oss:ListObjects` when object listing or recursive processing is needed.
5. If the test object is a user-specified business object, grant delete permission cautiously and confirm the cleanup strategy first.
## Summary Table by Product
| Product | RAM Action | Resource Scope | Description |
| --- | --- | --- | --- |
| OSS | `oss:GetObject` | `acs:oss:*:*:<bucket>/<object-or-prefix>` or `*` | Download objects, read object content, partial probe workflows |
| OSS | `oss:PutObject` | `acs:oss:*:*:<bucket>/<object-or-prefix>` or `*` | Upload probes, prepare test objects, create temporary objects |
| OSS | `oss:DeleteObject` | `acs:oss:*:*:<bucket>/<object-or-prefix>` or `*` | Delete explicit test objects or temporary objects |
| OSS | `oss:ListObjects` | `acs:oss:*:*:<bucket>` or `*` | List objects, recursive presign, or path confirmation |
## Example Policy: download-only probing
Applicable to:
- `aliyun ossutil probe --download --bucket <bucket> --object <object> --user-agent AlibabaCloud-Agent-Skills/alibabacloud-oss-manage-network-probe`
- `aliyun ossutil probe --probe-item download-speed --bucket <bucket> --object <object> --user-agent AlibabaCloud-Agent-Skills/alibabacloud-oss-manage-network-probe`
- `aliyun ossutil probe --probe-item download-time --bucket <bucket> --object <object> --user-agent AlibabaCloud-Agent-Skills/alibabacloud-oss-manage-network-probe`
```json
{
"Version": "1",
"Statement": [
{
"Effect": "Allow",
"Action": [
"oss:GetObject"
],
"Resource": "*"
}
]
}
```
## Example Policy: upload / temporary-object probing
Applicable to:
- `aliyun ossutil probe --upload --bucket <bucket> --user-agent AlibabaCloud-Agent-Skills/alibabacloud-oss-manage-network-probe`
- `aliyun ossutil probe --probe-item upload-speed --bucket <bucket> --user-agent AlibabaCloud-Agent-Skills/alibabacloud-oss-manage-network-probe`
- `aliyun ossutil probe --download --bucket <bucket> --user-agent AlibabaCloud-Agent-Skills/alibabacloud-oss-manage-network-probe` without explicit object
```json
{
"Version": "1",
"Statement": [
{
"Effect": "Allow",
"Action": [
"oss:GetObject",
"oss:PutObject",
"oss:DeleteObject"
],
"Resource": "*"
}
]
}
```
## Example Policy: full troubleshooting workflow
Applicable to:
- Listing objects to confirm paths
- Pre-uploading test objects
- Download bandwidth testing
- Cleaning up objects after completion
```json
{
"Version": "1",
"Statement": [
{
"Effect": "Allow",
"Action": [
"oss:GetObject",
"oss:PutObject",
"oss:DeleteObject",
"oss:ListObjects"
],
"Resource": "*"
}
]
}
```
## Notes
- Official `probe` documentation states: upload bandwidth probing requires at minimum `oss:GetObject`, `oss:PutObject`, `oss:DeleteObject`; download bandwidth probing requires at minimum `oss:GetObject`.
- The `configure list`, `configure set --auto-plugin-install true`, `configure ai-mode enable`, and `version` commands in this skill are all local CLI operations and do not correspond to RAM permissions.
- If the user requires stricter resource scoping, narrow the `Resource` from `*` to specific bucket/object ARN ranges.
FILE:references/related-apis.md
# Related APIs and Commands: alibabacloud-oss-manage-network-probe
## Overview
`aliyun ossutil probe` is a composite client-side diagnostic command.
It is not a single OSS OpenAPI, but rather a combination of local diagnostic logic and a set of OSS data access capabilities.
Therefore, this table lists:
1. The actual Alibaba Cloud CLI commands executed
2. The related underlying OSS capabilities or local behaviors
3. Minimum permission or constraint notes
## Command and Capability Table
| Workflow Step | CLI Command | Underlying OSS capability / local behavior | Minimum RAM action / permission | Notes |
| --- | --- | --- | --- | --- |
| CLI version check | `aliyun version` | Local CLI behavior | None | Verifies CLI version >= 3.3.3 |
| Enable auto plugin install | `aliyun configure set --auto-plugin-install true` | Local CLI behavior | None | Not a cloud OpenAPI |
| Enable AI safety mode | `aliyun configure ai-mode enable` | Local CLI behavior | None | Enables safety mode; dangerous operations are blocked |
| Credential gate | `aliyun configure list` | Local CLI behavior | None | Only checks whether the local profile is valid |
| Integrated ossutil check | `aliyun ossutil version` | Local CLI behavior | None | Verifies `ossutil 2.0` is integrated |
| Upload connectivity probe | `aliyun ossutil probe --upload --bucket <bucket> [<local_file>] --user-agent AlibabaCloud-Agent-Skills` | Composite probe using upload workflow and optional temporary object cleanup | Documented minimum: `oss:GetObject`, `oss:PutObject`, `oss:DeleteObject` | `--upmode` accepts `normal` / `append` / `multipart` |
| Download connectivity probe by URL | `aliyun ossutil probe --download --url "<http_url>" [<local_path>] --user-agent AlibabaCloud-Agent-Skills` | Download via HTTP/HTTPS URL | `oss:GetObject` when the URL points to an OSS object | Private objects require a presigned URL first |
| Download connectivity probe by bucket/object | `aliyun ossutil probe --download --bucket <bucket> [--object <object>] [<local_path>] --user-agent AlibabaCloud-Agent-Skills` | `GetObject`; if `--object` is omitted, probe creates and deletes a temporary object | With explicit object: `oss:GetObject`; with temporary object workflow: `oss:GetObject`, `oss:PutObject`, `oss:DeleteObject` | Suitable for directly verifying Bucket/Object paths |
| Symlink detection | `aliyun ossutil probe --probe-item cycle-symlink <local_path> --user-agent AlibabaCloud-Agent-Skills` | Local filesystem inspection only | None | Does not access OSS |
| Upload bandwidth probe | `aliyun ossutil probe --probe-item upload-speed --bucket <bucket> --user-agent AlibabaCloud-Agent-Skills` | Repeated upload diagnostics plus concurrency recommendation | Documented minimum: `oss:GetObject`, `oss:PutObject`, `oss:DeleteObject` | Outputs `suggest parallel is <N>` |
| Download bandwidth probe | `aliyun ossutil probe --probe-item download-speed --bucket <bucket> --object <object> --user-agent AlibabaCloud-Agent-Skills` | Repeated download diagnostics plus concurrency recommendation | `oss:GetObject` | Official recommendation: object larger than 5 MiB |
| Download time probe | `aliyun ossutil probe --probe-item download-time --bucket <bucket> --object <object> --user-agent AlibabaCloud-Agent-Skills` | Timed download with optional part size and parallelism | `oss:GetObject` | `--parallel` / `--part-size` only valid for this mode |
| Optional prep upload | `aliyun ossutil cp "<local_file>" "oss://<bucket>/<object>" --user-agent AlibabaCloud-Agent-Skills` | Upload local file to OSS | `oss:PutObject` | Prepares test objects for `download-speed` |
| Optional presigned URL | `aliyun ossutil presign "oss://<bucket>/<object>" --expires-duration 1h --user-agent AlibabaCloud-Agent-Skills` | Local signing for a specific OSS object URL | Usually no additional OSS call for a single object URL | May require `oss:ListObjects` for recursive/batch URL generation |
| Optional cleanup | `aliyun ossutil rm "oss://<bucket>/<object>" --user-agent AlibabaCloud-Agent-Skills` | Delete probe object | `oss:DeleteObject` | Only used when the user confirms deletion of explicitly created test objects |
## Important Notes
1. `probe` is not a command under `aliyun oss api`; do not write `aliyun oss api probe`.
2. `--url` mode only accepts HTTP/HTTPS URLs; it cannot take `oss://bucket/object`.
3. `cycle-symlink` has no cloud API counterpart; it performs local filesystem inspection.
4. `--user-agent AlibabaCloud-Agent-Skills` must be added only to API-calling commands (e.g., `probe`, `cp`, `presign`, `rm`). Local CLI commands (`aliyun version`, `aliyun configure ...`, `aliyun ossutil version`) do not support this flag.
5. For API-calling commands, `--user-agent` is passed as a trailing flag after all other arguments.
## Validated Command Set
The following commands have been validated against their help output during skill generation:
- `aliyun version`
- `aliyun configure list`
- `aliyun configure set --auto-plugin-install true`
- `aliyun configure ai-mode enable`
- `aliyun ossutil version`
- `aliyun ossutil probe --help --user-agent AlibabaCloud-Agent-Skills`
- `aliyun ossutil cp --help --user-agent AlibabaCloud-Agent-Skills`
- `aliyun ossutil presign --help --user-agent AlibabaCloud-Agent-Skills`
- `aliyun ossutil rm --help --user-agent AlibabaCloud-Agent-Skills`
FILE:references/verification-method.md
# Verification Method: alibabacloud-oss-manage-network-probe
## Goal
Verify that the `aliyun ossutil probe` solution has successfully achieved one of the following objectives:
- Successfully diagnosed the local-to-OSS upload or download link
- Output upload/download bandwidth with a suggested concurrency value
- Output download time statistics
- Detected whether local symlinks have anomalies
## Step 1: Verify CLI prerequisites
```bash
aliyun version
aliyun configure list
aliyun ossutil version
```
Success indicators:
- `version` outputs a version number >= 3.3.3
- `configure list` shows at least one `Valid` profile
- `ossutil version` returns version information successfully
Failure guardrails:
- If `configure list` does not show a valid profile, stop immediately; do not proceed with `configure set --auto-plugin-install true`, `configure ai-mode enable`, `ossutil version`, or any probe commands
- Do not read `~/.aliyun/config.json`, do not export environment variables, do not log any plaintext credentials
## Step 2: Verify input object or URL when needed
### 2.1 Verify a bucket/object path before download-speed or download-time
```bash
aliyun ossutil stat \
"oss://<BUCKET_NAME>/<OBJECT_NAME>" \
--region "<REGION_ID_IF_NEEDED>" \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-oss-manage-network-probe
```
Success indicator:
- Command returns object metadata, not `NoSuchKey` or a permission error
### 2.2 Verify download URL mode
For private objects, generate a presigned URL first, then run the URL download probe:
```bash
aliyun ossutil presign \
"oss://<BUCKET_NAME>/<OBJECT_NAME>" \
--expires-duration 1h \
--region "<REGION_ID_IF_NEEDED>" \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-oss-manage-network-probe
```
Success indicator:
- Outputs a usable HTTP/HTTPS URL
Security note:
- When logging execution results, do not persist the full presigned URL query string; only keep the base URL, or redact everything after `?`
## Step 3: Verify each probe mode
### 3.1 Upload connectivity probe
```bash
aliyun ossutil probe \
--upload \
--bucket "<BUCKET_NAME>" \
--region "<REGION_ID_IF_NEEDED>" \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-oss-manage-network-probe
```
Success indicators:
- Output contains `begin upload file`
- Output contains `upload file:success`
- Output contains `upload time consuming:`
- Output contains `report log file:`
### 3.2 Download connectivity probe by bucket
```bash
aliyun ossutil probe \
--download \
--bucket "<BUCKET_NAME>" \
--object "<OBJECT_NAME_IF_ANY>" \
--region "<REGION_ID_IF_NEEDED>" \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-oss-manage-network-probe
```
Success indicators:
- Output contains `begin download file`
- Output contains `download file:success`
- Output contains `download time consuming:`
- Output contains `download file is`
### 3.3 Download connectivity probe by URL
```bash
aliyun ossutil probe \
--download \
--url "<DOWNLOAD_URL>" \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-oss-manage-network-probe
```
Success indicators:
- Output contains `download file:success`
- Output contains the target local file path
### 3.4 Upload bandwidth probe
Basic command:
```bash
aliyun ossutil probe \
--probe-item upload-speed \
--bucket "<BUCKET_NAME>" \
--region "<REGION_ID_IF_NEEDED>" \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-oss-manage-network-probe
```
To limit runtime, add `--runtime`:
```bash
aliyun ossutil probe \
--probe-item upload-speed \
--bucket "<BUCKET_NAME>" \
--runtime "<RUNTIME_IF_CONFIRMED>" \
--region "<REGION_ID_IF_NEEDED>" \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-oss-manage-network-probe
```
Success indicators:
- Output contains multiple lines of `parallel:<N>,average speed:`
- Output contains `suggest parallel is <N>`
### 3.5 Download bandwidth probe
```bash
aliyun ossutil probe \
--probe-item download-speed \
--bucket "<BUCKET_NAME>" \
--object "<OBJECT_NAME>" \
--runtime "<RUNTIME_IF_CONFIRMED>" \
--region "<REGION_ID_IF_NEEDED>" \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-oss-manage-network-probe
```
Success indicators:
- Output contains multiple lines of `parallel:<N>,average speed:`
- Output contains `suggest parallel is <N>`
- If the object is smaller than the recommended size or network fluctuations are significant, results may be unstable, but the command should still complete
### 3.6 Download time probe
Basic command:
```bash
aliyun ossutil probe \
--probe-item download-time \
--bucket "<BUCKET_NAME>" \
--object "<OBJECT_NAME>" \
--region "<REGION_ID_IF_NEEDED>" \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-oss-manage-network-probe
```
To explicitly control concurrency and part size, add:
```bash
aliyun ossutil probe \
--probe-item download-time \
--bucket "<BUCKET_NAME>" \
--object "<OBJECT_NAME>" \
--parallel "<PARALLEL_IF_CONFIRMED>" \
--part-size "<PART_SIZE_IF_CONFIRMED>" \
--region "<REGION_ID_IF_NEEDED>" \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-oss-manage-network-probe
```
Success indicators:
- Output contains `total bytes:`
- Output contains `cost:`
- Output contains `avg speed:`
### 3.7 Symlink detection
```bash
aliyun ossutil probe \
--probe-item cycle-symlink \
"<LOCAL_DIRECTORY_OR_FILE>" \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-oss-manage-network-probe
```
Success indicators:
- Command completes normally and outputs elapsed time
- If no anomalies, output should indicate no abnormal symlinks
- If anomalies are found, output should list the abnormal symlink information
Supplementary forensics rules:
- To reconstruct specific link chains, perform read-only local forensics on the same path (e.g. `readlink`, `stat -f "%N -> %Y"`)
- Only write precise chains when the target is successfully read; if `readlink`/`stat` itself fails, report only verified segments and the raw probe error
## Step 4: Verify local probe logs
After probe execution, check whether `logOssProbe*.log` files were generated in the current working directory or the `ossutil` run directory.
```bash
ls -1t logOssProbe*.log
```
Success indicator:
- At least one recent `logOssProbe*.log` file exists
## Step 5: Optional cleanup verification
If a test object was explicitly uploaded and is planned for deletion, execute:
```bash
aliyun ossutil rm \
"oss://<BUCKET_NAME>/<OBJECT_NAME>" \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-oss-manage-network-probe
```
Then verify the object no longer exists:
```bash
aliyun ossutil stat \
"oss://<BUCKET_NAME>/<OBJECT_NAME>" \
--region "<REGION_ID_IF_NEEDED>" \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-oss-manage-network-probe
```
Success indicator:
- Delete command succeeds
- Subsequent `stat` returns object not found, or the user confirms retaining the object and this step is skipped
## Failure Interpretation
| Symptom | Likely meaning | Next action |
| --- | --- | --- |
| `configure list` shows no valid profile | Credentials are unavailable | Configure credentials outside the session first |
| `probe --download-speed` reports object not found | `object_name` is wrong or the object has not been prepared | Run `ossutil stat` on the same target first; do not enumerate unconfirmed regions/buckets |
| `probe --download --url` returns 404/403 | URL is reachable but object, permission, or bucket conditions are not met | Quote the raw HTTP error; if necessary, run a single `stat` validation on the same `bucket/object/region` |
| `probe` fails during `network detection` phase | Local network, DNS, proxy, or link to the target address is abnormal | Continue troubleshooting with `--addr`, proxy configuration, and local network |
| `The bucket you are attempting to access must be addressed using the specified endpoint` | The current request endpoint does not match the bucket's requirements | Ask the user to confirm the correct region/endpoint or execution environment; do not assert VPC-only on your own |
| Only `--addr` detection fails, but OSS upload/download succeeds | Domain connectivity issue, not necessarily an OSS failure | Use the correct domain or skip this check |
| `cycle-symlink` reports `no such file or directory` | The local path does not exist in the current execution environment | Clearly state this is a missing local path; do not auto-rewrite it as "expected behavior" |
| `cycle-symlink` reports anomalies | Local symlink target is abnormal or a cyclic link exists | Manually fix the link, then retry |
Alibaba Cloud PAI Workspace Management Skill. Create, query, and list workspaces on the Platform for AI (PAI). Triggers: "create PAI workspace", "query PAI w...
---
name: alibabacloud-pai-workspace-manage
description: |
Alibaba Cloud PAI Workspace Management Skill. Create, query, and list workspaces on the Platform for AI (PAI).
Triggers: "create PAI workspace", "query PAI workspace", "list workspaces", "PAI workspace", "create workspace", "get workspace", "list workspaces", "AIWorkSpace CreateWorkspace", "AIWorkSpace GetWorkspace", "AIWorkSpace ListWorkspaces"
---
# PAI Workspace Management
Create, query, and list workspaces on Alibaba Cloud Platform for AI (PAI). Workspaces serve as isolated management units for AI model training, data processing, and related tasks.
**Architecture**: PAI AIWorkSpace (Workspace)
**Workspace Modes**:
- **Simple Mode**: Production environment only (`prod`)
- **Standard Mode**: Development (`dev`) + Production (`prod`) environments
---
## Installation
> **Pre-check: Aliyun CLI >= 3.3.3 required**
> Run `aliyun version` to verify >= 3.3.3. If not installed or version too low,
> run `curl -fsSL https://aliyuncli.alicdn.com/setup.sh | bash` to install/update,
> or see `references/cli-installation-guide.md` for installation instructions.
> Then [MUST] run `aliyun configure set --auto-plugin-install true` to enable automatic plugin installation.
> Then [MUST] run `aliyun plugin update` to ensure that any existing plugins on your local machine are always up-to-date.
**[MUST] CLI User-Agent** — Every `aliyun` CLI command invocation must include:
`--user-agent AlibabaCloud-Agent-Skills/alibabacloud-pai-workspace-manage`
```bash
aliyun version
aliyun configure set --auto-plugin-install true
aliyun plugin update
```
---
## Credential Verification
> **Pre-check: Alibaba Cloud Credentials Required**
>
> **Security Rules:**
> - **NEVER** read, echo, or print AK/SK values (e.g., `echo $ALIBABA_CLOUD_ACCESS_KEY_ID` is FORBIDDEN)
> - **NEVER** ask the user to input AK/SK directly in the conversation or command line
> - **NEVER** use `aliyun configure set` with literal credential values
> - **ONLY** use `aliyun configure list` to check credential status
>
> **Sensitive Data Masking:**
> - The following fields in API responses contain personally identifiable information and **MUST be masked** before displaying to the user:
> - `Owner.UserId` / `Creator` — Show only last 4 digits, e.g., `****1234`
> - `Owner.UserKp` — Never display, omit entirely
> - `Owner.UserName` / `Owner.DisplayName` — Show only first character + `***`, e.g., `z***`
> - Accounts in `AdminNames` — Mask as `u***@example.com` format
> - **[MUST] Raw sensitive data MUST NOT appear in stdout, execution logs, on disk, or in the conversation**: The execution framework logs ALL command stdout to execution logs/transcripts (e.g., `ran-scripts/executed-actions.log`). Therefore, **EVERY** execution of `get-workspace` or `list-workspaces` (including basic queries without `--verbose`) must include `| jq -r` pipe filtering — because `Creator` is **always** returned and is sensitive. There must be **NO execution step** where the raw API JSON appears in command output, even as an intermediate step. The `| jq -r` pipe must be part of a **single pipeline command**:
>
> **Basic query** (without `--verbose`):
> ```bash
> aliyun aiworkspace get-workspace --workspace-id <ID> --region <RegionId> \
> --user-agent AlibabaCloud-Agent-Skills/alibabacloud-pai-workspace-manage \
> | jq -r '"Workspace: \(.WorkspaceName) (ID: \(.WorkspaceId))
> Status: \(.Status)
> Environment: \(.EnvTypes | join(", "))
> Created: \(.GmtCreateTime)
> Creator ID: \(.Creator // "" | if length > 0 then "****" + .[-4:] else "N/A" end)"'
> ```
>
> **Verbose query** (with `--verbose true`):
> ```bash
> aliyun aiworkspace get-workspace --workspace-id <ID> --verbose true --region <RegionId> \
> --user-agent AlibabaCloud-Agent-Skills/alibabacloud-pai-workspace-manage \
> | jq -r '"Workspace: \(.WorkspaceName) (ID: \(.WorkspaceId))
> Status: \(.Status)
> Owner: \(.Owner.UserName // "" | if length > 0 then .[0:1] + "***" else "N/A" end) (ID: \(.Owner.UserId // "" | if length > 0 then "****" + .[-4:] else "N/A" end))
> Creator ID: \(.Creator // "" | if length > 0 then "****" + .[-4:] else "N/A" end)
> Administrators: \(.AdminNames // [] | map(.[0:1] + "***") | join(", "))"'
> ```
>
> The raw API response flows through the pipe internally and never reaches shell stdout. Only `jq`'s output (with masked values and natural language keys) is captured by the execution framework. The following are **all prohibited**:
> - Running the CLI command **without** `| jq` pipe filtering — even for basic queries (the `Creator` field is always returned and sensitive)
> - **Two-step processing** — running the CLI command first to get raw output, then separately masking it. The raw JSON would appear in the execution transcript before masking is applied. The `| jq -r` MUST be part of the same single pipeline command
> - **Capturing raw output to shell variables** — e.g., `response=$(aliyun ...)` then `echo "$response" | jq ...`. The variable assignment captures raw data into the execution log
> - Output redirection (`> file.json`, `>> file.log`, `| tee file`)
> - Executing commands via shell scripts saved to disk (e.g., `ran-scripts/*.sh`)
> - **Embedding raw API response data in any script or code file** — e.g., writing a Python/shell script that contains raw JSON values as string literals, variables, or data structures (such as `ran_scripts/process_workspace_data.py`). All data processing must be done entirely within the `| jq -r` pipe; do NOT create intermediate processing scripts that contain raw data
> - Displaying raw JSON snippets in the conversation
> - **[MUST] Original API field names MUST NOT be used as output keys**: Even when values are masked, using original API field names (such as `UserId`, `UserName`, `UserKp`, `AdminNames`) as JSON keys or structured output key names in any output (conversation or files) is **prohibited**. Use natural language key names instead:
> - `UserId` / `Creator` → `Owner ID` or `Creator ID`
> - `UserName` → `Username`
> - `DisplayName` → `Display Name`
> - `AdminNames` → `Administrators`
>
> **Correct approach**: **EVERY** execution of `get-workspace` or `list-workspaces` must be a **single pipeline command** with `| jq -r` appended. The Agent must NEVER run the CLI command first and then process the output in a separate step — the raw JSON would appear in the execution transcript before masking is applied. All data extraction, masking, and formatting must happen inside the `jq` filter. If saving to a file, redirect the **jq output** (not the CLI output) using `> file.md` at the end of the pipeline. This rule applies to ALL queries — basic, verbose, and list.
>
> ```bash
> aliyun configure list
> ```
> Check the output for a valid profile (AK, STS, or OAuth identity).
>
> **If no valid profile exists, STOP here.**
> 1. Obtain credentials from [Alibaba Cloud Console](https://ram.console.aliyun.com/manage/ak)
> 2. Configure credentials **outside of this session** (via `aliyun configure` in terminal or environment variables in shell profile)
> 3. Return and re-run after `aliyun configure list` shows a valid profile
---
## RAM Permissions
See `references/ram-policies.md` for required permissions (including Policy JSON and instructions).
> **[MUST] Permission Failure Handling:** When any command or API call fails due to permission errors at any point during execution, follow this process:
> 1. Read `references/ram-policies.md` to get the full list of permissions required by this SKILL
> 2. Use `ram-permission-diagnose` skill to guide the user through requesting the necessary permissions
> 3. Pause and wait until the user confirms that the required permissions have been granted
---
## Parameter Confirmation
> **IMPORTANT: Parameter Confirmation** — Before executing any command or API call,
> ALL user-customizable parameters (e.g., RegionId, WorkspaceName, Description, EnvTypes, etc.)
> MUST be confirmed with the user. Do NOT assume or use default values without explicit user approval.
| Parameter | Required/Optional | Description | Example |
|-----------|-------------------|-------------|---------|
| `--region` | Required | Region ID (global parameter), **must be specified by the user**, do not use default values | `cn-hangzhou` |
| `--workspace-name` | Required | Workspace name: 3-23 characters, starts with a letter, may contain letters/digits/underscores, unique within the region | `myworkspace` |
| `--description` | Required | Workspace description, max 80 characters | `My AI workspace` |
| `--env-types` | Required | Environment types (list format): `prod` (simple mode) or `dev prod` (standard mode) | `prod` |
| `--display-name` | Optional | Display name, defaults to WorkspaceName | `My Workspace` |
| `--resource-group-id` | Optional | Resource group ID, uses default resource group if not specified | `rg-xxxxxxxx` |
> **Note**: Once `--resource-group-id` is set, it **cannot be modified via CLI/code**. To change it, use the console or recreate the workspace.
---
## Timeout Configuration
API calls support timeout configuration (in seconds):
**Option 1: Command-line parameters** (applies to the current command only):
- `--connect-timeout <seconds>` — Connection timeout
- `--read-timeout <seconds>` — I/O read timeout
**Option 2: Persistent configuration** (applies globally, written to current profile):
```bash
aliyun configure set --connect-timeout 10 --read-timeout 30
```
> Command-line parameters take precedence over persistent configuration. If not set, the CLI uses built-in defaults. When encountering `timeout` or `context deadline exceeded` errors, increase `--read-timeout` (e.g., 30-60 seconds).
---
## Core Workflow
> See `references/related-commands.md` for all CLI command templates and parameter details.
### Prerequisite: Region Selection and PAI Activation Check
> **[MUST] Do not use a default region**: The Agent must not assume or use a default region. It must explicitly ask the user which region to use.
>
> **[MUST] Check PAI activation on first use of a region**: After the user specifies a region (or the first time a region is used in a session), the Agent must call `list-products` to check whether PAI is activated in that region before executing any subsequent workspace operations.
#### Step 1: Confirm Region
Ask the user which region to use. If the user has not specified one, provide the list of common regions for selection (see the Common Region IDs table in `references/related-commands.md`). **Do not** automatically select a default region.
#### Step 2: Check PAI Activation Status
Use `aliyun aiworkspace list-products` to check whether PAI and its dependent products are activated in the user-specified region:
```bash
aliyun aiworkspace list-products \
--region <UserSpecifiedRegionId> \
--product-codes PAI_share \
--verbose true \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-pai-workspace-manage
```
#### Step 3: Handle Check Results
Inspect the returned `Products` array for the matching product entry:
> **Decision logic**:
>
> 1. **`IsPurchased == true`** → PAI is activated, proceed with subsequent workflows
> 2. **`IsPurchased == false`** → PAI is not activated, guide the user to activate:
> - Check the `HasPermissionToPurchase` field:
> - `true` → User has permission. Show the `PurchaseUrl` link and prompt the user to complete activation in the console before continuing
> - `false` → User lacks permission (requires the primary account or a RAM user with `pai:CreateOrder` permission). Inform the user to contact the primary account administrator
> - **Do not** proceed with creating/querying workspaces when PAI is not activated
### Workflow 1: Create Workspace (CreateWorkspace)
Use `aliyun aiworkspace create-workspace` to create a workspace. Required parameters: `--region`, `--workspace-name`, `--description`, `--env-types`. Simple mode uses `--env-types prod`, standard mode uses `--env-types dev prod`. Optionally add `--display-name` and `--resource-group-id`.
#### Step 1: Input Parameter Validation
> **[MUST] Parameter format validation**: Before calling the API, the Agent must validate user-provided parameters as follows. If validation fails, prompt the user to correct the input. **Do not** submit non-compliant parameters:
>
> | Parameter | Validation Rules | Example |
> |-----------|-----------------|---------|
> | `--workspace-name` | 3-23 characters, must start with a **letter**, may only contain letters, digits, and underscores (`_`). Hyphens (`-`), spaces, Chinese characters, and other special characters are not allowed | `my_workspace_01` |
> | `--description` | Max 80 characters, wrap with quotes if containing special characters | `"My AI workspace"` |
> | `--env-types` | Must be `prod` or `dev prod`, list format | `prod` |
> | `--display-name` | Optional, no strict format restrictions | `My Workspace` |
#### Step 2: Name Existence Check (check-then-act idempotency pattern)
> **[MUST] Idempotency guarantee**: The CreateWorkspace API does not support ClientToken, so idempotency is ensured via a check-then-act pattern. Before creating, you **must** call `list-workspaces --option CheckWorkspaceExists --workspace-name <name>` to check if the name already exists.
>
> Decision logic:
> - `TotalCount == 0` → Name is available, proceed to Step 3 to create
> - `TotalCount >= 1` → Name already exists, perform the following:
> 1. Extract the existing `WorkspaceId` from the returned `Workspaces[0]`
> 2. Call `get-workspace --workspace-id <id>` to get full details
> 3. Compare the existing workspace's key parameters (`EnvTypes`, `Description`, etc.) with the current request parameters
> 4. **Match** → Treat as already created, return the existing `WorkspaceId` directly, **do not recreate**
> 5. **Mismatch** → Inform the user that the name is already taken with a different configuration, ask the user to choose a different name
#### Step 3: Execute Creation
After parameter validation passes and the name does not exist, execute the `create-workspace` command. On success, a `WorkspaceId` is returned. If the creation returns a `WorkspaceNameAlreadyExists` error (concurrent scenario), handle it using the `TotalCount >= 1` logic from Step 2.
### Workflow 2: Get Workspace Details (GetWorkspace)
> **[MUST] Single workspace queries must use `get-workspace`**: When querying the details of **one** specific workspace, you **must** use `aliyun aiworkspace get-workspace --workspace-id <id>`. **Do not** use `list-workspaces --workspace-ids` as a substitute. `get-workspace` calls the GetWorkspace API and returns the complete details of a single workspace.
Only accepts `--workspace-id` (required) and `--verbose` (optional). The region is specified via the global `--region` parameter. A `Status` of `ENABLED` indicates the workspace is ready.
> **[MUST] `--verbose true` trigger rules**: `--verbose true` returns Owner (UserKp, UserId, UserName, DisplayName) and AdminNames (admin account list). The Agent must follow these rules:
>
> 1. **Trigger conditions** — When the user's request involves any of the following keywords, `--verbose true` **must** be appended when constructing the command (determined before calling the API, not dependent on API success):
> - Chinese keywords: 所有者, 拥有者, 创建者, 管理员, 负责人, 归属
> - English keywords: owner, admin, administrator, verbose
> - Field names: Owner, AdminNames
> 2. **When not triggered** — When the user only queries basic info (status, environment types, etc.), do not append `--verbose`
> 3. **Masking rules** — UserId/Creator: last 4 digits only (`****1234`); UserKp: omit entirely; UserName/DisplayName: first character only (`z***`); AdminNames entries: `u***@example.com`
> 4. **No raw sensitive data in stdout, execution logs, on disk, or in output** — **EVERY** execution of `get-workspace` (with or without `--verbose`) or `list-workspaces` must be a **single pipeline command** with `| jq -r` appended. The Agent must NEVER run the CLI command first and then mask the output separately — the raw JSON would appear in the execution transcript. No two-step processing, no variable capture (`response=$(aliyun ...)`), no intermediate scripts. All masking must happen inside the `jq` filter of the same pipeline. See the Sensitive Data Masking section and `references/related-commands.md` for templates
> **[MUST] 404 error handling**: When `get-workspace` returns `StatusCode: 404, Code: 100400027, Message: Workspace not exists`, the workspace ID does not exist. The Agent must **directly report to the user that the workspace does not exist**, including the original workspace-id specified by the user. **Do not** fall back to `list-workspaces` or other APIs to try to "find" the workspace after receiving a 404. **Do not** silently ignore the error. If the user subsequently provides a new workspace-id, the Agent must retry `get-workspace` with **the same parameters as the initial call** (including `--verbose true`, etc.).
### Workflow 3: List Workspaces (ListWorkspaces)
Use `aliyun aiworkspace list-workspaces` to list workspaces. Supports the following filter and sort parameters:
- `--workspace-name <name>` — Fuzzy match by name
- `--workspace-ids <id1,id2,...>` — **Batch query by ID list**, comma-separated (e.g., `--workspace-ids "123,456,789"`)
- `--status <STATUS>` — Filter by status, enum values (all uppercase): `ENABLED` | `INITIALIZING` | `FAILURE` | `DISABLED` | `FROZEN` | `UPDATING`
- `--sort-by <Field>` — Sort field (case-sensitive): `GmtCreateTime` (default) | `GmtModifiedTime`
- `--order <ORDER>` — Sort direction (all uppercase): `ASC` (default) | `DESC`
- `--page-number <n>` / `--page-size <n>` — Pagination parameters
- `--option GetResourceLimits` — Get resource limit information instead of workspace list
- `--option CheckWorkspaceExists` — Check if a workspace with the specified name already exists (pre-creation check, use with `--workspace-name`)
> **[MUST] API selection rules**: Use `get-workspace --workspace-id` (GetWorkspace API) for querying a **single** ID; use `list-workspaces --workspace-ids "id1,id2,..."` for querying **multiple** IDs (2 or more) in a single batch query (ListWorkspaces API). Do not call `get-workspace` individually for each ID.
>
> **[MUST] Batch query results are final**: The `Workspaces` array returned by `list-workspaces --workspace-ids` already contains complete information for each workspace (Status, EnvTypes, GmtCreateTime, etc.). **Do not** call `get-workspace` for any ID in the batch results to get additional details. If some IDs are not in the response, those IDs do not exist — report this to the user directly.
> **[MUST] Enum values are case-sensitive**: `--sort-by` must be `GmtCreateTime` or `GmtModifiedTime` (camelCase), `--order` must be `ASC` or `DESC` (all uppercase), `--status` must be all uppercase like `ENABLED`. Using incorrect casing (e.g., `desc`, `gmtCreateTime`, `enabled`) will cause API errors or unexpected results.
> **[MUST] ListWorkspaces sensitive field masking**: Each workspace object returned by `list-workspaces` **always** contains `Creator` (creator user ID) and `AdminNames` (admin account list) — **no `--verbose true` needed**. The Agent must mask these fields when displaying (`Creator`: last 4 digits only; `AdminNames`: first character + `***`). Do not output JSON containing the raw values, and do not save raw responses to files via redirection (`> file`) or scripts.
---
## Success Verification
| Verification Target | Method | Success Criteria |
|---------------------|--------|------------------|
| WorkspaceId returned | Parse create command response | `WorkspaceId` is not empty |
| Workspace status is normal | `get-workspace` command | `Status == "ENABLED"` |
| Visible in console | Log in to [PAI Console](https://pai.console.aliyun.com/) and verify manually | New workspace appears in the list |
> See `references/verification-method.md` for detailed verification methods
---
## Cleanup (Delete Workspace)
> **Warning**: Deleting a workspace is an **irreversible operation** that removes all resources within it. Proceed with caution.
>
> **Note**: Workspace deletion **cannot be performed directly via CLI** (the `aiworkspace` plugin does not currently support `delete-workspace`). Use the following methods:
> 1. **Console deletion**: Log in to [PAI Console](https://pai.console.aliyun.com/) -> Workspace List -> Select workspace -> Delete
> 2. **API call**: Use the `DELETE /api/v1/workspaces/{WorkspaceId}` endpoint (via SDK or direct HTTP call)
---
## Best Practices
1. **Naming conventions**: Use project names or team identifier prefixes for WorkspaceName, e.g., `nlp_prod`, `cv_dev` (note: hyphens are not supported, use underscores)
2. **Environment selection**: Use standard mode (`dev` + `prod`) for production projects to separate development and production resources
3. **Description**: Description should indicate the purpose, team, or project for easier management
4. **Region selection**: Choose the region closest to your data storage to minimize data transfer latency
5. **Resource group management**: Use different resource groups for multi-project scenarios to facilitate cost allocation and permission management
6. **DisplayName**: Use business-friendly names as the display name while using English identifiers for WorkspaceName
---
## Reference Documentation
| Document | Description |
|----------|-------------|
| [references/ram-policies.md](references/ram-policies.md) | RAM permission policies, Policy JSON, and instructions |
| [references/related-commands.md](references/related-commands.md) | Complete CLI command templates, parameter tables, enum values, and return fields |
| [references/verification-method.md](references/verification-method.md) | Verification steps and scripts |
| [references/acceptance-criteria.md](references/acceptance-criteria.md) | CLI command acceptance criteria (correct/incorrect patterns) |
| [references/cli-installation-guide.md](references/cli-installation-guide.md) | Aliyun CLI installation and configuration |
| [ListWorkspaces API Doc](https://help.aliyun.com/zh/pai/developer-reference/api-aiworkspace-2021-02-04-listworkspaces) | ListWorkspaces API reference |
| [CreateWorkspace API Doc](https://help.aliyun.com/zh/pai/developer-reference/api-aiworkspace-2021-02-04-createworkspace) | CreateWorkspace API reference |
| [GetWorkspace API Doc](https://help.aliyun.com/zh/pai/developer-reference/api-aiworkspace-2021-02-04-getworkspace) | GetWorkspace API reference |
| [ListProducts API Doc](https://help.aliyun.com/zh/pai/developer-reference/api-aiworkspace-2021-02-04-listproducts) | ListProducts API reference (product activation status check) |
FILE:references/acceptance-criteria.md
# Acceptance Criteria — alibabacloud-pai-workspace-manage
**Scenario**: Create, query, and list PAI workspaces
**Purpose**: Skill testing acceptance criteria to ensure CLI commands and parameter patterns are correct
---
# General Rules
## 1. Product Name
#### CORRECT
```
aliyun aiworkspace <action> ...
```
#### INCORRECT
```
aliyun AIWorkSpace CreateWorkspace ... # Traditional API format, not plugin mode
aliyun paiworkspace create-workspace ... # Incorrect product name
aliyun pai create-workspace ... # Incorrect product name
```
## 2. Action Format
#### CORRECT — kebab-case plugin mode
```
create-workspace | get-workspace | list-workspaces
```
#### INCORRECT
```
CreateWorkspace # PascalCase
createWorkspace # camelCase
```
## 3. Region Parameter
#### CORRECT — global parameter `--region`
```
--region cn-hangzhou
```
#### INCORRECT
```
--region-id cn-hangzhou # Non-existent parameter name
```
## 3a. Region Selection — Do Not Use Default Region
> **CRITICAL**: The Agent must not assume or use a default region. The user must explicitly specify the region.
#### CORRECT — Ask the user and use their specified region
```
Agent: "Please select a region (e.g., cn-hangzhou, cn-shanghai, cn-beijing)"
User: "cn-shanghai"
Agent: Uses --region cn-shanghai
```
#### INCORRECT — Automatically use a default region
```
# Prohibited: Auto-selecting cn-hangzhou or any default value when user has not specified a region
aliyun aiworkspace create-workspace --region cn-hangzhou ...
# Must ask the user which region to use first
```
## 3b. PAI Activation Check — Must Check on First Use of a Region
> **CRITICAL**: After the user specifies a region (or the first time a region is used in a session), the Agent must call `list-products` to check whether PAI is activated before executing any workspace operations.
#### CORRECT — Check activation status before executing operations
```
# Step 1: User specifies region
User: "Create a workspace in cn-shanghai"
# Step 2: Check PAI activation status
aliyun aiworkspace list-products --region cn-shanghai --product-codes PAI_share --verbose true --user-agent AlibabaCloud-Agent-Skills
# Step 3a: IsPurchased == true → Proceed with subsequent operations
aliyun aiworkspace create-workspace --region cn-shanghai ...
# Step 3b: IsPurchased == false, HasPermissionToPurchase == true → Guide user to activate
Agent: "PAI is not activated in this region. Please visit the following link to activate: <PurchaseUrl>"
# Step 3c: IsPurchased == false, HasPermissionToPurchase == false → Inform user
Agent: "PAI is not activated in this region, and the current account lacks permission to activate. Please contact the primary account administrator (requires primary account or pai:CreateOrder permission)"
```
#### INCORRECT — Skip activation check and execute operations directly
```
# Prohibited: Creating/querying workspaces without checking PAI activation status
User: "Create a workspace in cn-shanghai"
aliyun aiworkspace create-workspace --region cn-shanghai ...
# Must call list-products to check if PAI is activated first
```
#### INCORRECT — Continue executing operations when PAI is not activated
```
# Prohibited: Continuing operations after list-products returns IsPurchased == false
aliyun aiworkspace list-products --region cn-shanghai --product-codes PAI_share --verbose true ...
# Returns: IsPurchased: false
aliyun aiworkspace create-workspace --region cn-shanghai ...
# Prohibited: Must wait for user to confirm activation before continuing
```
## 4. user-agent Identifier
Every `aliyun` command **must** include:
```
--user-agent AlibabaCloud-Agent-Skills
```
---
# CreateWorkspace Acceptance
## 5. EnvTypes Format — list format, not JSON array
#### CORRECT
```
--env-types prod # Simple mode
--env-types dev prod # Standard mode
```
#### INCORRECT
```
--env-types '["prod"]' # JSON array format
--env-types '["dev","prod"]' # JSON array format
--env-types "prod" # Unnecessary quotes
```
## 6. Parameter Names — kebab-case
#### CORRECT
```
--workspace-name | --description | --env-types | --display-name | --resource-group-id
```
#### INCORRECT
```
--WorkspaceName | --workspaceName | --EnvTypes | --env_types
```
## 7. WorkspaceName Value Rules — Input Validation
> **CRITICAL**: The Agent must validate the WorkspaceName format before calling the API. If validation fails, prompt the user to correct the input. Do not submit non-compliant parameters.
**Rules**: 3-23 characters, must start with a letter, may only contain letters, digits, and underscores (`_`).
#### CORRECT
```
myworkspace | my_workspace | myWorkspace123 | abc
```
#### INCORRECT — Agent must reject the following inputs and prompt user to correct
```
123workspace # Starts with a digit
_myworkspace # Starts with an underscore
my-workspace # Contains hyphen (not allowed)
ab # Less than 3 characters
averylongworkspacename123 # Exceeds 23 characters
my workspace # Contains space (not allowed)
test@ws! # Contains special characters (not allowed)
```
## 8. Description Length — Input Validation
> The Agent must check that Description length does not exceed 80 characters before calling the API. If it exceeds, prompt the user to shorten it. Wrap parameter values with quotes when they contain special characters.
## 8a. Pre-creation Name Existence Check
> **CRITICAL**: Before creating a workspace, you **must** call `list-workspaces --option CheckWorkspaceExists --workspace-name <name>` to check if the name already exists.
#### CORRECT — Check name before creating
```
# Step 1: Check name
aliyun aiworkspace list-workspaces --region cn-hangzhou --option CheckWorkspaceExists --workspace-name myworkspace --user-agent AlibabaCloud-Agent-Skills
# Returns TotalCount == 0 → Name is available
# Step 2: Create
aliyun aiworkspace create-workspace --region cn-hangzhou --workspace-name myworkspace ...
```
#### INCORRECT — Create without checking
```
# Prohibited: Skipping name check and creating directly
aliyun aiworkspace create-workspace --region cn-hangzhou --workspace-name myworkspace ...
```
## 9. Success Response
```json
{"RequestId": "xxx", "WorkspaceId": "1234"}
```
Verification: `WorkspaceId` is not empty.
## 10. Common Errors
| Error Code | Cause | Solution |
|------------|-------|----------|
| `InvalidParameter` | Incorrect parameter format | Check WorkspaceName format and length |
| `WorkspaceNameAlreadyExists` | Name already exists | Handle via idempotency rules (see Rule 10a) |
| `Forbidden.RAM` | Insufficient permissions | Grant required `paiworkspace:*` permissions and retry |
| `InvalidAccessKeyId` | Invalid AK | Reconfigure credentials |
## 10a. Idempotency Guarantee (check-then-act pattern)
> **CRITICAL**: The CreateWorkspace API does not support ClientToken. The Agent must ensure idempotency via the check-then-act pattern to avoid duplicate creation.
#### CORRECT — Reuse when name exists and configuration matches
```
# Step 1: CheckWorkspaceExists returns TotalCount >= 1
# Step 2: Call get-workspace to get existing workspace details
# Step 3: Compare EnvTypes, Description, and other parameters — they match the current request
# Step 4: Return existing WorkspaceId directly, do not recreate
Agent behavior: "Workspace 'myworkspace' already exists (ID: 1234), configuration matches, no need to recreate"
```
#### CORRECT — Prompt when name exists but configuration differs
```
Agent behavior: "Name 'myworkspace' is already taken (ID: 1234), but EnvTypes differ (existing: prod, requested: dev prod). Please choose a different name"
```
#### CORRECT — Received WorkspaceNameAlreadyExists error during creation
```
# Concurrent scenario: Did not exist during check, conflict during creation
# Agent should handle using TotalCount >= 1 logic: query existing workspace and compare parameters
```
#### INCORRECT — Create again directly when name already exists
```
# Prohibited: Calling create-workspace without checking, causing duplicate creation or errors
```
---
# GetWorkspace Acceptance
## 11. API Selection Rules — Single ID Must Use GetWorkspace
> **CRITICAL**: When querying a **single** workspace, you **must** use `get-workspace --workspace-id` (GetWorkspace API). **Do not** use `list-workspaces --workspace-ids` as a substitute. `list-workspaces --workspace-ids` is only for querying **multiple** IDs (2 or more) in batch scenarios.
#### CORRECT — Single ID uses get-workspace
```
aliyun aiworkspace get-workspace --workspace-id <WorkspaceId> --user-agent AlibabaCloud-Agent-Skills
```
#### INCORRECT — Single ID uses list-workspaces
```
aliyun aiworkspace list-workspaces --workspace-ids "<WorkspaceId>" --user-agent AlibabaCloud-Agent-Skills
# Prohibited: Single ID queries must not use list-workspaces --workspace-ids instead of get-workspace
```
## 12. Parameter Constraints
Only accepts `--workspace-id` (required) and `--verbose` (optional). No other action-specific parameters.
#### CORRECT
```
--workspace-id 1234
--workspace-id 1234 --verbose true
```
#### INCORRECT
```
--region-id cn-hangzhou --workspace-id 1234 # --region-id parameter does not exist
--WorkspaceId 1234 # PascalCase format
--workspace_id 1234 # Underscore format
```
## 13. Success Response
`Status` of `ENABLED` indicates the workspace is operational. `WorkspaceId` should match the query parameter.
## 13a. 404 Error Handling — Workspace Does Not Exist
> **CRITICAL**: When `get-workspace` returns `StatusCode: 404, Code: 100400027, Message: Workspace not exists`, the Agent must directly report to the user that the workspace ID does not exist. Do not fall back to `list-workspaces` or other APIs to try to find the workspace after receiving a 404.
>
> **Parameter preservation**: If the user subsequently provides a new workspace-id, the Agent must retry `get-workspace` with **the same parameters as the initial call** (including `--verbose true`, etc.).
#### CORRECT — Report not found directly after receiving 404
```
Call: aliyun aiworkspace get-workspace --workspace-id <ID> --verbose true --user-agent AlibabaCloud-Agent-Skills
Result: 404 Workspace not exists <ID>
Agent behavior: Report to user "Workspace <ID> does not exist"
```
#### CORRECT — Preserve original parameters when user provides a new ID (including --verbose true)
```
# After initial call returns 404, user provides a new workspace-id
# Agent must retry get-workspace with the same parameters as the initial call
Call: aliyun aiworkspace get-workspace --workspace-id <NewID> --verbose true --user-agent AlibabaCloud-Agent-Skills
# --verbose true and other parameters must be preserved, must not be dropped when ID changes
```
#### INCORRECT — Lose original parameters after user corrects ID
```
# Initial call: get-workspace --workspace-id <ID> --verbose true → 404
# After user correction: get-workspace --workspace-id <NewID> → 200 (missing --verbose true)
# Prohibited: User's original request included owner/admin query intent, --verbose true must be preserved after ID correction
```
#### INCORRECT — Fall back to other APIs after receiving 404
```
Call: aliyun aiworkspace get-workspace --workspace-id <ID> ... → 404
Then: aliyun aiworkspace list-workspaces --region cn-hangzhou ... → Lists all workspaces
# Prohibited: Must not use ListWorkspaces to try to find the workspace after GetWorkspace 404
```
## 13b. `--verbose true` Trigger Rules and Sensitive Data Masking
> **CRITICAL**: `--verbose true` returns Owner (containing UserKp, UserId, UserName, DisplayName) and AdminNames, which contain PII. The Agent must correctly identify trigger conditions and **mask all sensitive data while prohibiting raw JSON output**.
#### Trigger Conditions
When the user's request involves any of the following keywords, `--verbose true` **must** be appended when constructing the command (determined before calling the API, not dependent on API success):
- Chinese keywords: 所有者, 拥有者, 创建者, 管理员, 负责人, 归属
- English keywords: owner, admin, administrator, verbose
- Field names: Owner, AdminNames
#### Output Format Requirements
- **Do not** output raw JSON containing `"UserId"`, `"UserName"`, `"UserKp"`, or `"AdminNames"` key names in the conversation or files
- **Must** parse the API-returned JSON, mask sensitive values, then present in natural language or table format
- The `Creator` field (always returned) also contains a user ID and must be masked when displayed (last 4 digits only)
#### CORRECT — Use --verbose true and display with masking when user requests owner/admin info
```bash
User: "Show the owner and admin info for workspace <ID>"
# Must pipe through jq -r to prevent raw data from reaching stdout/execution logs
aliyun aiworkspace get-workspace \
--workspace-id <ID> \
--verbose true \
--region <RegionId> \
--user-agent AlibabaCloud-Agent-Skills \
| jq -r '"Workspace: \(.WorkspaceName) (ID: \(.WorkspaceId))
Status: \(.Status)
Owner: \(.Owner.UserName // "" | if length > 0 then .[0:1] + "***" else "N/A" end) (ID: \(.Owner.UserId // "" | if length > 0 then "****" + .[-4:] else "N/A" end))
Creator ID: \(.Creator // "" | if length > 0 then "****" + .[-4:] else "N/A" end)
Administrators: \(.AdminNames // [] | map(.[0:1] + "***") | join(", "))"'
# Output (natural language, only masked values):
# Workspace: myworkspace (ID: 12345)
# Status: ENABLED
# Owner: z*** (ID: ****7890)
# Creator ID: ****7890
# Administrators: a***, b***
```
#### CORRECT — Do not add --verbose when user does not request Owner/Admin (but still pipe through jq)
```bash
User: "Check the status of workspace <ID>"
# Even basic queries return Creator (sensitive), so | jq -r is always required
aliyun aiworkspace get-workspace --workspace-id <ID> --region <RegionId> \
--user-agent AlibabaCloud-Agent-Skills \
| jq -r '"Workspace: \(.WorkspaceName) (ID: \(.WorkspaceId))
Status: \(.Status)
Creator ID: \(.Creator // "" | if length > 0 then "****" + .[-4:] else "N/A" end)"'
```
#### INCORRECT — User requested owner/admin but --verbose true was not added
```
User: "Show the owner and admins of workspace <ID>"
Call: aliyun aiworkspace get-workspace --workspace-id <ID> --user-agent AlibabaCloud-Agent-Skills
# Prohibited: User explicitly requested owner/admin, --verbose true must be appended
```
#### INCORRECT — Output raw JSON format (using original key names is prohibited even if values are masked)
```
# Prohibited: Must not output any fields from the Owner object as JSON key-value pairs
# Prohibited format example: "<SensitiveKeyName>": "<AnyValue>" (e.g., Id, Name fields within Owner)
# Must display in natural language: Owner: z*** (ID: ****7890)
```
#### INCORRECT — Display complete raw values
```
# Prohibited: Must not display full usernames, full user IDs, full email addresses, or other PII
# All sensitive values must be masked before display
```
#### INCORRECT — Values are masked but original API field names are still used as key names
```
# Prohibited: Even if values are masked, original field names (e.g., UserId, UserName) must not be used as JSON keys
# The following format will still trigger security detection because it contains original key name patterns:
# {"Owner": {"UserId": "****5714", "UserName": "r***"}}
#
# Correct approach: Use natural language key names + plain text/Markdown format
# Owner: r*** (ID: ****5714)
```
#### INCORRECT — Execute CLI command without pipe filtering (execution log leakage)
```bash
# MOST CRITICAL PROHIBITION: The execution framework logs ALL command stdout to
# ran-scripts/executed-actions.log. Running the CLI command without | jq -r pipe filtering
# causes the raw API response (containing unmasked UserId, UserKp, UserName, AdminNames)
# to be captured in this centralized log file.
aliyun aiworkspace get-workspace --workspace-id <ID> --verbose true --user-agent AlibabaCloud-Agent-Skills
# → stdout contains raw JSON: {"Owner": {"UserId": "1095312831785714", "UserKp": "1095312831785714", "UserName": "release_pai_steed_00_testcloud_com", ...}}
# → execution framework captures this to ran-scripts/executed-actions.log
# → VIOLATION: unmasked sensitive data persisted to disk
#
# Correct approach: Append | jq -r with masking filter (see CORRECT example above)
```
#### INCORRECT — Two-step processing: run CLI first, then mask separately (execution transcript leakage)
```bash
# Prohibited: Running the CLI command first and then masking the output in a separate step.
# The raw JSON appears in the execution transcript at Step 1, before masking is applied at Step 2.
# Even if the final output file is correctly masked, the execution log has already leaked the raw data.
#
# Step 1 (LEAKS raw data to execution transcript):
aliyun aiworkspace get-workspace --workspace-id 584524 --verbose true --user-agent AlibabaCloud-Agent-Skills
# → execution log line 242: {"Creator": "1095312831785714", "Owner": {"UserId": "1095312831785714", ...}}
#
# Step 2 (Agent masks data and writes output file):
# → workspace_584524_audit_report.md correctly shows "****5714"
# → But the raw data already appeared in Step 1's execution transcript — VIOLATION
#
# Also prohibited: Capturing raw output to a shell variable first:
response=$(aliyun aiworkspace get-workspace --workspace-id 584524 --verbose true ...)
# → The variable assignment step exposes raw data in the execution log
echo "$response" | jq -r '...'
#
# Correct approach: Single pipeline command with | jq -r (see CORRECT example above)
# aliyun ... --verbose true | jq -r '"Owner: ..."'
```
#### INCORRECT — Save raw API response to any file
```bash
# Prohibited: All of the following will cause raw sensitive data to be written to disk
aliyun aiworkspace get-workspace --workspace-id <ID> --verbose true > output.json
aliyun aiworkspace get-workspace --workspace-id <ID> --verbose true > result.log
aliyun aiworkspace get-workspace --workspace-id <ID> --verbose true | tee output.txt
```
#### INCORRECT — Execute sensitive commands via shell scripts (script log leakage)
```bash
# Prohibited: Writing CLI commands into a shell script file and executing it.
# The execution framework captures script stdout to .log files (e.g., ran-scripts/get_workspace_584524.log).
#
# Example of PROHIBITED pattern:
# Step 1: Agent writes ran-scripts/get_workspace_584524.sh
# Step 2: Agent executes: bash ran-scripts/get_workspace_584524.sh
# Step 3: Framework captures stdout to ran-scripts/get_workspace_584524.log
# → Log file contains: "UserId": "1095312831785714", "UserName": "release_pai_steed_00_testcloud_com"
#
# Correct approach: Append | jq -r with masking filter
```
#### INCORRECT — Embed raw API response data in processing scripts (script data leakage)
```python
# Prohibited: Creating a Python/shell script that contains raw API response data
# as hardcoded string literals, variables, or data structures.
#
# Example of PROHIBITED pattern:
# Agent creates ran_scripts/process_workspace_data.py containing:
# data = {
# "Creator": "1095312831785714", # line 10: raw Creator ID
# "Owner": {
# "DisplayName": "release_pai_steed_00...", # line 24: raw DisplayName
# "UserId": "1095312831785714", # line 25: raw UserId
# "UserKp": "1095312831785714", # line 26: raw UserKp
# "UserName": "release_pai_steed_00..." # line 27: raw UserName
# }
# }
#
# Even if the script then masks the values before printing, the raw data is already
# persisted in the .py file on disk, violating the security requirement.
#
# Correct approach: All data processing must be done within the | jq -r pipe.
# Do NOT create intermediate scripts or files that contain raw API response data.
```
---
# ListWorkspaces Acceptance
## 14. Batch Query (--workspace-ids) — Must Use ListWorkspaces for Multi-ID (2+) Queries
> **CRITICAL**: When the user provides **multiple** workspace IDs (2 or more), you **must** use `list-workspaces --workspace-ids` for a single batch query. **Do not** call `get-workspace` individually for each ID. Single ID queries **must** use `get-workspace` (see Rule 11).
>
> **CRITICAL**: Results returned by `list-workspaces --workspace-ids` already contain complete information for each workspace. **Do not** call `get-workspace` for any ID in the batch results to get additional details. If a requested ID is not in the results, that ID does not exist — report it directly.
#### CORRECT — Use --workspace-ids for batch query, results are final
```
aliyun aiworkspace list-workspaces --workspace-ids "10234,10567,10891" --region cn-hangzhou --user-agent AlibabaCloud-Agent-Skills
# Use results directly, do not call any other APIs
```
#### INCORRECT — Call get-workspace individually (instead of batch query)
```
aliyun aiworkspace get-workspace --workspace-id 10234 ...
aliyun aiworkspace get-workspace --workspace-id 10567 ...
aliyun aiworkspace get-workspace --workspace-id 10891 ...
# Prohibited: Must not call get-workspace individually for multi-ID scenarios
```
#### INCORRECT — Call get-workspace individually after batch query (additional detail queries)
```
# Step 1: Batch query (correct)
aliyun aiworkspace list-workspaces --workspace-ids "10234,10567,10891" ...
# Step 2: Individual detail queries (prohibited!)
aliyun aiworkspace get-workspace --workspace-id 10234 ...
aliyun aiworkspace get-workspace --workspace-id 10567 ...
aliyun aiworkspace get-workspace --workspace-id 10891 ...
# Prohibited: Batch query results already contain complete information, do not add get-workspace calls
```
#### INCORRECT — list-workspaces without --workspace-ids filter
```
aliyun aiworkspace list-workspaces --region cn-hangzhou ...
# Prohibited: When user provides specific ID list, do not use unfiltered full listing
```
## 15. Enum Values (Case-Sensitive — Incorrect Casing Will Cause API Errors)
> **CRITICAL**: The following enum values must be used with exactly the specified casing. The API does not auto-convert casing — using incorrect format will cause request failures or unexpected results. When encountering sort/filter errors, the Agent must check enum value casing and must not skip these parameters.
| Parameter | CORRECT | INCORRECT |
|-----------|---------|-----------|
| `--status` | `ENABLED`, `DISABLED`, `FROZEN` | `enabled`, `Enabled` |
| `--sort-by` | `GmtCreateTime`, `GmtModifiedTime` | `createTime`, `gmtCreateTime`, `gmt_create_time` |
| `--order` | `ASC`, `DESC` | `asc`, `desc`, `Desc` |
| `--option` | `GetWorkspaces`, `GetResourceLimits`, `CheckWorkspaceExists` | `getWorkspaces`, `get-workspaces`, `checkWorkspaceExists` |
## 16. Return Structure
- `--option GetWorkspaces` (default): Returns `Workspaces` array + `TotalCount`
- `--option GetResourceLimits`: Returns `ResourceLimits` object
## 17. ListWorkspaces Sensitive Field Masking
> **CRITICAL**: Each workspace object returned by `list-workspaces` **always** contains `Creator` (creator user ID) and `AdminNames` (admin account list) — **no `--verbose true` needed**. Masking rules are the same as GetWorkspace (see Rule 13b).
#### CORRECT — Display ListWorkspaces results with masking
```
Workspace list:
- myworkspace (ID: 10234) Status: ENABLED, Creator: ****7890, Admin: a***@example.com
- testworkspace (ID: 10567) Status: ENABLED, Creator: ****3456, Admin: b***@example.com
```
#### INCORRECT — Directly output or save raw JSON from list-workspaces
```bash
# Prohibited: Must not execute list-workspaces as a standalone shell command — the execution framework
# captures ALL command stdout to ran-scripts/executed-actions.log, leaking raw Creator and AdminNames values
aliyun aiworkspace list-workspaces --region cn-hangzhou --user-agent AlibabaCloud-Agent-Skills
# Also prohibited: redirecting or saving to files
aliyun aiworkspace list-workspaces --region cn-hangzhou > workspaces.json
# Correct approach: Append | jq -r with masking filter, display in natural language
```
FILE:references/cli-installation-guide.md
# Aliyun CLI Installation & Configuration Guide
Complete guide for installing and configuring Aliyun CLI.
> **Aliyun CLI 3.3.3+**: Supports installing and using all published Alibaba Cloud product plugins. Make sure to upgrade to 3.3.3 or later for full plugin ecosystem coverage.
## Installation
### macOS
**Using Homebrew (Recommended)**
```bash
brew install aliyun-cli
# Upgrade to latest
brew upgrade aliyun-cli
# Verify version (>= 3.3.3)
aliyun version
```
**Using Binary**
```bash
# Download
wget https://aliyuncli.alicdn.com/aliyun-cli-macosx-latest-amd64.tgz
# Extract
tar -xzf aliyun-cli-macosx-latest-amd64.tgz
# Move to PATH
sudo mv aliyun /usr/local/bin/
# Verify
aliyun version
```
### Linux
**Debian/Ubuntu**
```bash
# Download
wget https://aliyuncli.alicdn.com/aliyun-cli-linux-latest-amd64.tgz
# Extract and install
tar -xzf aliyun-cli-linux-latest-amd64.tgz
sudo mv aliyun /usr/local/bin/
# Verify
aliyun version
```
**CentOS/RHEL**
```bash
# Download
wget https://aliyuncli.alicdn.com/aliyun-cli-linux-latest-amd64.tgz
# Extract and install
tar -xzf aliyun-cli-linux-latest-amd64.tgz
sudo mv aliyun /usr/local/bin/
# Verify
aliyun version
```
**ARM64 Architecture**
```bash
# Download ARM64 version
wget https://aliyuncli.alicdn.com/aliyun-cli-linux-latest-arm64.tgz
# Extract and install
tar -xzf aliyun-cli-linux-latest-arm64.tgz
sudo mv aliyun /usr/local/bin/
```
### Windows
**Using Binary**
1. Download from: https://aliyuncli.alicdn.com/aliyun-cli-windows-latest-amd64.zip
2. Extract the ZIP file
3. Add the directory to your PATH environment variable
4. Open new Command Prompt or PowerShell
5. Verify: `aliyun version`
**Using PowerShell**
```powershell
# Download
Invoke-WebRequest -Uri "https://aliyuncli.alicdn.com/aliyun-cli-windows-latest-amd64.zip" -OutFile "aliyun-cli.zip"
# Extract
Expand-Archive -Path aliyun-cli.zip -DestinationPath C:\aliyun-cli
# Add to PATH (requires admin privileges)
$env:Path += ";C:\aliyun-cli"
[Environment]::SetEnvironmentVariable("Path", $env:Path, [System.EnvironmentVariableTarget]::Machine)
# Verify
aliyun version
```
## Configuration
### Quick Start
```bash
aliyun configure set \
--mode AK \
--access-key-id <your-access-key-id> \
--access-key-secret <your-access-key-secret> \
--region cn-hangzhou
```
All `aliyun configure` commands support non-interactive flags, which is the recommended approach —
it works in scripts, CI/CD pipelines, and agent-driven automation without hanging on stdin prompts.
**Where to Get Access Keys**
1. Log in to Aliyun Console: https://ram.console.aliyun.com/
2. Navigate to: AccessKey Management
3. Create a new AccessKey pair
4. Save the secret immediately — it's only shown once
### Configuration Modes
Aliyun CLI supports 6 authentication modes. All examples below use non-interactive flags.
#### 1. AK Mode (Access Key)
Most common mode for personal accounts and scripts.
```bash
aliyun configure set \
--mode AK \
--access-key-id LTAI5tXXXXXXXX \
--access-key-secret 8dXXXXXXXXXXXXXXXXXXXXXXXX \
--region cn-hangzhou
```
Configuration is stored in `~/.aliyun/config.json`:
```json
{
"current": "default",
"profiles": [
{
"name": "default",
"mode": "AK",
"access_key_id": "LTAI5tXXXXXXXX",
"access_key_secret": "8dXXXXXXXXXXXXXXXXXXXXXXXX",
"region_id": "cn-hangzhou",
"output_format": "json",
"language": "en"
}
]
}
```
#### 2. StsToken Mode (Temporary Credentials)
For short-lived access (tokens expire in 1-12 hours).
```bash
aliyun configure set \
--mode StsToken \
--access-key-id LTAI5tXXXXXXXX \
--access-key-secret 8dXXXXXXXXXXXXXXXXXXXXXXXX \
--sts-token v1.0:XXXXXXXXXXXXXXXX \
--region cn-hangzhou
```
Use cases: CI/CD pipelines, temporary access for external contractors, cross-account access.
#### 3. RamRoleArn Mode (Assume RAM Role)
Assume a RAM role for elevated or cross-account access.
```bash
aliyun configure set \
--mode RamRoleArn \
--access-key-id LTAI5tXXXXXXXX \
--access-key-secret 8dXXXXXXXXXXXXXXXXXXXXXXXX \
--ram-role-arn acs:ram::123456789012:role/AdminRole \
--role-session-name my-session \
--region cn-hangzhou
```
Use cases: cross-account resource access, temporary elevated privileges, role-based access control.
#### 4. EcsRamRole Mode (ECS Instance RAM Role)
Use the RAM role attached to an ECS instance — no credentials needed.
```bash
aliyun configure set \
--mode EcsRamRole \
--ram-role-name MyEcsRole \
--region cn-hangzhou
```
Requirements: must be running on an ECS instance with a RAM role attached.
Use cases: scripts and automation running on ECS instances.
#### 5. RsaKeyPair Mode (RSA Key Pair)
Use RSA key pair for authentication (generate key pair in Aliyun Console first).
```bash
aliyun configure set \
--mode RsaKeyPair \
--private-key /path/to/private-key.pem \
--key-pair-name my-key-pair \
--region cn-hangzhou
```
#### 6. RamRoleArnWithEcs Mode (ECS + RAM Role)
Combine ECS instance role with RAM role assumption for cross-account access from ECS.
```bash
aliyun configure set \
--mode RamRoleArnWithEcs \
--ram-role-name MyEcsRole \
--ram-role-arn acs:ram::123456789012:role/TargetRole \
--role-session-name my-session \
--region cn-hangzhou
```
### Environment Variables
**Highest priority** - overrides config file
**Access Key Mode**
```bash
export ALIBABA_CLOUD_ACCESS_KEY_ID=your_access_key_id
export ALIBABA_CLOUD_ACCESS_KEY_SECRET=your_access_key_secret
export ALIBABA_CLOUD_REGION_ID=cn-hangzhou
```
**STS Token Mode**
```bash
export ALIBABA_CLOUD_ACCESS_KEY_ID=your_access_key_id
export ALIBABA_CLOUD_ACCESS_KEY_SECRET=your_access_key_secret
export ALIBABA_CLOUD_SECURITY_TOKEN=your_sts_token
export ALIBABA_CLOUD_REGION_ID=cn-hangzhou
```
**ECS RAM Role Mode**
```bash
export ALIBABA_CLOUD_ECS_METADATA=role_name
```
**Use Case**:
- CI/CD pipelines
- Docker containers
- Temporary credential override
### Managing Multiple Profiles
**Create Named Profiles**
```bash
aliyun configure set --profile projectA \
--mode AK \
--access-key-id LTAI5tAAAAAAAA \
--access-key-secret 8dAAAAAAAAAAAAAAAAAAAAAAAA \
--region cn-hangzhou
aliyun configure set --profile projectB \
--mode AK \
--access-key-id LTAI5tBBBBBBBB \
--access-key-secret 8dBBBBBBBBBBBBBBBBBBBBBBBB \
--region cn-shanghai
```
**Use Specific Profile**
```bash
aliyun ecs describe-instances --profile projectA
export ALIBABA_CLOUD_PROFILE=projectA
aliyun ecs describe-instances # Uses projectA
```
**List and Switch Profiles**
```bash
aliyun configure list # List all profiles
aliyun configure set --current projectA # Switch default profile
```
### Credential Priority
Credentials are loaded in this order (first found wins):
1. **Command-line flag**: `--profile <name>`
2. **Environment variable**: `ALIBABA_CLOUD_PROFILE`
3. **Environment credentials**: `ALIBABA_CLOUD_ACCESS_KEY_ID`, etc.
4. **Configuration file**: `~/.aliyun/config.json` (current profile)
5. **ECS Instance RAM Role**: If running on ECS with attached role
## Verification
### Test Authentication
```bash
# Basic test - list regions
aliyun ecs describe-regions
# Expected output: JSON array of regions
```
**If successful**, you'll see:
```json
{
"Regions": {
"Region": [
{
"RegionId": "cn-hangzhou",
"RegionEndpoint": "ecs.cn-hangzhou.aliyuncs.com",
"LocalName": "华东 1(杭州)"
},
...
]
},
"RequestId": "..."
}
```
**If failed**, you'll see error messages:
- `InvalidAccessKeyId.NotFound` - Wrong Access Key ID
- `SignatureDoesNotMatch` - Wrong Access Key Secret
- `InvalidSecurityToken.Expired` - STS token expired (for StsToken mode)
- `Forbidden.RAM` - Insufficient permissions
### Debug Configuration
```bash
# Show current configuration
aliyun configure get
# Test with debug logging
aliyun ecs describe-regions --log-level=debug
# Check credential provider
aliyun configure get mode
```
## Security Best Practices
### 1. Use RAM Users (Not Root Account)
❌ **Don't**: Use Aliyun root account credentials
✅ **Do**: Create RAM users with specific permissions
```bash
# Create RAM user in console
# Attach only necessary policies
# Use RAM user's access keys
```
### 2. Principle of Least Privilege
Grant only the minimum permissions needed:
```bash
# Example: Read-only ECS access
# Attach policy: AliyunECSReadOnlyAccess
```
### 3. Rotate Access Keys Regularly
```bash
# Create new access key in RAM Console, then update configuration
aliyun configure set --access-key-id NEW_KEY --access-key-secret NEW_SECRET
# Delete old access key from console
```
### 4. Use STS Tokens for Temporary Access
```bash
aliyun configure set --mode StsToken \
--access-key-id XXXX --access-key-secret XXXX \
--sts-token XXXX --region cn-hangzhou
```
### 5. Use ECS RAM Roles When Possible
```bash
aliyun configure set --mode EcsRamRole --ram-role-name MyRole --region cn-hangzhou
```
### 6. Never Commit Credentials
```bash
# Add to .gitignore
echo "~/.aliyun/config.json" >> .gitignore
# Use environment variables in CI/CD instead
```
### 7. Secure Config File
```bash
# Restrict permissions
chmod 600 ~/.aliyun/config.json
```
## Troubleshooting
### Issue: Command Not Found
```bash
# Check installation
which aliyun
# Check PATH
echo $PATH
# Reinstall or add to PATH
```
### Issue: Authentication Failed
```bash
# Verify configuration
aliyun configure get
# Test with debug
aliyun ecs describe-regions --log-level=debug
# Check credentials in console
# Verify access key is active
```
### Issue: Permission Denied
```bash
# Error: Forbidden.RAM
# Check RAM user permissions
# Attach necessary policies in RAM console
# Example: AliyunECSFullAccess for ECS operations
```
### Issue: STS Token Expired
```bash
# Error: InvalidSecurityToken.Expired
# Reconfigure with new token
aliyun configure set --mode StsToken \
--access-key-id XXXX --access-key-secret XXXX \
--sts-token NEW_TOKEN --region cn-hangzhou
```
### Issue: Wrong Region
```bash
# Some resources may not exist in the specified region
# Check available regions
aliyun ecs describe-regions
# Update default region
aliyun configure set region cn-shanghai
```
## Advanced Configuration
### Custom Endpoint
```bash
# Use custom or private endpoint
export ALIBABA_CLOUD_ECS_ENDPOINT=ecs-vpc.cn-hangzhou.aliyuncs.com
```
### Proxy Settings
```bash
# HTTP proxy
export HTTP_PROXY=http://proxy.example.com:8080
export HTTPS_PROXY=http://proxy.example.com:8080
# No proxy for specific domains
export NO_PROXY=localhost,127.0.0.1,.aliyuncs.com
```
### Timeout Settings
```bash
# Connection timeout (default: 10s)
export ALIBABA_CLOUD_CONNECT_TIMEOUT=30
# Read timeout (default: 10s)
export ALIBABA_CLOUD_READ_TIMEOUT=30
```
## Next Steps
After installation and configuration:
1. **Install plugins** for services you need (v3.3.3+ supports all published product plugins):
```bash
aliyun plugin install --names ecs vpc rds
# List all available plugins
aliyun plugin list-remote
```
2. **Explore commands**:
```bash
aliyun ecs --help
aliyun fc --help
```
3. **Read documentation**:
- [Command Syntax Guide](./command-syntax.md)
- [Global Flags Reference](./global-flags.md)
- [Common Scenarios](./common-scenarios.md)
## References
- Official Documentation: https://help.aliyun.com/zh/cli/
- RAM Console: https://ram.console.aliyun.com/
- Access Key Management: https://ram.console.aliyun.com/manage/ak
- Plugin Repository: https://github.com/aliyun/aliyun-cli
FILE:references/ram-policies.md
# RAM Policies — PAI Workspace Management
## Overview
The following RAM permissions are required to execute this Skill. Following the principle of least privilege, only permissions needed for creating, querying, and listing workspaces are granted.
## Permission List
| Product | RAM Action | Resource Scope | Description |
|---------|------------|----------------|-------------|
| PAI AIWorkSpace | `paiworkspace:CreateWorkspace` | `*` | Create PAI workspace |
| PAI AIWorkSpace | `paiworkspace:GetWorkspace` | `*` | Query workspace details (for verification) |
| PAI AIWorkSpace | `paiworkspace:ListWorkspaces` | `*` | List workspaces |
## RAM Policy JSON
Attach the following policy to the RAM user or RAM role:
```json
{
"Version": "1",
"Statement": [
{
"Effect": "Allow",
"Action": [
"paiworkspace:CreateWorkspace",
"paiworkspace:GetWorkspace",
"paiworkspace:ListWorkspaces"
],
"Resource": "*"
}
]
}
```
## Action Details
| Action | Access Level | Required |
|--------|-------------|----------|
| `paiworkspace:CreateWorkspace` | Write | Required |
| `paiworkspace:GetWorkspace` | Read | Recommended (for post-creation verification) |
| `paiworkspace:ListWorkspaces` | List | Recommended (for listing workspaces) |
## Notes
- **RAM user vs. root account**: It is strongly recommended to use a RAM user rather than the primary account's Access Key.
- **Least privilege**: If you only need to create workspaces, grant only `paiworkspace:CreateWorkspace`.
- **Resource group permissions**: If `ResourceGroupId` is specified, `resourcemanager:GetResourceGroup` permission may also be required.
- Create custom policies in the RAM console: https://ram.console.aliyun.com/policies
FILE:references/related-commands.md
# Related Commands — PAI Workspace Management
All commands use plugin mode format and include `--user-agent AlibabaCloud-Agent-Skills/alibabacloud-pai-workspace-manage`.
> **Important**: CLI uses `--region` (global parameter) to specify the region, not `--region-id`. `--region` **must be specified by the user** — do not use default values.
> `--env-types` uses list format (e.g., `--env-types prod` or `--env-types dev prod`), not JSON arrays.
### Global Optional Parameters — Timeout & Retry
All `aliyun` commands support the following global parameters:
| Parameter | Type | Description | Example |
|-----------|------|-------------|---------|
| `--connect-timeout` | int | Connection timeout (seconds) | `--connect-timeout 10` |
| `--read-timeout` | int | I/O read timeout (seconds) | `--read-timeout 30` |
| `--retry-count` | int | Number of retries on failure | `--retry-count 3` |
> When encountering `timeout` or `context deadline exceeded` errors, increase `--read-timeout` (e.g., 30-60 seconds). You can also persist the configuration via `aliyun configure set --connect-timeout 10 --read-timeout 30`.
---
## 1. Create Workspace (CreateWorkspace)
### Simple Mode (production environment only)
```bash
aliyun aiworkspace create-workspace \
--region <RegionId> \
--workspace-name <WorkspaceName> \
--description "<Description>" \
--env-types prod \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-pai-workspace-manage
```
### Standard Mode (development + production environments)
```bash
aliyun aiworkspace create-workspace \
--region <RegionId> \
--workspace-name <WorkspaceName> \
--description "<Description>" \
--env-types dev prod \
--display-name "<DisplayName>" \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-pai-workspace-manage
```
### With Resource Group
```bash
aliyun aiworkspace create-workspace \
--region <RegionId> \
--workspace-name <WorkspaceName> \
--description "<Description>" \
--env-types prod \
--resource-group-id <ResourceGroupId> \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-pai-workspace-manage
```
### create-workspace Parameter Reference
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `--region` | string | Yes | Region ID (global parameter), **must be specified by the user**, do not use default values |
| `--workspace-name` | string | Yes | 3-23 characters, starts with a letter, may contain letters/digits/underscores, unique within the region |
| `--description` | string | Yes | Max 80 characters |
| `--env-types` | list | Yes | List format: `prod` (simple mode), `dev prod` (standard mode) |
| `--display-name` | string | No | Display name, defaults to WorkspaceName |
| `--resource-group-id` | string | No | Resource group ID |
---
## 2. Get Workspace Details (GetWorkspace)
> **[MUST] Single ID queries must use this command**: When querying **single** workspace details, you must use `get-workspace` (calls GetWorkspace API). Do not use `list-workspaces --workspace-ids` as a substitute for single ID queries.
> `get-workspace` only accepts `--workspace-id` and `--verbose` parameters. The region is specified via the global `--region` parameter.
>
> **[MUST] `--verbose true` trigger rules**: When the user's request involves keywords such as 所有者/拥有者/创建者/管理员/负责人/归属/owner/admin/administrator/verbose, `--verbose true` **must** be appended.
### Basic Query (when user does not request Owner/Admin info)
> **[MUST]** Even basic queries return `Creator` (sensitive). This command must **always** include `| jq -r` pipe filtering. The Agent must NEVER run the CLI command without `| jq -r` — not even as an intermediate step.
```bash
aliyun aiworkspace get-workspace \
--workspace-id <WorkspaceId> \
--region <RegionId> \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-pai-workspace-manage \
| jq -r '"Workspace: \(.WorkspaceName) (ID: \(.WorkspaceId))
Status: \(.Status)
Environment: \(.EnvTypes | join(", "))
Created: \(.GmtCreateTime)
Creator ID: \(.Creator // "" | if length > 0 then "****" + .[-4:] else "N/A" end)"'
```
### With Owner and Admin Info (must use when user requests owner/admin info)
> **[MUST]** Since `--verbose true` returns sensitive data, this command must **NEVER** be executed without `| jq -r` pipe filtering. The execution framework logs ALL command stdout to `ran-scripts/executed-actions.log`. By piping through `jq -r`, the raw JSON flows through the pipe internally and only the masked, natural-language output reaches stdout.
```bash
aliyun aiworkspace get-workspace \
--workspace-id <WorkspaceId> \
--verbose true \
--region <RegionId> \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-pai-workspace-manage \
| jq -r '"Workspace: \(.WorkspaceName) (ID: \(.WorkspaceId))
Status: \(.Status)
Environment: \(.EnvTypes | join(", "))
Created: \(.GmtCreateTime)
Owner: \(.Owner.UserName // "" | if length > 0 then .[0:1] + "***" else "N/A" end) (ID: \(.Owner.UserId // "" | if length > 0 then "****" + .[-4:] else "N/A" end))
Creator ID: \(.Creator // "" | if length > 0 then "****" + .[-4:] else "N/A" end)
Administrators: \(.AdminNames // [] | map(.[0:1] + "***") | join(", "))"'
```
**Output example** (only masked values, no raw JSON, no original key names):
```
Workspace: myworkspace (ID: 12345)
Status: ENABLED
Environment: dev, prod
Created: 2021-01-21T17:12:35.232Z
Owner: z*** (ID: ****5714)
Creator ID: ****5714
Administrators: a***, b***
```
### get-workspace Parameter Reference
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `--workspace-id` | string | Yes | Workspace ID, e.g., `1234` |
| `--verbose` | bool | Conditionally required | **Must** pass `true` when user requests owner/admin info. Returns Owner, AdminNames, and other fields that must be masked when displayed |
### Key Return Fields
| Field | Description | Possible Values | Sensitivity |
|-------|-------------|-----------------|-------------|
| `Status` | Workspace status | `ENABLED` / `INITIALIZING` / `FAILURE` / `DISABLED` / `FROZEN` / `UPDATING` | Non-sensitive |
| `EnvTypes` | Environment list | `["prod"]` or `["dev","prod"]` | Non-sensitive |
| `IsDefault` | Whether it is the default workspace | `true` / `false` | Non-sensitive |
| `GmtCreateTime` | Creation time (ISO8601 UTC) | `2021-01-21T17:12:35.232Z` | Non-sensitive |
| `Creator` | Creator user ID (always returned) | `"28815334567890"` | **Sensitive — must be masked** |
| `Owner` | Owner (returned when `--verbose true`) | `{UserKp, UserId, UserName, DisplayName}` | **Sensitive — must be masked** |
| `AdminNames` | Admin list (returned when `--verbose true`) | `["[email protected]"]` | **Sensitive — must be masked** |
| `ResourceGroupId` | Resource group ID | `rg-xxxxxxxx` | Non-sensitive |
> **[MUST] Sensitive field masking rules — raw sensitive data must not appear in stdout, on disk, or in conversation**:
>
> The execution framework logs ALL command stdout to `ran-scripts/executed-actions.log`. Therefore, CLI commands returning sensitive data must **NEVER** be executed without `| jq -r` pipe filtering. Pipe through `jq -r` with a masking filter so the raw JSON flows through the pipe internally and only the masked, natural-language result reaches stdout and execution logs.
>
> | Field | Masking Method | Display Format Example |
> |-------|---------------|----------------------|
> | `Owner.UserId` / `Creator` | Show only last 4 digits | `Owner ID: ****7890` |
> | `Owner.UserKp` | **Omit entirely, do not display** | — (not output) |
> | `Owner.UserName` | Show only first character + `***` | `Username: z***` |
> | `Owner.DisplayName` | Show only first character + `***` | `Display Name: Z***` |
> | Accounts in `AdminNames` | First character + `***` + domain | `Admin: a***@example.com` |
>
> **Correct display example**:
> ```
> Owner: z*** (ID: ****7890)
> Admin: a***@example.com
> ```
>
> **Prohibited behaviors** (any of the following will trigger security detection):
> - **Executing ANY `get-workspace` or `list-workspaces` command without `| jq -r` pipe filtering** — including basic queries (which return `Creator`). The execution framework captures stdout to execution logs, leaking raw API responses. This is the most critical prohibition
> - **Two-step processing** — running the CLI command first to get raw output, then separately masking it in a second step. The raw JSON appears in the execution transcript before masking is applied. The `| jq -r` MUST be part of the same single pipeline command
> - **Capturing raw output to shell variables** — e.g., `response=$(aliyun ...)` then processing `$response`. The variable assignment step exposes raw data in the execution log
> - **Embedding raw API response data in any script or code file** — e.g., writing a Python/shell script that contains raw JSON values as string literals, variables, or data structures (such as `ran_scripts/process_workspace_data.py`). All data processing must be done entirely within the `| jq -r` pipe; do NOT create intermediate processing scripts that contain raw data
> - Saving raw API responses to any file (`.json`, `.log`, `.txt`, or any other format)
> - Redirecting command output to files (`> file`, `>> file`, `| tee file`)
> - Executing commands via shell scripts saved to disk (e.g., `ran-scripts/*.sh`)
> - Displaying raw JSON snippets containing sensitive key names in the conversation
> - Creating intermediate files, log files, or output files containing unmasked sensitive values
> - **Even when values are masked**, using original API field names (such as `UserId`, `UserName`) as JSON keys or structured key names in output is prohibited. Replace with natural language key names (`Owner ID`, `Username`, etc.)
>
> **Correct approach**: **EVERY** execution of `get-workspace` or `list-workspaces` must be a **single pipeline command** with `| jq -r` appended. The Agent must NEVER run the CLI command first and then process the output in a separate step. All data extraction, masking, and formatting must happen inside the `jq` filter of the same pipeline. If saving to a file, redirect the **jq output** (not the CLI output) using `> file.md` at the end of the pipeline. See the command templates above.
### Error Responses
| StatusCode | Code | Meaning | Handling |
|------------|------|---------|----------|
| 404 | 100400027 | Workspace does not exist | Report to user that the ID does not exist. Do not fall back to `list-workspaces` to search |
---
## 3. List Workspaces (ListWorkspaces)
> **[MUST] Pipe filtering required**: Since `list-workspaces` **always** returns `Creator` and `AdminNames` (sensitive PII), these commands must be piped through `| jq -r` with a masking filter — just like `get-workspace --verbose true`. See the masking rules in the "Sensitive Fields in Workspaces Array Elements" section below. The command templates in this section show the CLI arguments only; in practice, they must include `| jq -r` pipe filtering for masking.
### List All Workspaces
```bash
aliyun aiworkspace list-workspaces \
--region <RegionId> \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-pai-workspace-manage
```
### Filter by Name
```bash
aliyun aiworkspace list-workspaces \
--region <RegionId> \
--workspace-name <WorkspaceName> \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-pai-workspace-manage
```
### Filter by Status + Sort by Creation Time Descending
> **Enum values are case-sensitive**: `--sort-by` values must be camelCase `GmtCreateTime` or `GmtModifiedTime`, `--order` values must be all uppercase `ASC` or `DESC`, `--status` values must be all uppercase like `ENABLED`. Incorrect examples: `desc`, `gmtCreateTime`, `enabled`.
```bash
aliyun aiworkspace list-workspaces \
--region <RegionId> \
--status ENABLED \
--sort-by GmtCreateTime \
--order DESC \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-pai-workspace-manage
```
### Paginated Query
```bash
aliyun aiworkspace list-workspaces \
--region <RegionId> \
--page-number 1 \
--page-size 20 \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-pai-workspace-manage
```
### Batch Query by ID List (for multiple IDs, 2 or more)
> **[MUST] Must use this method for multi-ID (2+) scenarios**: When querying **multiple** specific workspaces, use `--workspace-ids` for a single batch query. **Do not** call `get-workspace` individually for each ID. **Single ID** queries must use `get-workspace` (see above).
>
> **[MUST] Returned results are final**: The `Workspaces` array from batch queries already contains complete information for each workspace (Status, EnvTypes, GmtCreateTime, etc.). **Do not** call `get-workspace` for any ID in the batch results to get additional details. If a requested ID is not in the results, that ID does not exist.
```bash
aliyun aiworkspace list-workspaces \
--workspace-ids "10234,10567,10891" \
--region <RegionId> \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-pai-workspace-manage
```
### Get Resource Limits
```bash
aliyun aiworkspace list-workspaces \
--region <RegionId> \
--option GetResourceLimits \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-pai-workspace-manage
```
### Check Workspace Name Existence (must call before creating)
> **[MUST] Must use this command to check name uniqueness before creating a workspace.** `TotalCount == 0` means the name is available; `TotalCount >= 1` means the name already exists, prompt the user to choose a different name.
```bash
aliyun aiworkspace list-workspaces \
--region <RegionId> \
--option CheckWorkspaceExists \
--workspace-name <WorkspaceName> \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-pai-workspace-manage
```
**Response examples**:
Name available (`TotalCount == 0`):
```json
{"TotalCount": 0, "RequestId": "xxx", "Workspaces": []}
```
Name already exists (`TotalCount >= 1`):
```json
{"TotalCount": 1, "RequestId": "xxx", "Workspaces": [{"WorkspaceName": "test"}]}
```
### Return Only Workspace IDs
```bash
aliyun aiworkspace list-workspaces \
--region <RegionId> \
--fields Id \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-pai-workspace-manage
```
### list-workspaces Parameter Reference
| Parameter | Type | Required | Description | Default |
|-----------|------|----------|-------------|---------|
| `--region` | string | Yes | Region ID (global parameter), **must be specified by the user**, do not use default values | - |
| `--workspace-name` | string | No | Fuzzy match by name | - |
| `--status` | string | No | Filter by status (all uppercase: `ENABLED` / `DISABLED` / `FROZEN`, etc.) | - |
| `--page-number` | int | No | Page number, starting from 1 | `1` |
| `--page-size` | int | No | Items per page | `20` |
| `--sort-by` | string | No | Sort field (case-sensitive): `GmtCreateTime` / `GmtModifiedTime` | `GmtCreateTime` |
| `--order` | string | No | Sort direction (all uppercase): `ASC` / `DESC` | `ASC` |
| `--verbose` | bool | No | Return detailed information | `false` |
| `--workspace-ids` | string | No | Query by ID list, comma-separated | - |
| `--resource-group-id` | string | No | Filter by resource group | - |
| `--module-list` | string | No | Comma-separated module list | `PAI` |
| `--option` | string | No | Query option: `GetWorkspaces`/`GetResourceLimits` | `GetWorkspaces` |
| `--fields` | string | No | Return field list, currently only supports `Id` | - |
| `--user-id` | string | No | User ID | - |
### Sensitive Fields in Workspaces Array Elements
> **[MUST]** Each workspace object returned by `list-workspaces` **always** contains `Creator` (creator user ID) and `AdminNames` (admin account list) — **no `--verbose true` needed**. These fields contain PII and follow the same masking rules as GetWorkspace:
>
> | Field | Always Returned | Masking Method | Display Format Example |
> |-------|----------------|---------------|----------------------|
> | `Creator` | Yes | Show only last 4 digits | `Creator ID: ****7890` |
> | `AdminNames` | Yes | First character + `***` + domain | `Admin: a***@example.com` |
>
> Do not output raw `Creator` or `AdminNames` values from `list-workspaces` responses. Since the execution framework logs ALL command stdout to `ran-scripts/executed-actions.log`, `list-workspaces` must also be piped through `| jq -r` with a masking filter — the raw JSON flows through the pipe internally and only the masked result reaches stdout. Example:
>
> ```bash
> aliyun aiworkspace list-workspaces \
> --region <RegionId> \
> --user-agent AlibabaCloud-Agent-Skills/alibabacloud-pai-workspace-manage \
> | jq -r '.Workspaces[] | "- \(.WorkspaceName) (ID: \(.WorkspaceId)) Status: \(.Status), Creator: \(.Creator // "" | if length > 0 then "****" + .[-4:] else "N/A" end), Admin: \(.AdminNames // [] | map(.[0:1] + "***") | join(", "))"'
> ```
### Status Enum Values
| Value | Description |
|-------|-------------|
| `ENABLED` | Active |
| `INITIALIZING` | Initializing |
| `FAILURE` | Failed |
| `DISABLED` | Manually disabled |
| `FROZEN` | Frozen due to overdue payment |
| `UPDATING` | Updating |
### SortBy Enum Values
| Value | Description |
|-------|-------------|
| `GmtCreateTime` | Sort by creation time (default) |
| `GmtModifiedTime` | Sort by modification time |
### Option Enum Values
| Value | Description |
|-------|-------------|
| `GetWorkspaces` | Get workspace list (default), returns `Workspaces` |
| `GetResourceLimits` | Get resource limit information, returns `ResourceLimits` |
| `CheckWorkspaceExists` | Check if a workspace with the specified name already exists, use with `--workspace-name` |
---
## 4. Check Product Activation Status (ListProducts)
> **[MUST] Must check on first use of a region**: After the user specifies a region (or the first time a region is used in a session), this command must be called first to check whether PAI is activated before executing subsequent workspace operations.
### Check PAI Activation Status
```bash
aliyun aiworkspace list-products \
--region <RegionId> \
--product-codes PAI_share \
--verbose true \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-pai-workspace-manage
```
### list-products Parameter Reference
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `--region` | string | Yes | Region ID (global parameter) |
| `--product-codes` | string | Yes | Product codes, comma-separated. Use `PAI_share` for PAI |
| `--verbose` | bool | Yes | Pass `true` to return detailed fields such as `PurchaseUrl` and `HasPermissionToPurchase` |
### Key Return Fields (Products Array Elements)
| Field | Type | Description |
|-------|------|-------------|
| `ProductCode` | string | Product code, e.g., `PAI_share` |
| `IsPurchased` | boolean | Whether the product is purchased/activated. `true` = activated, `false` = not activated |
| `PurchaseUrl` | string | Purchase/activation link. When `IsPurchased == false`, guide the user to visit this link to complete activation |
| `HasPermissionToPurchase` | boolean | Whether the current user has permission to purchase. When `false`, requires the primary account or a RAM user with `pai:CreateOrder` permission |
| `ProductId` | string | Product ID |
### Response Example
```json
{
"RequestId": "xxx",
"Products": [
{
"ProductCode": "PAI_share",
"IsPurchased": true,
"PurchaseUrl": "https://common-buy.aliyun.com/...",
"HasPermissionToPurchase": true,
"ProductId": ""
}
]
}
```
### Result Handling Logic
| `IsPurchased` | `HasPermissionToPurchase` | Agent Behavior |
|---------------|--------------------------|----------------|
| `true` | — | PAI is activated, proceed with subsequent workflows |
| `false` | `true` | Show `PurchaseUrl` to user, prompt to complete activation in the console |
| `false` | `false` | Inform user they lack permission. Contact primary account administrator (requires primary account or `pai:CreateOrder` permission) |
> **[MUST]** When PAI is not activated (`IsPurchased == false`), do not proceed with creating/querying workspaces. Wait for the user to confirm activation before continuing.
---
## Common Region IDs
| Region | RegionId |
|--------|----------|
| China East 1 (Hangzhou) | cn-hangzhou |
| China East 2 (Shanghai) | cn-shanghai |
| China North 2 (Beijing) | cn-beijing |
| China South 1 (Shenzhen) | cn-shenzhen |
| Singapore | ap-southeast-1 |
FILE:references/verification-method.md
# Verification Method — PAI Workspace Management
## Scenario Verification
**Expected outcome**: PAI workspace is successfully created with `ENABLED` status and is ready for use.
---
## Step 1: Extract WorkspaceId from Create Response
After the create command succeeds, the response contains a `WorkspaceId`. Extract and save it:
```bash
# Execute create command and extract WorkspaceId
WORKSPACE_ID=$(aliyun aiworkspace create-workspace \
--region <RegionId> \
--workspace-name <WorkspaceName> \
--description "<Description>" \
--env-types prod \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-pai-workspace-manage | jq -r '.WorkspaceId')
echo "WorkspaceId: $WORKSPACE_ID"
```
**Success criteria**: `WorkspaceId` is a non-empty string (e.g., `"1234"`)
---
## Step 2: Verify Workspace Status
```bash
aliyun aiworkspace get-workspace \
--workspace-id $WORKSPACE_ID \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-pai-workspace-manage
```
> **Note**: `get-workspace` only accepts `--workspace-id` and `--verbose` parameters. The region is specified via the global `--region` parameter (if overriding the default region).
**Expected response fields**:
| Field | Expected Value | Description |
|-------|---------------|-------------|
| `WorkspaceName` | Matches creation input | Workspace name |
| `Status` | `ENABLED` | Workspace is operational |
| `EnvTypes` | Matches creation input | Environment types |
| `GmtCreateTime` | Non-empty | Creation time is recorded |
**Success criteria**: `Status` field value is `ENABLED`
---
## Step 3: Verify via List (Optional)
```bash
aliyun aiworkspace list-workspaces \
--region <RegionId> \
--workspace-name <WorkspaceName> \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-pai-workspace-manage
```
**Success criteria**: Response has `TotalCount >= 1` and contains the target workspace.
---
## Step 4: Console Verification (When CLI/Code Verification Is Not Possible)
> **Note**: The following verification steps require manual operation in the console and cannot be automated via CLI or code.
1. Log in to [PAI Console](https://pai.console.aliyun.com/)
2. Select the corresponding region in the left navigation
3. Find the newly created workspace in the Workspace list
4. Confirm the status is "Enabled"
5. Click the workspace name to verify the environment (dev/prod) configuration is correct
---
## Quick Verification Script
```bash
#!/bin/bash
# Quick verification: check if workspace was created successfully
WORKSPACE_ID="<WorkspaceId>"
STATUS=$(aliyun aiworkspace get-workspace \
--workspace-id $WORKSPACE_ID \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-pai-workspace-manage | jq -r '.Status')
if [ "$STATUS" = "ENABLED" ]; then
echo "Workspace created successfully, Status: $STATUS"
else
echo "Workspace status abnormal: $STATUS"
exit 1
fi
```
Alibaba Cloud ECS File Backup Essential Edition (ECS文件备份基础版). One-click activation, daily automatic backup, 30-day file recovery, 100 GiB free quota. Trigger...
---
name: alibabacloud-cloudbackup-ecs-file-backup-essential-edition
description: |
Alibaba Cloud ECS File Backup Essential Edition (ECS文件备份基础版). One-click activation, daily automatic backup, 30-day file recovery, 100 GiB free quota.
Trigger words: ECS file backup, HBR essential edition, Cloud Backup essential, file deletion recovery, free backup quota, ECS data protection, lightweight backup, affordable ECS backup
Redirect words: ECS database backup, ECS full-machine backup, full-machine clone, cross-region backup, cross-account backup, KMS encrypted backup
---
# ECS File Backup Essential Edition - Operations & Viewing
## Scenario Description
ECS File Backup Essential Edition (ECS文件备份基础版) is a basic backup product launched by Alibaba Cloud's Cloud Backup service (HBR) for ECS file scenarios, featuring one-click activation and zero-configuration setup.
### Core Features
| Feature | Description |
|---------|-------------|
| Automatic Backup (自动备份) | Daily automatic backup with 30-day retention |
| File Recovery (文件恢复) | Files accidentally deleted within 30 days can be recovered; supports file-level restoration |
| Free Quota (免费额度) | 100 GiB permanent free block storage backup quota per account (shared across all regions) |
| Low Maintenance (低运维) | One-click activation, zero configuration required, backup client auto-installed |
### Recommended Use Cases
When user requirements match the following conditions, recommend ECS File Backup Essential Edition:
| Scenario | Description |
|----------|-------------|
| **ECS File Data Protection** | Need to protect/backup ECS file data and recover from accidental deletion |
| **Accept Daily Backup Policy** | Accept once-daily backup with 30-day retention |
| **Cost-Effective** | Affordable/free ECS data backup; 100 GiB permanent free quota per account (shared across all regions) |
| **Personal Websites/Blogs** | Quick recovery from accidental deletion of images or config files |
| **Dev/Test Environments** | Protection for code and configuration files |
| **Small Business Applications** | Basic data protection needs with low maintenance cost |
### Not-Recommended Scenarios & Alternatives
| Scenario | Reason | Alternative |
|----------|--------|-------------|
| **RDS or Self-Managed Database Backup** (数据库备份) | Database files are locked by the main process; backups may be inconsistent | For RDS, contact the RDS team; for MySQL/Oracle/SQL Server, use **Cloud Backup Database Backup** |
| **Cannot Install Backup Client** (不接受安装备份客户端) | Backup client consumes ECS CPU and memory resources | Use **ECS Snapshots** (note: no file-level recovery) |
| **ECS Spec < 1C512MB** | Specs too low, affecting backup performance | Use **ECS Snapshots**, or upgrade ECS specs first |
| **Full-Machine Clone/DR Failover** (整机克隆/异地拉起) | Essential Edition does not support full-machine recovery | Use **ECS Snapshots** |
| **Cross-Region/Cross-Account Backup** (跨地域/跨账号备份) | Essential Edition does not support cross-region or cross-account | Use **Cloud Backup ECS File Backup Standard Edition** (enterprise-grade) |
| **KMS-Encrypted Backup Data** (KMS加密备份) | Essential Edition does not support KMS encryption | Use **Cloud Backup ECS File Backup Standard Edition** |
| **Custom Backup Policy** (自定义备份策略) | Essential Edition is fixed at once-daily backup with 30-day retention | Use **Cloud Backup ECS File Backup Standard Edition** (customizable policy) |
| **Data Volume > 2 TB** | Backup may not complete within 24 hours | Contact Cloud Backup technical support, or use Standard Edition |
### Usage Limitations
| Limitation | Description |
|------------|-------------|
| Operating System | 32-bit operating systems not supported |
| Network Type | Classic network (经典网络) ECS not supported |
| Storage Type | Only block storage (块存储) supported; NAS/OSS and other network-mounted storage not supported |
| Dependent Service | Requires Cloud Assistant (云助手) service (ECS purchased before Dec 2017 requires manual installation of Cloud Assistant Agent) |
| ECS Spec | Recommended >= 1 vCPU, 512 MB memory for adequate backup performance |
| Data Volume | Low priority: < 600 GB; High priority: < 2 TB |
---
## Scenario Eligibility Check (Mandatory First Step)
> **CRITICAL - Hard Gate**: This is the **first step** before all operations, taking priority over installation checks, credential verification, and any workflow.
> The agent **MUST** complete this check before executing any other step.
**Decision Flow:**
```
User requests ECS backup/restore
|
+-> Check each item in "Not-Recommended Scenarios & Alternatives"
| +-> Matches any not-recommended scenario -> Execute [HALT Flow]
| +-> No match -> Pass, continue to "Installation Requirements"
|
+-> Not-recommended scenario keywords:
- Database: MySQL/Oracle/SQL Server/PostgreSQL/MongoDB/Redis/database data directory
- Full-machine: full-machine recovery/DR failover/clone instance
- Cross-region/cross-account: remote backup/cross-account replication
- Custom policy: hourly backup/custom retention period
- Large data volume: data exceeds 2 TB
```
**[HALT Flow] - Must execute when a not-recommended scenario is matched:**
1. **Stop immediately** - Do NOT execute installation checks, credential verification, parameter confirmation, or any CLI command
2. **Output warning to user** - Explain why the current scenario is not suitable for ECS File Backup Essential Edition (cite the reason from "Not-Recommended Scenarios & Alternatives")
3. **Recommend alternatives** - Provide specific alternative products/features
4. **End current task** - After outputting the warning and alternatives, the agent **MUST stop** and **NOT continue with any subsequent steps of this Skill**
> **Sole recovery condition**: Only when the user **proactively and explicitly** states "I understand the risks and still want to use ECS File Backup Essential Edition" (or semantically equivalent), may the agent continue.
> The following are **NOT** valid confirmations (agent must remain stopped): no reply; vague confirmations ("OK", "Continue", "Help me backup") without mentioning "ECS File Backup Essential Edition"; topic changes; asking about alternatives.
---
## Installation Requirements (Mandatory Pre-check)
> **CRITICAL**: The agent **MUST** complete the following pre-checks before executing any core workflow.
### Pre-check: Aliyun CLI >= 3.3.3 required
> Run `aliyun version` to verify >= 3.3.3. If not installed or version too low,
> run `curl -fsSL https://aliyuncli.alicdn.com/setup.sh | bash` to update,
> or see [references/cli-installation-guide.md](references/cli-installation-guide.md) for installation instructions.
```bash
aliyun version
```
Then [MUST] run `aliyun plugin update` to ensure that any existing plugins on your local machine are always up-to-date.
**[MUST] CLI User-Agent** — Every `aliyun` CLI command invocation must include:
`--user-agent AlibabaCloud-Agent-Skills/alibabacloud-cloudbackup-ecs-file-backup-essential-edition`
Enable automatic plugin installation:
```bash
aliyun configure set --auto-plugin-install true
```
### Pre-check: AI-Mode Configuration
**[MUST] Enable AI-Mode** — Run before any CLI invocation:
```bash
aliyun configure ai-mode enable
aliyun configure ai-mode set-user-agent --user-agent "AlibabaCloud-Agent-Skills/alibabacloud-cloudbackup-ecs-file-backup-essential-edition"
```
**[MUST] Disable AI-Mode at EVERY exit point** — Before delivering the final response for ANY reason (success, failure, error, cancellation), always disable AI-mode first. AI-mode MUST NOT remain enabled after the skill stops running.
```bash
aliyun configure ai-mode disable
```
### Pre-check: aliyun-cli-hbr plugin >= 0.1.3 required
```bash
aliyun plugin list 2>/dev/null | grep aliyun-cli-hbr
```
If the plugin is not installed or the version is below 0.1.3, install/update:
```bash
aliyun plugin install --names aliyun-cli-hbr
```
> After plugin installation, HBR commands and parameter names use kebab-case naming convention (e.g., `describe-backup-plans` instead of `DescribeBackupPlans`).
---
## Credential Verification
> **Pre-check: Alibaba Cloud Credentials Required**
>
> **Security Rules:**
> - **NEVER** print, echo, or output AK/SK values in any form (including partial fragments or masked forms)
> - **NEVER** expose any credential content in command-line arguments, logs, conversation output, or code comments
> - **NEVER** enter AK/SK directly in the command line
> - **ONLY USE** `aliyun configure list` to check credential status; **NEVER echo the output of this command to the user** (output may contain credential-related information); the agent should only use the output internally to determine whether credentials are valid
>
> ```bash
> aliyun configure list
> ```
>
> Confirm the output shows a valid profile (AK, STS, or OAuth identity).
>
> **If no valid credentials exist, configure first:**
> 1. Obtain credentials from [Alibaba Cloud Console](https://ram.console.aliyun.com/manage/ak)
> 2. Run `aliyun configure` in the terminal to configure credentials
> 3. Re-run `aliyun configure list` to confirm successful configuration
---
## Parameter Confirmation & Validation
> **IMPORTANT: Parameter Confirmation** - Before executing any command, all customizable parameters must be confirmed with the user.
> Do not assume default values; explicit user confirmation is required.
> **If the user refuses to confirm or does not respond to the confirmation request, the agent MUST abort the current operation and NOT continue with subsequent steps.**
> **CRITICAL - Security Gate**: Before embedding any parameter into a CLI command, the agent **MUST** validate all user-provided parameters against the validation regex in the table below.
> On validation failure, the agent **MUST refuse to execute the command**, inform the user which parameter is invalid and what format is expected, and wait for the user to provide a valid value before re-validating.
| Parameter | Required/Optional | Description | Validation Regex | Example |
|-----------|-------------------|-------------|------------------|---------|
| `REGION_ID` | Required | Region of the ECS instance (ECS实例所在地域) | `^[a-zA-Z0-9-]+$` | `cn-hangzhou` |
| `INSTANCE_ID` | Required | ECS Instance ID (ECS实例ID) | `^[a-zA-Z0-9-]+$` | `i-bp1abc123def456` |
| `PLAN_ID` | Required for some ops | Backup Plan ID (备份计划ID); needed for pause/resume/cancel | `^[a-zA-Z0-9-]+$` | `plan-abc123` |
| `VAULT_ID` | Required for restore | Backup Vault ID (备份仓库ID); obtained via `search-historical-snapshots` | `^[a-zA-Z0-9-]+$` | `v-0001xjb123` |
| `SNAPSHOT_ID` | Required for restore | Snapshot ID (备份版本ID); obtained via `search-historical-snapshots` | `^[a-zA-Z0-9-]+$` | `s-0001abc123` |
| `SNAPSHOT_HASH` | Required for restore | Snapshot Hash (备份版本哈希值); obtained via `search-historical-snapshots` | `^[a-zA-Z0-9-]+$` | `sh-abc123` |
| `performanceLevel` | Optional | Backup priority (备份优先级): `L0` (default, data < 600 GB) or `L1` (data 600 GB~2 TB) | `^(L0\|L1)$` | `L0` |
| `ConflictPolicy` | Required for restore | File conflict policy (文件冲突策略): `SKIP_THE_FILE` (skip) or `OVERWRITE_EXISTING` (overwrite) | `^(SKIP_THE_FILE\|OVERWRITE_EXISTING)$` | `SKIP_THE_FILE` |
| `CLIENT_TOKEN` | Required for restore | Idempotency token (幂等令牌); agent-generated UUID, reuse on timeout retry | `^[a-zA-Z0-9-]{1,64}$` | `550e8400-e29b-41d4-a716-446655440000` |
| `keep-latest-snapshots` | Optional | Keep last backup version (保留最后一个备份版本): `1` (keep) or `0` (don't keep) | `^(0\|1)$` | `1` |
| `SOURCE_PATH` | Optional for restore | Source file path to restore (要恢复的源文件路径) | `^[a-zA-Z0-9/_.-]+$` | `/home/data/file.txt` |
| `TARGET_PATH` | Required for restore | Restore target directory (恢复目标目录); must already exist | `^[a-zA-Z0-9/_.-]+$` | `/tmp/restore` |
## RAM Permissions
This Skill requires the permissions detailed in [references/ram-policies.md](references/ram-policies.md).
Recommended system policy: `AliyunHBRFullAccess`
---
## Core Workflows
> **CRITICAL**: Before executing any of the following workflows, the agent **MUST** complete all steps in "Scenario Eligibility Check" and "Installation Requirements (Mandatory Pre-check)".
> If Aliyun CLI or the aliyun-cli-hbr plugin is not installed or does not meet version requirements, it **MUST be installed/updated first** before proceeding.
> **Note**: All CLI operations below are idempotent and safe to retry.
### 1. Activate Backup
Activate ECS File Backup Essential Edition for a specified ECS instance.
**Step 1: Enable Cloud Backup Service (first-time use)**
```bash
aliyun hbr open-hbr-service \
--endpoint hbr.aliyuncs.com \
--read-timeout 60 \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-cloudbackup-ecs-file-backup-essential-edition
```
**Step 2: Activate ECS Instance Backup**
```bash
aliyun hbr create-backup-plan \
--region <REGION_ID> \
--edition BASIC \
--source-type ECS_FILE \
--instance-id <INSTANCE_ID> \
--keep-latest-snapshots 1 \
--options '{"performanceLevel":"<LEVEL>"}' \
--read-timeout 60 \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-cloudbackup-ecs-file-backup-essential-edition
```
> Idempotent operation; repeated calls for the same instance will not create duplicate backup plans. Safe to retry on timeout.
**Step 3: Verify Activation Status**
> Activation and client installation are asynchronous operations; they typically take a few minutes to become ready.
Use the status determination logic from "5. View ECS Backup Status" to verify. Expected state progression: `Preparing` -> `Ready` -> `Backing Up`
---
### 2. Pause Backup (Suspend)
Pause the backup plan (备份计划) while retaining existing backup data; can be resumed later.
**Step 1: Get Backup Plan ID**
```bash
aliyun hbr describe-backup-plans \
--region <REGION_ID> \
--edition BASIC \
--source-type ECS_FILE \
--filters '[{"Key":"instanceId","Values":["<INSTANCE_ID>"]}]' \
--read-timeout 60 \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-cloudbackup-ecs-file-backup-essential-edition
```
> Extract `PlanId` from the response.
**Step 2: Pause Backup**
```bash
aliyun hbr disable-backup-plan \
--region <REGION_ID> \
--plan-id <PLAN_ID> \
--edition BASIC \
--read-timeout 60 \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-cloudbackup-ecs-file-backup-essential-edition
```
---
### 3. Resume Backup
Resume a previously paused backup plan.
```bash
aliyun hbr enable-backup-plan \
--region <REGION_ID> \
--plan-id <PLAN_ID> \
--edition BASIC \
--read-timeout 60 \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-cloudbackup-ecs-file-backup-essential-edition
```
---
### 4. Cancel Backup (Delete)
> **WARNING**: This operation will permanently delete all backup data and is irreversible! User intent must be confirmed before execution.
> **If the user has not explicitly confirmed deletion, the agent MUST abort the operation and NOT continue.**
**Step 1: Get Backup Plan ID**
```bash
aliyun hbr describe-backup-plans \
--region <REGION_ID> \
--source-type ECS_FILE \
--edition BASIC \
--filters '[{"Key":"instanceId","Values":["<INSTANCE_ID>"]}]' \
--read-timeout 60 \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-cloudbackup-ecs-file-backup-essential-edition
```
**Step 2: Delete Backup Plan**
```bash
aliyun hbr delete-backup-plan \
--region <REGION_ID> \
--plan-id <PLAN_ID> \
--edition BASIC \
--read-timeout 60 \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-cloudbackup-ecs-file-backup-essential-edition
```
> After cancellation, the instance stops incurring charges; deleted backup data cannot be recovered. Safe to call repeatedly on an already-deleted plan.
---
### 5. View ECS Backup Status
**Step 1: Query Backup Plan**
```bash
aliyun hbr describe-backup-plans \
--region <REGION_ID> \
--edition BASIC \
--source-type ECS_FILE \
--filters '[{"Key":"instanceId","Values":["<INSTANCE_ID>"]}]' \
--read-timeout 60 \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-cloudbackup-ecs-file-backup-essential-edition
```
**Step 2: Query Latest Backup Job**
```bash
aliyun hbr describe-backup-jobs-2 \
--region <REGION_ID> \
--edition BASIC \
--source-type ECS_FILE \
--filters '[{"Key":"instanceId","Values":["<INSTANCE_ID>"]}]' \
--read-timeout 60 \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-cloudbackup-ecs-file-backup-essential-edition
```
> `describe-backup-jobs-2` returns backup jobs sorted by creation time in descending order; the first record is the latest execution result.
**Status Determination Logic**
```
describe-backup-plans finds no plan -> Not Activated (未激活)
describe-backup-plans finds a plan
+-> Disabled = true -> Paused (已暂停)
+-> Query describe-backup-jobs-2 for latest backup job
+-> No backup jobs -> Preparing (准备中)
+-> Has backup jobs (first record = latest result)
+-> COMPLETE/PARTIAL_COMPLETE -> Backup Normal (备份正常)
+-> RUNNING/QUEUED/CREATED -> Backing Up (备份中)
+-> CANCELED -> Canceled (已取消)
+-> FAILED/EXPIRED -> Backup Abnormal (备份异常); troubleshoot via describe-backup-clients
```
**Auxiliary Query Commands**
View backup client status:
```bash
aliyun hbr describe-backup-clients \
--region <REGION_ID> \
--client-type ECS_CLIENT \
--instance-ids '["<INSTANCE_ID>"]' \
--read-timeout 60 \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-cloudbackup-ecs-file-backup-essential-edition
```
View backup history (Snapshot list):
```bash
aliyun hbr search-historical-snapshots \
--region <REGION_ID> \
--edition BASIC \
--source-type ECS_FILE \
--query '[{"field":"instanceId","value":"<INSTANCE_ID>","operation":"MATCH_TERM"}]' \
--read-timeout 60 \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-cloudbackup-ecs-file-backup-essential-edition
```
---
### 6. View Free Quota & Capacity
```bash
aliyun hbr get-basic-statistics \
--source-type ECS_FILE \
--read-timeout 60 \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-cloudbackup-ecs-file-backup-essential-edition
```
**Key field**: `GlobalStatistics.ProtectedDataSize` is the total block storage capacity of backed-up ECS instances (in bytes).
**Free quota rules**: 100 GiB per account (permanent, shared across all regions). Usage beyond the quota is billed on a pay-as-you-go basis; billing is based on the total block storage capacity mounted on backed-up ECS instances.
---
### 7. File Restore
```bash
aliyun hbr create-restore-job \
--region <REGION_ID> \
--restore-type ECS_FILE \
--edition BASIC \
--source-type ECS_FILE \
--vault-id <VAULT_ID> \
--snapshot-id <SNAPSHOT_ID> \
--snapshot-hash <SNAPSHOT_HASH> \
--include '["<SOURCE_PATH>"]' \
--target-instance-id <INSTANCE_ID> \
--target-path <TARGET_PATH> \
--options '{"ConflictPolicy":"<CONFLICT_POLICY>"}' \
--client-token <UUID> \
--read-timeout 60 \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-cloudbackup-ecs-file-backup-essential-edition
```
> `VaultId`, `SnapshotId`, and `SnapshotHash` can be obtained via `search-historical-snapshots`.
> Omitting `--include` restores all files in the snapshot.
> `TargetPath` must be an existing directory on the target ECS instance; otherwise the restore job will report a `TARGET_NOT_EXIST` error.
> Using the `OVERWRITE_EXISTING` policy will overwrite files with the same name at the target path; explicit user confirmation is required before execution. If the user has not confirmed, the agent MUST abort the restore operation.
> Use `--client-token` to ensure idempotency; the agent should generate a UUID as the ClientToken and reuse the same token on timeout retries to prevent duplicate restore jobs.
**View Restore Progress**
```bash
aliyun hbr describe-restore-jobs-2 \
--region <REGION_ID> \
--edition BASIC \
--restore-type ECS_FILE \
--read-timeout 60 \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-cloudbackup-ecs-file-backup-essential-edition
```
---
### 8. Modify Scheduled Backup Time
**Step 1: Get Backup Plan ID**
```bash
aliyun hbr describe-backup-plans \
--region <REGION_ID> \
--edition BASIC \
--source-type ECS_FILE \
--filters '[{"Key":"instanceId","Values":["<INSTANCE_ID>"]}]' \
--read-timeout 60 \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-cloudbackup-ecs-file-backup-essential-edition
```
**Step 2: Update Backup Schedule**
```bash
aliyun hbr update-backup-plan \
--region <REGION_ID> \
--plan-id <PLAN_ID> \
--edition BASIC \
--schedule 'I|<TIMESTAMP>|P1D' \
--read-timeout 60 \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-cloudbackup-ecs-file-backup-essential-edition
```
> Schedule format: `I|<start_timestamp>|P1D`, where start_timestamp is a Unix timestamp in seconds, and `P1D` means once per day (fixed for Essential Edition).
---
### 9. Toggle Keep-Last-Snapshot
When enabled, even if all backup versions exceed the retention period, the system will retain the last version without deleting it.
```bash
aliyun hbr update-backup-plan \
--region <REGION_ID> \
--plan-id <PLAN_ID> \
--edition BASIC \
--keep-latest-snapshots <0_OR_1> \
--read-timeout 60 \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-cloudbackup-ecs-file-backup-essential-edition
```
> `1` = keep the last backup version (recommended); `0` = do not keep; all backup points older than 30 days will be automatically deleted.
---
### 10. Adjust Backup Execution Priority
```bash
aliyun hbr update-backup-plan \
--region <REGION_ID> \
--plan-id <PLAN_ID> \
--edition BASIC \
--options '{"performanceLevel":"<LEVEL>"}' \
--read-timeout 60 \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-cloudbackup-ecs-file-backup-essential-edition
```
> See `performanceLevel` in the Parameter Confirmation table for valid values; detailed use cases are described in [references/related-apis.md](references/related-apis.md).
---
## Verification
See [references/verification-method.md](references/verification-method.md) for details.
---
## References
| Document | Link |
|----------|------|
| CLI Installation Guide | [references/cli-installation-guide.md](references/cli-installation-guide.md) |
| API & CLI Command Reference | [references/related-apis.md](references/related-apis.md) |
| RAM Permission Policies | [references/ram-policies.md](references/ram-policies.md) |
| Verification Methods | [references/verification-method.md](references/verification-method.md) |
| Official User Guide | [ECS File Backup Essential Edition](https://help.aliyun.com/zh/cloud-backup/user-guide/ecs-file-backup-essential-edition) |
| Cloud Backup API Docs | [HBR API Reference](https://help.aliyun.com/zh/cloud-backup/developer-reference/api-hbr-2017-09-08-overview) |
FILE:references/cli-installation-guide.md
# Aliyun CLI Installation Guide
Complete guide for installing Aliyun CLI.
> **Aliyun CLI 3.3.3+**: Supports installing and using all published Alibaba Cloud product plugins. Make sure to upgrade to 3.3.3 or later for full plugin ecosystem coverage.
## Installation
### macOS
**Using Homebrew (Recommended)**
```bash
brew install aliyun-cli
# Upgrade to latest
brew upgrade aliyun-cli
# Verify version (>= 3.3.3)
aliyun version
```
**Using Binary**
```bash
# Download
wget --timeout=30 --connect-timeout=10 https://aliyuncli.alicdn.com/aliyun-cli-macosx-3.3.3-amd64.tgz
# Extract
tar -xzf aliyun-cli-macosx-3.3.3-amd64.tgz
# Move to PATH
sudo mv aliyun /usr/local/bin/
# Verify
aliyun version
```
### Linux
**Debian/Ubuntu**
```bash
# Download
wget --timeout=30 --connect-timeout=10 https://aliyuncli.alicdn.com/aliyun-cli-linux-3.3.3-amd64.tgz
# Extract and install
tar -xzf aliyun-cli-linux-3.3.3-amd64.tgz
sudo mv aliyun /usr/local/bin/
# Verify
aliyun version
```
**ARM64 Architecture**
```bash
# Download ARM64 version
wget --timeout=30 --connect-timeout=10 https://aliyuncli.alicdn.com/aliyun-cli-linux-3.3.3-arm64.tgz
# Extract and install
tar -xzf aliyun-cli-linux-3.3.3-arm64.tgz
sudo mv aliyun /usr/local/bin/
```
### Windows
**Using Binary**
1. Download from: https://aliyuncli.alicdn.com/aliyun-cli-windows-3.3.3-amd64.zip
2. Extract the ZIP file
3. Add the directory to your PATH environment variable
4. Open new Command Prompt or PowerShell
5. Verify: `aliyun version`
## Configuration
Aliyun CLI relies on the default credential chain for authentication. Run `aliyun configure` interactively to set up credentials:
```bash
aliyun configure
```
The default credential chain resolves credentials in the following order:
1. Environment variables (automatically detected by the CLI)
2. Configuration file (`~/.aliyun/config.json`)
3. Instance metadata (ECS instance role, available when running on ECS)
> **Security**: Do not pass access keys explicitly via command-line arguments or hardcode them in scripts. Always rely on the default credential chain.
**Where to Get Credentials**
1. Log in to Aliyun Console: https://ram.console.aliyun.com/
2. Navigate to: AccessKey Management
3. Create a new AccessKey pair
4. Save the secret immediately — it's only shown once
## Verification
```bash
# Basic test - list regions
aliyun ecs describe-regions
# Show current configuration
aliyun configure get
```
## References
- Official Documentation: https://help.aliyun.com/zh/cli/
- RAM Console: https://ram.console.aliyun.com/
- Access Key Management: https://ram.console.aliyun.com/manage/ak
FILE:references/ram-policies.md
# RAM Permission Policies - ECS File Backup Essential Edition
## Required Permissions
### Least-Privilege Policy
The following is the minimum set of RAM permissions required to use ECS File Backup Essential Edition CLI commands:
```json
{
"Version": "1",
"Statement": [
{
"Effect": "Allow",
"Action": [
"hbr:OpenHbrService",
"hbr:CreateBackupPlan",
"hbr:DescribeBackupPlans",
"hbr:DisableBackupPlan",
"hbr:EnableBackupPlan",
"hbr:DeleteBackupPlan",
"hbr:DescribeBackupJobs2",
"hbr:DescribeBackupClients",
"hbr:SearchHistoricalSnapshots",
"hbr:GetBasicStatistics",
"hbr:CreateRestoreJob",
"hbr:DescribeRestoreJobs2"
],
"Resource": "*"
}
]
}
```
### Permission Descriptions
| API Action | Description | Operation Type |
|------------|-------------|----------------|
| `hbr:OpenHbrService` | Enable Cloud Backup service (开通云备份服务, one-time operation) | Service Activation |
| `hbr:CreateBackupPlan` | Create a backup plan; activate ECS instance backup (创建备份计划) | Write |
| `hbr:DescribeBackupPlans` | Query backup plan list and status (查询备份计划列表和状态) | Read-only |
| `hbr:DisableBackupPlan` | Pause a backup plan (暂停备份计划) | Write |
| `hbr:EnableBackupPlan` | Resume a paused backup plan (恢复已暂停的备份计划) | Write |
| `hbr:DeleteBackupPlan` | Delete a backup plan / cancel backup (删除备份计划) | Write |
| `hbr:DescribeBackupJobs2` | Query backup job execution status (查询备份任务执行状态) | Read-only |
| `hbr:DescribeBackupClients` | Query backup client status (查询备份客户端状态) | Read-only |
| `hbr:SearchHistoricalSnapshots` | Search historical backup snapshots (搜索历史备份版本) | Read-only |
| `hbr:GetBasicStatistics` | Get capacity statistics (获取容量统计信息) | Read-only |
| `hbr:CreateRestoreJob` | Create a file restore job (创建文件恢复任务) | Write |
| `hbr:DescribeRestoreJobs2` | Query restore job status (查询恢复任务状态) | Read-only |
### Read-Only Policy
If you only need to view backup status and capacity information:
```json
{
"Version": "1",
"Statement": [
{
"Effect": "Allow",
"Action": [
"hbr:DescribeBackupPlans",
"hbr:DescribeBackupJobs2",
"hbr:DescribeBackupClients",
"hbr:SearchHistoricalSnapshots",
"hbr:GetBasicStatistics",
"hbr:DescribeRestoreJobs2"
],
"Resource": "*"
}
]
}
```
### Service-Linked Role
When ECS File Backup Essential Edition is activated for the first time, the system automatically creates a service-linked role:
- **Role Name**: `AliyunServiceRoleForHbrEcsBackup`
- **Purpose**: Cloud Backup service uses this role to install backup clients and perform backup operations
- **Creation Method**: Automatically created; no manual configuration required
> **Note**: If the account lacks permission to create service-linked roles, backup activation may fail. Ensure the account has the `ram:CreateServiceLinkedRole` permission.
### Recommended System Policies
Alibaba Cloud provides the following system policies for direct use:
| Policy Name | Description |
|-------------|-------------|
| `AliyunHBRFullAccess` | Full access to Cloud Backup |
| `AliyunHBRReadOnlyAccess` | Read-only access to Cloud Backup |
## References
- [Cloud Backup RAM Permission Reference](https://help.aliyun.com/zh/cloud-backup/developer-reference/authorization-rules)
- [RAM Access Control Console](https://ram.console.aliyun.com/)
FILE:references/related-apis.md
# Related APIs - ECS File Backup Essential Edition
## API & CLI Command Reference
| Product | CLI Command | API Action | Description | CLI Supported |
|---------|-------------|------------|-------------|---------------|
| HBR | `aliyun hbr open-hbr-service` | OpenHbrService | Enable Cloud Backup service (开通云备份服务) | Yes |
| HBR | `aliyun hbr create-backup-plan` | CreateBackupPlan | Create/activate a backup plan (创建/激活备份计划) | Yes |
| HBR | `aliyun hbr describe-backup-plans` | DescribeBackupPlans | Query backup plan list (查询备份计划列表) | Yes |
| HBR | `aliyun hbr disable-backup-plan` | DisableBackupPlan | Pause a backup plan (暂停备份计划) | Yes |
| HBR | `aliyun hbr enable-backup-plan` | EnableBackupPlan | Resume a backup plan (恢复备份计划) | Yes |
| HBR | `aliyun hbr delete-backup-plan` | DeleteBackupPlan | Delete/cancel a backup plan (删除/取消备份计划) | Yes |
| HBR | `aliyun hbr update-backup-plan` | UpdateBackupPlan | Update a backup plan (schedule/priority, etc.) (更新备份计划) | Yes |
| HBR | `aliyun hbr describe-backup-jobs-2` | DescribeBackupJobs2 | Query backup job list (查询备份任务列表) | Yes |
| HBR | `aliyun hbr describe-backup-clients` | DescribeBackupClients | Query backup client status (查询备份客户端状态) | Yes |
| HBR | `aliyun hbr search-historical-snapshots` | SearchHistoricalSnapshots | Search historical backup snapshots (搜索历史备份版本) | Yes |
| HBR | `aliyun hbr get-basic-statistics` | GetBasicStatistics | Get basic statistics including capacity (获取基础统计信息) | Yes |
| HBR | `aliyun hbr create-restore-job` | CreateRestoreJob | Create a restore job (创建恢复任务) | Yes |
| HBR | `aliyun hbr describe-restore-jobs-2` | DescribeRestoreJobs2 | Query restore job status (查询恢复任务状态) | Yes |
## API Version Information
| Product | API Version | Endpoint |
|---------|-------------|----------|
| HBR (Cloud Backup, 云备份) | 2017-09-08 | hbr.{region}.aliyuncs.com |
## Key Parameter Descriptions
### edition
- `BASIC` - Essential Edition (基础版, for ECS File Backup Essential Edition)
### source-type
- `ECS_FILE` - ECS file backup (ECS文件备份)
### performanceLevel (Backup Priority, 备份优先级)
| Value | Meaning | Max Throughput | Recommended Data Volume |
|-------|---------|----------------|-------------------------|
| `L0` | Low priority (低优先级) | 10 MB/s, 1 vCPU | < 600 GB |
| `L1` | High priority (高优先级) | 30 MB/s, 2 vCPU | < 2 TB |
### Backup Plan Status (备份计划状态)
| Status | Description |
|--------|-------------|
| `ENABLED` | Enabled (已启用) |
| `DISABLED` | Paused (已暂停) |
### Client Status (客户端状态)
| Status | Description |
|--------|-------------|
| Preparing (准备中) | Client is being installed |
| Ready (就绪) | Client is ready |
| Backing Up (备份中) | Backup is in progress |
## Console-Only Operations (Not Available via CLI)
The following features are currently **not available via CLI** and require console access:
| Feature | Description | Console Path |
|---------|-------------|--------------|
| Backup Overview Dashboard | Visual display of backed-up ECS instances, block storage capacity, etc. | Cloud Backup Console > ECS File Backup Essential Edition |
| Browse File Directory | Browse the directory structure of backed-up files online | Backup Plan Details > Browse Files |
| Selective Single-File Restore | Select specific files to restore through the UI | Backup Plan Details > Restore Files |
| Modify Backup Time Window | Change the daily backup start time | Backup Plan Details > Edit |
## References
- [Cloud Backup API Documentation](https://help.aliyun.com/zh/cloud-backup/developer-reference/api-hbr-2017-09-08-overview)
- [ECS File Backup Essential Edition User Guide](https://help.aliyun.com/zh/cloud-backup/user-guide/ecs-file-backup-essential-edition)
FILE:references/verification-method.md
# Verification Methods - ECS File Backup Essential Edition
This document describes how to verify that each operation has been executed successfully.
## 1. Activate Backup Verification
### Verification Steps
**Step 1: Confirm the backup plan has been created**
```bash
aliyun hbr describe-backup-plans \
--region <REGION_ID> \
--edition BASIC \
--source-type ECS_FILE \
--filters '[{"Key":"instanceId","Values":["<INSTANCE_ID>"]}]' \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-cloudbackup-ecs-file-backup-essential-edition
```
**Expected Result**:
- The `BackupPlans` array contains a backup plan for the corresponding instance
- `BusinessStatus` is `ACTIVE`
**Step 2: Confirm backup job status**
```bash
aliyun hbr describe-backup-jobs-2 \
--region <REGION_ID> \
--edition BASIC \
--source-type ECS_FILE \
--filters '[{"Key":"instanceId","Values":["<INSTANCE_ID>"]}]' \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-cloudbackup-ecs-file-backup-essential-edition
```
**Expected Result**:
- The first record returned is the latest backup job (sorted by creation time in descending order)
- `Status` is `COMPLETE` or `PARTIAL_COMPLETE`, indicating a successful backup
### Success Criteria
- Backup plan `BusinessStatus` is `ACTIVE`
- Latest backup job `Status` is `COMPLETE` or `PARTIAL_COMPLETE`
---
## 2. Pause Backup Verification
### Verification Steps
```bash
aliyun hbr describe-backup-plans \
--region <REGION_ID> \
--edition BASIC \
--source-type ECS_FILE \
--filters '[{"Key":"planId","Values":["<PLAN_ID>"]}]' \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-cloudbackup-ecs-file-backup-essential-edition
```
**Expected Result**:
- The `Disabled` field is `true`
### Success Criteria
- Backup plan `Disabled` is `true`
- No new backup jobs are generated
---
## 3. Resume Backup Verification
### Verification Steps
```bash
aliyun hbr describe-backup-plans \
--region <REGION_ID> \
--edition BASIC \
--source-type ECS_FILE \
--filters '[{"Key":"planId","Values":["<PLAN_ID>"]}]' \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-cloudbackup-ecs-file-backup-essential-edition
```
**Expected Result**:
- The `Disabled` field is `false`
### Success Criteria
- Backup plan `Disabled` is `false`
- The next backup window will execute a backup job
---
## 4. Cancel Backup Verification
### Verification Steps
```bash
# Check whether the backup plan has been deleted
aliyun hbr describe-backup-plans \
--region <REGION_ID> \
--edition BASIC \
--source-type ECS_FILE \
--filters '[{"Key":"instanceId","Values":["<INSTANCE_ID>"]}]' \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-cloudbackup-ecs-file-backup-essential-edition
```
**Expected Result**:
- The `BackupPlans` array is empty
- Or it does not contain a backup plan for the specified instance
### Success Criteria
- No backup plan found for the corresponding instance
- The instance is no longer billed
---
## 5. Free Quota Viewing Verification
### Verification Steps
```bash
aliyun hbr get-basic-statistics \
--edition BASIC \
--source-type ECS_FILE \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-cloudbackup-ecs-file-backup-essential-edition
```
**Expected Result**:
- Returns a `GlobalStatistics` object
- Contains the `ProtectedDataSize` field (unit: bytes)
### Key Metric Interpretation
| Metric | Description |
|--------|-------------|
| `ProtectedDataSize` | Total block storage capacity of backed-up ECS instances (bytes) |
| Free Quota (免费额度) | 100 GiB/account (permanent, shared across all regions) = 107,374,182,400 bytes |
**Calculation Example**:
```
ProtectedDataSize = 53,687,091,200 bytes = 50 GiB
Remaining Free Quota = 100 GiB - 50 GiB = 50 GiB
```
### Success Criteria
- The `ProtectedDataSize` value is retrieved successfully
- The value matches the console display
---
## 6. File Restore Verification
### Verification Steps
**Step 1: Query status after creating a restore job**
```bash
aliyun hbr describe-restore-jobs-2 \
--region <REGION_ID> \
--edition BASIC \
--restore-type ECS_FILE \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-cloudbackup-ecs-file-backup-essential-edition
```
**Expected Result**:
- The newly created restore job can be found
- The `Status` field shows the job status
### Restore Job Status Descriptions
| Status | Description |
|--------|-------------|
| `CREATED` | Job has been created (任务已创建) |
| `RUNNING` | Restore in progress (正在恢复) |
| `COMPLETE` | Restore completed (恢复完成) |
| `FAILED` | Restore failed (恢复失败) |
| `CANCELED` | Canceled (已取消) |
### Success Criteria
- Restore job status is `COMPLETE`
- Restored files are visible on the target ECS instance
---
## General Troubleshooting
### Common Errors and Solutions
| Error Message | Possible Cause | Solution |
|---------------|----------------|----------|
| `InvalidInstanceId` | ECS instance ID does not exist | Verify the instance ID is correct |
| `Forbidden.RAM` | Insufficient permissions | Check RAM policy configuration |
| `ServiceNotActivated` | Service not enabled | Run `open-hbr-service` first |
| `ClientNotInstalled` | Cloud Assistant (云助手) not installed | Install Cloud Assistant Agent on the ECS instance |
### Debug Command
```bash
# Enable verbose logging
aliyun hbr describe-backup-plans \
--region cn-hangzhou \
--edition BASIC \
--source-type ECS_FILE \
--log-level=debug \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-cloudbackup-ecs-file-backup-essential-edition
```
Deploy Alibaba Cloud official tech solutions. Trigger when the user mentions an Alibaba Cloud solution, pastes a solution URL (aliyun.com/solution/tech-solut...
---
name: alibabacloud-solution-deploy
description: >
Deploy Alibaba Cloud official tech solutions. Trigger when the user mentions
an Alibaba Cloud solution, pastes a solution URL (aliyun.com/solution/tech-solution/...),
or wants to deploy an official solution template. Covers both Terraform module
deployment and CLI step-by-step execution paths.
---
# Alibaba Cloud Solution Deploy
Match the user's scenario to the best execution path (Terraform or CLI), then complete the task end-to-end.
## Core Principles
### Maximum Automation
If 10 steps are needed and 9 can be automated, automate all 9. Only pause for the 1 that genuinely requires human action. Every cloud operation that has a CLI path should use it — the user came to you precisely so they don't have to click through consoles.
### CLI-First, Console-Last
Express every cloud action as a runnable `aliyun` CLI command. Only fall back to console when no CLI exists — and when you do, give a **direct deep-linked URL** (not a product homepage). The difference between `https://vision.aliyun.com/facebody` and `https://console.aliyun.com/` is the difference between being helpful and being useless.
### Never Guess — Verify First
- **CLI syntax**: Run `aliyun <product> <command> --help` before constructing commands. Parameter naming is inconsistent across products — `--RegionId` vs `--region-id` vs `--region` all exist.
- **Errors**: Run `diagnose_cli_command.py` immediately on failure. Error messages from the Alibaba Cloud API are often cryptic — the diagnosis script calls a specialized endpoint that maps error codes to fixes.
---
## Workflow
### Step 0: Verify Environment
Run this first in any new session:
> **Pre-check: Aliyun CLI >= 3.3.1 required**
>
> Run `aliyun version` to verify >= 3.3.1. If not installed or version too low, see [installation guide](references/aliyun-cli-installation-guide.md) for instructions.
>
> Then run the following command to enable automatic plugin installation and set the agent user-agent:
> ```bash
> aliyun configure set --auto-plugin-install true --user-agent AlibabaCloud-Agent-Skills
> ```
> This ensures product-specific CLI plugins are downloaded on first use (no manual install needed), and identifies requests as coming from this skill.
Then run the full environment check:
```bash
bash {{SKILL_PATH}}/scripts/verify_env.sh
```
This checks: CLI version, valid credentials, auto-plugin-install, Python3 + SDK. If any check fails, tell the user what to fix and stop — a broken environment means every subsequent command will fail.
#### RAM Permission Pre-check
Before executing any commands, verify the current user has the required permissions:
1. Compare the user's permissions against [references/ram-policies.md](references/ram-policies.md)
2. If any permission is missing, abort and prompt the user to attach the required policy
Minimum required permissions are listed in [references/ram-policies.md](references/ram-policies.md).
### Step 1: Understand the Scenario
Extract from the user's request:
- **What** they want to build or configure
- **Which Alibaba Cloud products** are involved (or can be inferred)
- **Key requirements**: region, instance specs, budget, HA needs, environment (dev/staging/prod)
Distill into search keywords (Chinese + English) for Step 2. For example, "我要搭个RAG知识库" → keywords: `RAG`, `知识库`, `AnalyticDB`, `百炼`.
### Step 2: Route to the Right Path
Check `references/alicloud-tech-solutions-all.md` — the master catalog of 187 Alibaba Cloud tech solutions. Search by keyword match against the solution names and descriptions.
Each row has a `Terraform Module 名称` column:
- **Column has a value** (e.g., `analyticdb-rag`, `deepseek-personal-website`) → **Path A: Terraform**
- **Column is empty or no matching solution found** → **Path B: CLI-First**
Also use [intent-mapping.md](references/intent-mapping.md) for fuzzy keyword → solution matching (e.g., "小程序" → `develop-your-wechat-mini-program-in-10-minutes`).
Tell the user which path you're taking and why before proceeding.
---
## Path A: Terraform Solution
When a Terraform module matches, deploy through the IaCService remote runtime — no local `terraform` binary needed.
### A.1: Locate the Module
Look up the Module 名称 and Module 地址 in `references/tf-plan/tf-solutions.md`. Match by:
1. Exact module name from the master catalog
2. Keyword match against the 描述 column
3. [Intent mapping](references/intent-mapping.md)
### A.2: Fetch Example Parameters
Every module has a GitHub repo with tested examples. Derive the URLs:
```
Module 地址: https://registry.terraform.io/modules/alibabacloud-automation/<name>/alicloud/latest
GitHub repo: https://github.com/alibabacloud-automation/terraform-alicloud-<name>
Example: https://raw.githubusercontent.com/alibabacloud-automation/terraform-alicloud-<name>/main/examples/complete/main.tf
```
Fetch the example `main.tf` via WebFetch. These values come from real tested deployments — they're far more reliable than generic defaults.
**Parameter priority:**
1. User explicitly specified → always use
2. Example `main.tf` from `examples/complete/` → use as default
3. Fallback defaults (only if fetch fails): see [terraform-defaults.md](references/terraform-defaults.md)
### A.3: Confirm with User
Show the parameters and ask for confirmation. Never silently apply them — cloud resources cost real money.
```
以下是基于官方示例的部署参数,请确认或修改:
• Region: cn-hangzhou
• Instance type: ecs.c7.large
• VPC CIDR: 172.16.0.0/12
• Password: (请提供)
```
Sensitive values like passwords and API keys: never generate them yourself. The user provides these.
### A.4: Write main.tf and Deploy
```hcl
# Based on: https://github.com/alibabacloud-automation/terraform-alicloud-<name>/blob/main/examples/complete/main.tf
module "<module_name>" {
source = "alibabacloud-automation/<module_name>/alicloud"
version = "~> 1.0"
# Parameters adjusted per user confirmation
}
```
Deploy using the remote runtime — see [terraform-online-runtime.md](references/terraform-online-runtime.md) for full usage:
```bash
SKILL_DIR="{{SKILL_PATH}}"
TF="SKILL_DIR/scripts/terraform_runtime_online.sh"
STATE_ID=$($TF apply main.tf | grep '^STATE_ID=' | cut -d= -f2)
echo "STATE_ID=$STATE_ID" >> terraform_state_ids.env
```
The STATE_ID is required for any future update or destroy. Losing it means you lose control over the resources.
### A.5: Verify and Report
Confirm resources exist. Provide the destroy command for cleanup.
---
## Path B: CLI-First Execution
This path handles everything without a Terraform template. The approach: understand the architecture → decompose into steps → find the CLI command for each step → execute.
### B.1: Understand the Architecture
Before writing any commands, understand what you're building:
- If the master catalog had a matching solution (just without TF Module), it still has **tutorial links** (部署教程 column). Fetch that page to understand the target architecture, required products, and deployment sequence. This gives you the blueprint — you'll then translate each step into CLI commands.
- If no solution matched at all, reason from the user's description: what products are needed, what depends on what, what's the end state.
### B.2: Decompose into Steps
Break the goal into atomic steps ordered by dependency. Think through:
- **Resource creation order**: VPC → VSwitch → Security Group → ECS is almost always the foundation
- **ID chaining**: which step outputs IDs that later steps need (VpcId → CreateVSwitch, VSwitchId → RunInstances)
- **Async operations**: some create calls return immediately but the resource takes time — you'll need to poll
- **What might not have a CLI**: some product activations, some console-only features
### B.3: Research CLI Commands
For each step, use the scripts to find the correct API name and parameters. This is critical — don't rely on memory. Alibaba Cloud has thousands of APIs, and parameter names are inconsistent across products.
```bash
python3 {{SKILL_PATH}}/scripts/lsit_products.py '<keyword>' # Find product code + API version
python3 {{SKILL_PATH}}/scripts/search_apis.py '<what you want to do>' # Natural language → API
python3 {{SKILL_PATH}}/scripts/search_documents.py '<topic>' # Parameter details, valid values, constraints
python3 {{SKILL_PATH}}/scripts/lsit_api_overview.py <Product> <version> # Full API list for a product
```
Run scripts in parallel when researching multiple products — don't serialize what can be parallelized.
**Common CLI shortcuts that avoid console entirely:**
| Scenario | CLI Command | Notes |
|----------|------------|-------|
| Get Bailian (百炼) API Key | `aliyun modelstudio list-workspaces` → `aliyun modelstudio create-api-key --WorkspaceId <id>` | Avoids console entirely. Almost every AI solution needs this. |
| Run commands on ECS | `aliyun ecs RunCommand --Type RunShellScript --CommandContent '<script>' --InstanceId.1 <id>` | Use Cloud Assistant instead of asking the user to SSH in. |
| OSS operations | `aliyun ossutil cp/ls/mb ...` | Use `ossutil` subcommand, not `oss`. |
The Bailian API Key pattern is especially important — nearly every AI-related solution needs a DashScope/Bailian SK, and users often don't know it can be obtained programmatically. Whenever a plan involves 百炼/Bailian/DashScope, proactively use the `modelstudio` commands to get the key.
### B.4: Present Plan and Confirm
Before running any write operations, show the complete execution plan. The plan MUST include a **RAM permissions section** listing all permissions the current account needs — this lets the user verify access before execution starts, avoiding mid-deploy `Forbidden.RAM` errors.
Derive the required permissions from the planned CLI commands: each `aliyun <product> <API>` call maps to a RAM action in the form `<product>:<API>` (e.g., `aliyun vpc CreateVpc` → `vpc:CreateVpc`).
```
所需 RAM 权限:
| 云产品 | 所需权限 (Action) | 对应步骤 | 快捷策略 |
|--------|-------------------|----------|----------|
| VPC | vpc:CreateVpc, vpc:CreateVSwitch, vpc:DescribeVpcs | 步骤 1-2 | AliyunVPCFullAccess |
| ECS | ecs:RunInstances, ecs:DescribeInstances, ecs:RunCommand | 步骤 4-6 | AliyunECSFullAccess |
| EIP | vpc:AllocateEipAddress, vpc:AssociateEipAddress | 步骤 3 | AliyunEIPFullAccess |
提示: 可使用快捷策略快速授权,或按 Action 列配置最小权限自定义策略。
---
执行计划 (共 N 步, M 步 CLI 自动化, K 步需控制台):
步骤 1 — 创建 VPC
aliyun vpc CreateVpc --RegionId cn-hangzhou --CidrBlock 172.16.0.0/12 --VpcName demo-vpc
步骤 2 — 创建交换机 (依赖: 步骤1 VpcId)
aliyun vpc CreateVSwitch --RegionId cn-hangzhou --VpcId <步骤1> --ZoneId cn-hangzhou-h --CidrBlock 172.16.0.0/24
步骤 3 — [控制台] 开通视觉智能 API (无 CLI)
打开: https://vision.aliyun.com/facebody → 点击 "立即开通"
```
Wait for user approval. Cloud resources cost money, and some operations (like deleting RDS instances) are irreversible.
### B.5: Execute
For each step:
1. **Verify syntax first**: `aliyun <product> <api> --help` — catch parameter errors before they hit the API
2. **Run the command**
3. **Verify result**: poll async operations; describe the resource to confirm it exists
4. **Capture output**: save IDs, endpoints, connection strings for subsequent steps and final report
### B.6: Handle Errors
When a command fails:
```bash
python3 {{SKILL_PATH}}/scripts/diagnose_cli_command.py '<the full command>' '<the error message>'
```
The diagnosis script calls a specialized API that maps error codes to actionable fixes. Apply the fix and retry. If the same error persists after the fix, report to the user with the diagnosis — don't keep retrying blindly.
Resume from the failed step. Never re-run steps that already succeeded — those resources already exist and re-running would either fail (duplicate) or create unwanted duplicates.
### B.7: Report
Summarize:
- Resources created (with IDs)
- Access endpoints / connection strings
- How to use what was built
- Cleanup commands (delete in reverse dependency order: ECS → Security Group → VSwitch → VPC)
---
## Script Reference
| Script | Purpose | Example |
|--------|---------|---------|
| `verify_env.sh` | Environment check | `bash {{SKILL_PATH}}/scripts/verify_env.sh` |
| `lsit_products.py` | Find product code + version | `python3 {{SKILL_PATH}}/scripts/lsit_products.py 'ECS'` |
| `search_apis.py` | Natural language → API | `python3 {{SKILL_PATH}}/scripts/search_apis.py '创建ECS实例'` |
| `search_documents.py` | Doc search for details | `python3 {{SKILL_PATH}}/scripts/search_documents.py 'ECS实例规格'` |
| `lsit_api_overview.py` | Full API list for a product | `python3 {{SKILL_PATH}}/scripts/lsit_api_overview.py Ecs 2014-05-26` |
| `diagnose_cli_command.py` | Diagnose CLI errors | `python3 {{SKILL_PATH}}/scripts/diagnose_cli_command.py '<cmd>' '<err>'` |
| `terraform_runtime_online.sh` | Remote TF execution | See [terraform-online-runtime.md](references/terraform-online-runtime.md) |
## References
- [Intent Mapping](references/intent-mapping.md) — keyword → solution mapping
- [Terraform Defaults](references/terraform-defaults.md) — default parameter values
- [Terraform Online Runtime](references/terraform-online-runtime.md) — IaCService script usage
- [All Tech Solutions Catalog](references/alicloud-tech-solutions-all.md) — 187 solutions with TF Module availability
- [TF Solutions Detail](references/tf-plan/tf-solutions.md) — 48 Terraform modules with Registry addresses
FILE:references/alicloud-tech-solutions-all.md
# 阿里云技术解决方案全览
> 数据来源:https://www.aliyun.com/solution/tech-solution
> 共 **187** 个解决方案 | 🆓 免费部署
**部署方式说明**:
- **官网控制台部署**:通过阿里云控制台界面手动操作部署
- **Terraform 模板 IaC 部署**:通过 Terraform 代码基础设施即代码方式部署
- **ROS 模板 IaC 部署**:通过阿里云 ROS 资源编排服务模板部署
## AI(74 个解决方案)
### 模型应用与工具
| 解决方案名称 | 链接 | 部署教程 | 部署方式 | Terraform Module 名称 |
| --- | --- | --- | --- | --- |
| 部署 HiClaw,打造专属 AI 多员工团队 | [查看](https://www.aliyun.com/solution/tech-solution/hiclaw/3023557) | [部署 HiClaw,打造专属 AI 多员工团队 🆓](https://www.aliyun.com/solution/tech-solution/hiclaw/3023557)(官网控制台部署) | 官网控制台部署 | |
| 5 分钟轻松部署专属 CoPaw | [查看](https://www.aliyun.com/solution/tech-solution/copaw/3023684) | [5 分钟轻松部署专属 CoPaw 🆓](https://www.aliyun.com/solution/tech-solution/copaw/3023684)(官网控制台部署) | 官网控制台部署 | |
| 快速拥有专属 OpenClaw | [查看](https://www.aliyun.com/solution/tech-solution/clawdbot/3018681) | [基于 OpenClaw 4 步构建 AI 员工 🆓](https://www.aliyun.com/solution/tech-solution/clawdbot/3018681)(官网控制台部署) | 官网控制台部署 | |
| 从单帧到叙事,开启 AI 视觉创作 | [查看](https://www.aliyun.com/solution/tech-solution/tongyi-wan-two-point-six/3004348) | [从单帧到叙事,开启 AI 视觉创作 🆓](https://www.aliyun.com/solution/tech-solution/tongyi-wan-two-point-six/3004348)(官网控制台部署) | 官网控制台部署 | |
| 千问与 LangChain 搭建对话服务 | [查看](https://www.aliyun.com/solution/tech-solution/tongyi-langchain/2708788) | [千问和LangChain搭建对话服务](https://www.aliyun.com/solution/tech-solution/tongyi-langchain/2708788)(官网控制台部署、ROS 模板 IaC 部署) | ROS 模板 IaC 部署、官网控制台部署 | `tongyi-langchain` |
| 向量检索与千问搭建专属问答服务 | [查看](https://www.aliyun.com/solution/tech-solution/dashvector/2754433) | [向量检索与千问搭建专属问答服务](https://www.aliyun.com/solution/tech-solution/dashvector/2754433)(官网控制台部署、ROS 模板 IaC 部署) | ROS 模板 IaC 部署、官网控制台部署 | |
| AnalyticDB 与千问搭建 AI 客服 | [查看](https://www.aliyun.com/solution/tech-solution/analyticdb-rag/2837375) | [AnalyticDB与千问搭建AI智能客服](https://www.aliyun.com/solution/tech-solution/analyticdb-rag/2837375)(官网控制台部署、ROS 模板 IaC 部署) | ROS 模板 IaC 部署、官网控制台部署 | `analyticdb-rag` |
| n8n+百炼:自动获取AI热点资讯 | [查看](https://www.aliyun.com/solution/tech-solution/n8n-workflow/2987524) | [n8n+阿里云百炼:搭建自动获取AI热点的工作流](https://www.aliyun.com/solution/tech-solution/n8n-workflow/2987524)(官网控制台部署) | 官网控制台部署 | |
| PAI部署Stable Diffusion WebUI服务 | [查看](https://www.aliyun.com/solution/tech-solution/pai-eas/2509703) | [PAI 部署多形态的 Stable Diffusion WebUI 服务](https://www.aliyun.com/solution/tech-solution/pai-eas/2509703)(官网控制台部署) | 官网控制台部署 | `pai-eas-stable-diffusion` |
| 文档智能与 RAG 构建 LLM 知识库 | [查看](https://www.aliyun.com/solution/tech-solution/document-mind-rag-for-llm/2845368) | [文档智能 & RAG ,让你的 AI 大模型开启“外挂”之旅](https://www.aliyun.com/solution/tech-solution/document-mind-rag-for-llm/2845368)(官网控制台部署) | 官网控制台部署 | |
| 与 AI 智能体进行实时音视频通话 | [查看](https://www.aliyun.com/solution/tech-solution/real-time-interaction/2847614) | [AI 语音通话](https://www.aliyun.com/solution/tech-solution/real-time-interaction/2847614)(官网控制台部署)<br/>[与 AI 智能体进行实时音视频通话](https://www.aliyun.com/solution/tech-solution/real-time-interaction/2864478)(官网控制台部署) | 官网控制台部署 | |
| 码力全开,实现企业级 AI 编码 | [查看](https://www.aliyun.com/solution/tech-solution/intelligent-coding/2857059) | [AI 编码,码力全开,通义灵码引领研发新范式](https://www.aliyun.com/solution/tech-solution/intelligent-coding/2857059)(官网控制台部署) | 官网控制台部署 | |
| 在 App 上搭建开箱即用的 AI 助手 | [查看](https://www.aliyun.com/solution/tech-solution/add-copilot-by-miniappdev/2858000) | [在 App 上搭建开箱即用的 AI 助手](https://www.aliyun.com/solution/tech-solution/add-copilot-by-miniappdev/2858000)(官网控制台部署) | 官网控制台部署 | |
| AI 智能陪练,学习与培训的新体验 | [查看](https://www.aliyun.com/solution/tech-solution/ai-training-companion/2865020) | [AI 企业内部培训](https://www.aliyun.com/solution/tech-solution/ai-training-companion/2865020)(官网控制台部署)<br/>[AI 英语口语陪练](https://www.aliyun.com/solution/tech-solution/ai-training-companion/2861523)(官网控制台部署) | 官网控制台部署 | |
| 快速部署 Dify,高效搭建 AI 应用 | [查看](https://www.aliyun.com/solution/tech-solution/rapidly-deploy-dify-to-accelerate-ai-application-development/2876504) | [搭建智能问答 AI 电商客服助手](https://www.aliyun.com/solution/tech-solution/rapidly-deploy-dify-to-accelerate-ai-application-development/2876504)(官网控制台部署)<br/>[搭建复杂业务流程管理的对话流(Chatflow)AI 电商客服助手](https://www.aliyun.com/solution/tech-solution/rapidly-deploy-dify-to-accelerate-ai-application-development/2876508)(官网控制台部署)<br/>[通过 Serverless 应用引擎部署生产环境 Dify 平台](https://www.aliyun.com/solution/tech-solution/rapidly-deploy-dify-to-accelerate-ai-application-development/2882552)(官网控制台部署)<br/>[搭建自主决策的智能体(Agent)AI 电商客服助手](https://www.aliyun.com/solution/tech-solution/rapidly-deploy-dify-to-accelerate-ai-application-development/2876507)(官网控制台部署)<br/>[部署测试环境 Dify 平台](https://www.aliyun.com/solution/tech-solution/rapidly-deploy-dify-to-accelerate-ai-application-development/2870155)(官网控制台部署)<br/>[部署生产环境 Dify 平台](https://www.aliyun.com/solution/tech-solution/rapidly-deploy-dify-to-accelerate-ai-application-development/2871859)(官网控制台部署)<br/>[搭建检索增强生成(RAG)驱动的智能问答 AI 电商客服助手](https://www.aliyun.com/solution/tech-solution/rapidly-deploy-dify-to-accelerate-ai-application-development/2876505)(官网控制台部署)<br/>[通过 Serverless 应用引擎部署测试环境 Dify 平台](https://www.aliyun.com/solution/tech-solution/rapidly-deploy-dify-to-accelerate-ai-application-development/2948807)(官网控制台部署) | 官网控制台部署 | |
| 零代码搭建 DeepSeek 版个人知识库 | [查看](https://www.aliyun.com/solution/tech-solution/deepseek-and-mobi-build-personal-space/2871950) | [零代码搭建 DeepSeek 版个人知识库](https://www.aliyun.com/solution/tech-solution/deepseek-and-mobi-build-personal-space/2871950)(官网控制台部署) | 官网控制台部署 | |
| 低成本搭建 DeepSeek 专属 AI 网站 | [查看](https://www.aliyun.com/solution/tech-solution/ecs-and-deepseek-build-personal-website/2872381) | [低成本搭建 DeepSeek 个人专属 AI 网站 🆓](https://www.aliyun.com/solution/tech-solution/ecs-and-deepseek-build-personal-website/2872381)(官网控制台部署) | 官网控制台部署 | `deepseek-personal-website` |
| 千问3 + MCP:一切皆有可能 | [查看](https://www.aliyun.com/solution/tech-solution/mcp-agent/2880695) | [快速构建增强型智能体,并集成高德地图的 MCP Server,实现智能旅行规划 🆓](https://www.aliyun.com/solution/tech-solution/mcp-agent/2880695)(官网控制台部署)<br/>[集成专属 MCP Server,实现网页的智能开发和部署](https://www.aliyun.com/solution/tech-solution/mcp-agent/2880750)(官网控制台部署) | 官网控制台部署 | |
| MetaGPT 构建多智能体协作系统 | [查看](https://www.aliyun.com/solution/tech-solution/meta-gpt/2882578) | [MetaGPT 构建多智能体协作系统 🆓](https://www.aliyun.com/solution/tech-solution/meta-gpt/2882578)(官网控制台部署) | 官网控制台部署 | |
| 告别低效沟通,使用大模型发起语音通话 | [查看](https://www.aliyun.com/solution/tech-solution/ai-voice-assistant/2921947) | [告别低效沟通,使用大模型发起语音通话](https://www.aliyun.com/solution/tech-solution/ai-voice-assistant/2921947)(官网控制台部署) | 官网控制台部署 | |
| 基于 RAGFlow 构建私有知识问答应用 | [查看](https://www.aliyun.com/solution/tech-solution/build-rag-qa-assistant-based-on-ragflow/2926764) | [基于RAGFlow构建私有知识问答应用](https://www.aliyun.com/solution/tech-solution/build-rag-qa-assistant-based-on-ragflow/2926764)(官网控制台部署) | 官网控制台部署 | |
| JManus解锁AI Agent高效开发 | [查看](https://www.aliyun.com/solution/tech-solution/sae-deploy-jmanus/2938626) | [通过Serverless应用引擎部署JManus](https://www.aliyun.com/solution/tech-solution/sae-deploy-jmanus/2938626)(官网控制台部署) | 官网控制台部署 | |
| AI 视频翻译:打破语言壁垒,连接全球观众 | [查看](https://www.aliyun.com/solution/tech-solution/one-stop-ai-video-translation-services/2937860) | [AI 视频翻译:打破语言壁垒,连接全球观众](https://www.aliyun.com/solution/tech-solution/one-stop-ai-video-translation-services/2937860)(官网控制台部署) | 官网控制台部署 | |
| 支付宝MCP,让您的AI应用自动收款 | [查看](https://www.aliyun.com/solution/tech-solution/alipay-mcp/2938758) | [集成支付宝MCP Server,为您的智能体应用添加收款功能](https://www.aliyun.com/solution/tech-solution/alipay-mcp/2938758)(官网控制台部署) | 官网控制台部署 | |
| 告别手动操作,让AI知识库自动更新 | [查看](https://www.aliyun.com/solution/tech-solution/auto-updated-knowledge-base/2948704) | [告别手动操作,让AI知识库自动更新](https://www.aliyun.com/solution/tech-solution/auto-updated-knowledge-base/2948704)(官网控制台部署) | 官网控制台部署 | |
| 跨应用和平台,AI记忆不再丢失 | [查看](https://www.aliyun.com/solution/tech-solution/cross-platform-ai-memory/2974766) | [跨应用和平台,AI记忆不再丢失](https://www.aliyun.com/solution/tech-solution/cross-platform-ai-memory/2974766)(官网控制台部署) | 官网控制台部署 | |
| LightRAG:轻量级知识图谱RAG系统 | [查看](https://www.aliyun.com/solution/tech-solution/lightrag/2928778) | [快速部署LightRAG:轻量级知识图谱RAG系统](https://www.aliyun.com/solution/tech-solution/lightrag/2928778)(官网控制台部署) | 官网控制台部署 | |
| 使用kubectl-ai助力ACK集群运维提效 | [查看](https://www.aliyun.com/solution/tech-solution/optimize-ack-om-with-kubectl-ai/2936629) | [使用kubectl-ai助力ACK集群运维提效](https://www.aliyun.com/solution/tech-solution/optimize-ack-om-with-kubectl-ai/2936629)(官网控制台部署) | 官网控制台部署 | |
| ETL For AI Data:一站式构建AI数据处理平台 | [查看](https://www.aliyun.com/solution/tech-solution/etl-for-ai-data-a-one-stop-platform-for-ai-data-processing/2979974) | [多源 RAG 处理方案:为 AI 场景提供高效数据管道 🆓](https://www.aliyun.com/solution/tech-solution/etl-for-ai-data-a-one-stop-platform-for-ai-data-processing/2979974)(官网控制台部署)<br/>[AI 数据推理方案:AI 赋能数据处理能力 🆓](https://www.aliyun.com/solution/tech-solution/etl-for-ai-data-a-one-stop-platform-for-ai-data-processing/2983230)(官网控制台部署) | 官网控制台部署 | |
| 通义灵码一站式定制专属MCP服务 | [查看](https://www.aliyun.com/solution/tech-solution/customize-mcp-server/2927225) | [定制专属MCP服务,通义灵码智能体一站式搞定](https://www.aliyun.com/solution/tech-solution/customize-mcp-server/2927225)(官网控制台部署) | 官网控制台部署 | |
| 通义听悟:全场景语音对话分析,自动化提炼业务洞察 | [查看](https://www.aliyun.com/solution/tech-solution/tingwu/2980305) | [快速上手通义听悟通用服务洞察](https://www.aliyun.com/solution/tech-solution/tingwu/2980305)(官网控制台部署)<br/>[快速上手通义听悟智能纪要应用](https://www.aliyun.com/solution/tech-solution/tingwu/2999887)(官网控制台部署) | 官网控制台部署 | |
| 千问+Vanna:让数据库听懂人话 | [查看](https://www.aliyun.com/solution/tech-solution/qwen-and-vanna-nl2sql/2928777) | [基于阿里云Milvus的RAG架构自然语言数据库问答系统](https://www.aliyun.com/solution/tech-solution/qwen-and-vanna-nl2sql/2928777)(官网控制台部署)<br/>[基于阿里云RDS PostgreSQL的RAG架构自然语言数据库问答系统](https://www.aliyun.com/solution/tech-solution/qwen-and-vanna-nl2sql/2937770)(官网控制台部署) | 官网控制台部署 | |
| RocketMQ for AI:企业级 AI 应用集成的异步通信方案 | [查看](https://www.aliyun.com/solution/tech-solution/rocketmq-for-multi-agent-communication/2990228) | [通过RocketMQ实现多智能体异步通信 🆓](https://www.aliyun.com/solution/tech-solution/rocketmq-for-multi-agent-communication/2990228)(官网控制台部署、Terraform 模板 IaC 部署)<br/>[通过RocketMQ解决会话异步通知和状态连续性的问题](https://www.aliyun.com/solution/tech-solution/rocketmq-for-multi-agent-communication/3015890)(官网控制台部署、Terraform 模板 IaC 部署) | Terraform 模板 IaC 部署、官网控制台部署 | `rocketmq-multi-agent-communication` |
| 企业私有 MCP 市场:实现 AI 工具的统一治理与安全分发 | [查看](https://www.aliyun.com/solution/tech-solution/mcp-market/2995859) | [使用计算巢快速部署企业私有MCP市场](https://www.aliyun.com/solution/tech-solution/mcp-market/2995859)(官网控制台部署) | 官网控制台部署 | |
| DeepSite一键生成专属网站 | [查看](https://www.aliyun.com/solution/tech-solution/deepsite/2938368) | [基于函数计算部署DeepSite](https://www.aliyun.com/solution/tech-solution/deepsite/2938368)(ROS 模板 IaC 部署)<br/>[通过ECS手动部署DeepSite](https://www.aliyun.com/solution/tech-solution/deepsite/2938367)(官网控制台部署、Terraform 模板 IaC 部署) | ROS 模板 IaC 部署、Terraform 模板 IaC 部署、官网控制台部署 | `ecs-deploy-deepsite-application` |
| 无限画布:让视频特效自由生长 | [查看](https://www.aliyun.com/solution/tech-solution/infinite-canvas/3019399) | [无限画布:让视频特效自由生长 🆓](https://www.aliyun.com/solution/tech-solution/infinite-canvas/3019399)(官网控制台部署) | 官网控制台部署 | |
| 漫剧工坊:一站式动画创作平台 | [查看](https://www.aliyun.com/solution/tech-solution/use-bailian-to-intelligently-create-comics/3018643) | [漫剧工坊:一站式动画创作平台 🆓](https://www.aliyun.com/solution/tech-solution/use-bailian-to-intelligently-create-comics/3018643)(官网控制台部署) | 官网控制台部署 | |
| AI 解题 + 批改:推动课程教学智变 | [查看](https://www.aliyun.com/solution/tech-solution/ai-homework-helper/3023071) | [AI 解题 + 批改:推动课程教学智变 🆓](https://www.aliyun.com/solution/tech-solution/ai-homework-helper/3023071)(官网控制台部署) | 官网控制台部署 | |
| 从热点追踪到洞察报告,AI一站式生成 | [查看](https://www.aliyun.com/solution/tech-solution/agentrun-trending-report/3009512) | [从热点到洞察报告,AI一站式生成](https://www.aliyun.com/solution/tech-solution/agentrun-trending-report/3009512)(官网控制台部署) | 官网控制台部署 | |
### 模型推理与调用
| 解决方案名称 | 链接 | 部署教程 | 部署方式 | Terraform Module 名称 |
| --- | --- | --- | --- | --- |
| 创意加速器:AI 绘画创作 | [查看](https://www.aliyun.com/solution/tech-solution/tongyi-wanxiang/2788326) | [创意加速器:AI 绘画创作](https://www.aliyun.com/solution/tech-solution/tongyi-wanxiang/2788326)(官网控制台部署、ROS 模板 IaC 部署) | ROS 模板 IaC 部署、官网控制台部署 | |
| 在聊天系统中增加一个 AI 助手 | [查看](https://www.aliyun.com/solution/tech-solution/build-a-chatbot-for-your-website-or-chat-system) | (暂无) | — | |
| 主动式智能导购 AI 助手构建 | [查看](https://www.aliyun.com/solution/tech-solution/build-an-ai-shopping-assistant) | (暂无) | — | |
| 构建 AI 总结助手,实现智能文档摘要 | [查看](https://www.aliyun.com/solution/tech-solution/bailian-ai-summary/2845047) | [构建 AI 总结助手,实现智能文档摘要](https://www.aliyun.com/solution/tech-solution/bailian-ai-summary/2845047)(官网控制台部署) | 官网控制台部署 | |
| 对话分析,让服务更懂客户 | [查看](https://www.aliyun.com/solution/tech-solution/conversation-analysis/2848682) | [对话分析,让服务更懂客户 🆓](https://www.aliyun.com/solution/tech-solution/conversation-analysis/2848682)(官网控制台部署) | 官网控制台部署 | |
| 精准识别,轻松集成人脸比对服务 | [查看](https://www.aliyun.com/solution/tech-solution/viapi-for-face-detection/2853965) | [精准识别,轻松集成人脸比对服务](https://www.aliyun.com/solution/tech-solution/viapi-for-face-detection/2853965)(官网控制台部署) | 官网控制台部署 | |
| AI 提效,轻松制作商品图 | [查看](https://www.aliyun.com/solution/tech-solution/ai-goods-image-generate/2865375) | [AI 商品图换装 🆓](https://www.aliyun.com/solution/tech-solution/ai-goods-image-generate/2865375)(官网控制台部署) | 官网控制台部署 | |
| 多模态数据信息提取 | [查看](https://www.aliyun.com/solution/tech-solution/information-extraction/2858610) | [文本信息提取 🆓](https://www.aliyun.com/solution/tech-solution/information-extraction/2858610)(官网控制台部署)<br/>[文档文件信息提取 🆓](https://www.aliyun.com/solution/tech-solution/information-extraction/2858611)(官网控制台部署)<br/>[图片OCR信息提取 🆓](https://www.aliyun.com/solution/tech-solution/information-extraction/2856973)(官网控制台部署)<br/>[图片结构化属性提取 🆓](https://www.aliyun.com/solution/tech-solution/information-extraction/2851499)(官网控制台部署)<br/>[视频理解与内容提取 🆓](https://www.aliyun.com/solution/tech-solution/information-extraction/2860032)(官网控制台部署) | 官网控制台部署 | |
| 一键生成PPT及讲解视频 | [查看](https://www.aliyun.com/solution/tech-solution/ai-for-ppt-to-video/2862477) | [一键生成,PPT及讲解视频](https://www.aliyun.com/solution/tech-solution/ai-for-ppt-to-video/2862477)(官网控制台部署) | 官网控制台部署 | |
| AI 剧本生成与动画创作 | [查看](https://www.aliyun.com/solution/tech-solution/animation-creation/2863572) | [AI 剧本生成与动画创作 🆓](https://www.aliyun.com/solution/tech-solution/animation-creation/2863572)(官网控制台部署) | 官网控制台部署 | |
| 一键创作 AI 有声绘本 | [查看](https://www.aliyun.com/solution/tech-solution/ai-audiobook-flow/2865113) | [一键创作 AI 有声绘本 🆓](https://www.aliyun.com/solution/tech-solution/ai-audiobook-flow/2865113)(官网控制台部署) | 官网控制台部署 | |
| 无需邀请码,OpenManus 搞定复杂任务 | [查看](https://www.aliyun.com/solution/tech-solution/open-manus/2878032) | [无需邀请码,OpenManus 搞定复杂任务 🆓](https://www.aliyun.com/solution/tech-solution/open-manus/2878032)(官网控制台部署) | 官网控制台部署 | |
| 高效搭建 AI 智能体与工作流应用 | [查看](https://www.aliyun.com/solution/tech-solution/build-ai-applications-based-on-alibaba-cloud-model-studio/2878136) | [通过百炼高效搭建 AI Agent 和工作流应用](https://www.aliyun.com/solution/tech-solution/build-ai-applications-based-on-alibaba-cloud-model-studio/2878136)(官网控制台部署、ROS 模板 IaC 部署)<br/>[零代码搭建数据标注工作流](https://www.aliyun.com/solution/tech-solution/build-ai-applications-based-on-alibaba-cloud-model-studio/2977204)(官网控制台部署) | ROS 模板 IaC 部署、官网控制台部署 | `ai-applications-model-studio` |
| AI建站:用Bolt.diy一句话生成网站 | [查看](https://www.aliyun.com/solution/tech-solution/bolt-diy/2878871) | [基于函数计算部署 Bolt.diy 🆓](https://www.aliyun.com/solution/tech-solution/bolt-diy/2878871)(官网控制台部署)<br/>[基于计算巢部署 Bolt.diy](https://www.aliyun.com/solution/tech-solution/bolt-diy/2928484)(官网控制台部署) | 官网控制台部署 | |
| Qwen-Image,生图告别文字乱码 | [查看](https://www.aliyun.com/solution/tech-solution/qwen-image/2978463) | [Qwen-Image实现图像生成与编辑 🆓](https://www.aliyun.com/solution/tech-solution/qwen-image/2978463)(官网控制台部署) | 官网控制台部署 | |
| 零代码搭建企业级图像与视频创作平台 | [查看](https://www.aliyun.com/solution/tech-solution/ai-image-video-creation-platform/2983088) | [一站式体验图像与视频生成](https://www.aliyun.com/solution/tech-solution/ai-image-video-creation-platform/2983088)(官网控制台部署) | 官网控制台部署 | |
| 在网站上增加一个 AI 助手 | [查看](https://www.aliyun.com/solution/tech-solution/add-an-ai-assistant-to-your-website-in-10-minutes/2861812) | [在网站上增加一个 AI 助手 🆓](https://www.aliyun.com/solution/tech-solution/add-an-ai-assistant-to-your-website-in-10-minutes/2861812)(官网控制台部署) | 官网控制台部署 | |
| 声音克隆:定制你的专属声线 | [查看](https://www.aliyun.com/solution/tech-solution/voice-cloning/3019432) | [声音克隆:定制你的专属声线 🆓](https://www.aliyun.com/solution/tech-solution/voice-cloning/3019432)(官网控制台部署) | 官网控制台部署 | |
| 告别昂贵摄制,一图生成高清数字人 | [查看](https://www.aliyun.com/solution/tech-solution/avatar/3019340) | [告别昂贵摄制,一图生成高清数字人 🆓](https://www.aliyun.com/solution/tech-solution/avatar/3019340)(官网控制台部署) | 官网控制台部署 | |
### 模型训练与部署
| 解决方案名称 | 链接 | 部署教程 | 部署方式 | Terraform Module 名称 |
| --- | --- | --- | --- | --- |
| 触手可及,函数计算玩转 AI 大模型 | [查看](https://www.aliyun.com/solution/tech-solution/fc-for-ai-server/2713176) | [基于函数计算部署 Stable Diffusion 实现高质量的图像生成](https://www.aliyun.com/solution/tech-solution/fc-for-ai-server/2713176)(官网控制台部署)<br/>[基于函数计算部署 GPT-Sovits 模型实现语音生成](https://www.aliyun.com/solution/tech-solution/fc-for-ai-server/2805773)(官网控制台部署)<br/>[基于函数计算快速部署开源大模型](https://www.aliyun.com/solution/tech-solution/fc-for-ai-server/2840266)(官网控制台部署)<br/>[通过函数计算部署 ComfyUI 以实现一个 AIGC 图像生成系统](https://www.aliyun.com/solution/tech-solution/fc-for-ai-server/2804364)(官网控制台部署) | 官网控制台部署 | |
| 挖掘及触达高价值用户 | [查看](https://www.aliyun.com/solution/tech-solution/pai-ugs/2412384) | [高价值用户挖掘及触达](https://www.aliyun.com/solution/tech-solution/pai-ugs/2412384)(官网控制台部署) | 官网控制台部署 | |
| 一键训练模型及部署GPU共享推理服务 | [查看](https://www.aliyun.com/solution/tech-solution/one-gpu/2510079) | [一键训练大模型及部署 GPU 共享推理服务](https://www.aliyun.com/solution/tech-solution/one-gpu/2510079)(官网控制台部署) | 官网控制台部署 | |
| 快速部署DeepSeek-OCR | [查看](https://www.aliyun.com/solution/tech-solution/deepseek-ocr/2996995) | [通过人工智能平台PAI部署DeepSeek-OCR模型](https://www.aliyun.com/solution/tech-solution/deepseek-ocr/2996995)(官网控制台部署) | 官网控制台部署 | |
| AI 打造专属企业风格海报 | [查看](https://www.aliyun.com/solution/tech-solution/pai-artlab-for-image-design/2856959) | [让视觉营销焕新,AI 打造专属企业风格海报](https://www.aliyun.com/solution/tech-solution/pai-artlab-for-image-design/2856959)(官网控制台部署) | 官网控制台部署 | |
| Qwen3 升级版,0元即刻上手 | [查看](https://www.aliyun.com/solution/tech-solution/use-qwen3-ranging-from-0-6b-to-235b/2883727) | [基于 GPU 云服务器部署 Qwen3](https://www.aliyun.com/solution/tech-solution/use-qwen3-ranging-from-0-6b-to-235b/2883727)(官网控制台部署)<br/>[基于人工智能平台 PAI 部署 Qwen3 模型](https://www.aliyun.com/solution/tech-solution/use-qwen3-ranging-from-0-6b-to-235b/2873194)(官网控制台部署)<br/>[基于函数计算 FC 部署 Qwen3 模型 🆓](https://www.aliyun.com/solution/tech-solution/use-qwen3-ranging-from-0-6b-to-235b/2881564)(官网控制台部署)<br/>[通过阿里云百炼调用 Qwen3-235B-A22B-Thinking-2507 模型 🆓](https://www.aliyun.com/solution/tech-solution/use-qwen3-ranging-from-0-6b-to-235b/2881565)(官网控制台部署) | 官网控制台部署 | |
| 即刻拥有 DeepSeek-R1 满血版或蒸馏版 | [查看](https://www.aliyun.com/solution/tech-solution/deepseek-r1-for-platforms/2868644) | [函数计算 FC 部署 DeepSeek-R1 模型 🆓](https://www.aliyun.com/solution/tech-solution/deepseek-r1-for-platforms/2868644)(官网控制台部署)<br/>[ACS 部署 DeepSeek-R1 满血版](https://www.aliyun.com/solution/tech-solution/deepseek-r1-for-platforms/2869201)(ROS 模板 IaC 部署)<br/>[ACK 部署 DeepSeek-R1 满血版](https://www.aliyun.com/solution/tech-solution/deepseek-r1-for-platforms/2870316)(官网控制台部署)<br/>[人工智能平台 PAI 部署 DeepSeek-R1 模型](https://www.aliyun.com/solution/tech-solution/deepseek-r1-for-platforms/2868642)(官网控制台部署)<br/>[GPU 云服务器部署 DeepSeek-R1 满血版](https://www.aliyun.com/solution/tech-solution/deepseek-r1-for-platforms/2869698)(官网控制台部署)<br/>[阿里云百炼调用 DeepSeek 模型 🆓](https://www.aliyun.com/solution/tech-solution/deepseek-r1-for-platforms/2868889)(官网控制台部署)<br/>[通过计算巢部署DeepSeek-R1-Distill-Qwen-7B](https://www.aliyun.com/solution/tech-solution/deepseek-r1-for-platforms/2949744)(官网控制台部署) | ROS 模板 IaC 部署、官网控制台部署 | |
| 阿里云百炼专属版 AI Stack 一体机 | [查看](https://www.aliyun.com/solution/tech-solution/bailian-aistack) | (暂无) | — | |
| 快速上手 DeepSeek-V3.2 | [查看](https://www.aliyun.com/solution/tech-solution/efficient-deployment-of-the-deepseek-v3-latest-model/2878261) | [在 GPU 云服务器中部署 DeepSeek-V3.2-Exp 模型](https://www.aliyun.com/solution/tech-solution/efficient-deployment-of-the-deepseek-v3-latest-model/2878261)(官网控制台部署)<br/>[基于人工智能平台 PAI 部署 DeepSeek-V3.2](https://www.aliyun.com/solution/tech-solution/efficient-deployment-of-the-deepseek-v3-latest-model/2978341)(官网控制台部署)<br/>[通过计算巢部署DeepSeek-V3.2到ECS](https://www.aliyun.com/solution/tech-solution/efficient-deployment-of-the-deepseek-v3-latest-model/2978415)(官网控制台部署)<br/>[通过计算巢部署DeepSeek-V3.1到ACS](https://www.aliyun.com/solution/tech-solution/efficient-deployment-of-the-deepseek-v3-latest-model/2978500)(官网控制台部署)<br/>[基于阿里云百炼调用 DeepSeek-V3.2 🆓](https://www.aliyun.com/solution/tech-solution/efficient-deployment-of-the-deepseek-v3-latest-model/2978543)(官网控制台部署) | 官网控制台部署 | |
| 部署Qwen2.5-Omni,畅享多模态交互 | [查看](https://www.aliyun.com/solution/tech-solution/deploy-the-qwen2-5-omni-7b-model-rapidly/2880242) | [通过阿里云百炼快速体验 Qwen2.5-Omni 模型](https://www.aliyun.com/solution/tech-solution/deploy-the-qwen2-5-omni-7b-model-rapidly/2880242)(官网控制台部署、ROS 模板 IaC 部署)<br/>[通过人工智能平台 PAI 部署 Qwen2.5-Omni 模型](https://www.aliyun.com/solution/tech-solution/deploy-the-qwen2-5-omni-7b-model-rapidly/2880348)(官网控制台部署)<br/>[通过 GPU 云服务器部署 Qwen2.5-Omni 模型](https://www.aliyun.com/solution/tech-solution/deploy-the-qwen2-5-omni-7b-model-rapidly/2880349)(官网控制台部署) | ROS 模板 IaC 部署、官网控制台部署 | |
| Kimi K2,开源万亿参数大模型 | [查看](https://www.aliyun.com/solution/tech-solution/kimi-k2-instruct/2948505) | [基于阿里云百炼调用 Kimi K2.5 🆓](https://www.aliyun.com/solution/tech-solution/kimi-k2-instruct/2948505)(官网控制台部署)<br/>[基于 PAI Model Gallery 部署 Kimi K2](https://www.aliyun.com/solution/tech-solution/kimi-k2-instruct/2948504)(官网控制台部署)<br/>[基于计算巢部署 Kimi K2](https://www.aliyun.com/solution/tech-solution/kimi-k2-instruct/2948506)(官网控制台部署) | 官网控制台部署 | |
| OpenAI 重磅开源,快速部署GPT-OSS模型 | [查看](https://www.aliyun.com/solution/tech-solution/gpt-oss/2974153) | [零代码部署OpenAI开源模型 GPT-OSS 🆓](https://www.aliyun.com/solution/tech-solution/gpt-oss/2974153)(官网控制台部署)<br/>[基于计算巢部署 GPT-OSS](https://www.aliyun.com/solution/tech-solution/gpt-oss/2974094)(官网控制台部署) | 官网控制台部署 | |
| 模型蒸馏:让0.6B模型媲美235B模型 | [查看](https://www.aliyun.com/solution/tech-solution/qwen3-distill/2925027) | [基于 GPU 云服务器微调 Qwen3 模型 🆓](https://www.aliyun.com/solution/tech-solution/qwen3-distill/2925027)(官网控制台部署)<br/>[基于 PAI-DSW 微调 Qwen3 模型 🆓](https://www.aliyun.com/solution/tech-solution/qwen3-distill/2925028)(官网控制台部署)<br/>[基于 PAI 的 Model Gallery 微调 Qwen3 模型 🆓](https://www.aliyun.com/solution/tech-solution/qwen3-distill/2925534)(官网控制台部署) | 官网控制台部署 | |
| 零代码微调,打造领域专属大模型 | [查看](https://www.aliyun.com/solution/tech-solution/fine-tuning/2978350) | [通过微调打造“虚拟角色”](https://www.aliyun.com/solution/tech-solution/fine-tuning/2978350)(官网控制台部署)<br/>[通过Qwen-VL微调提升特定目标检测能力](https://www.aliyun.com/solution/tech-solution/fine-tuning/2978352)(官网控制台部署) | 官网控制台部署 | |
| 即享 QwQ-32B,性能比肩最强开源 | [查看](https://www.aliyun.com/solution/tech-solution/qwq-for-platforms/2873019) | [人工智能平台 PAI 部署 QwQ-32B 模型](https://www.aliyun.com/solution/tech-solution/qwq-for-platforms/2873019)(官网控制台部署)<br/>[函数计算 FC 部署 QwQ-32B 模型 🆓](https://www.aliyun.com/solution/tech-solution/qwq-for-platforms/2873031)(官网控制台部署)<br/>[GPU 云服务器部署 QwQ-32B](https://www.aliyun.com/solution/tech-solution/qwq-for-platforms/2872983)(官网控制台部署)<br/>[阿里云百炼调用 QwQ-32B 模型](https://www.aliyun.com/solution/tech-solution/qwq-for-platforms/2872978)(官网控制台部署) | 官网控制台部署 | |
| 轻松部署,即刻触达 Qwen2.5 | [查看](https://www.aliyun.com/solution/tech-solution/qwen2-5-for-platforms/2860074) | [人工智能平台 PAI 部署 Qwen2.5 模型](https://www.aliyun.com/solution/tech-solution/qwen2-5-for-platforms/2860074)(官网控制台部署)<br/>[GPU 云服务器部署 Qwen2.5 模型](https://www.aliyun.com/solution/tech-solution/qwen2-5-for-platforms/2860075)(官网控制台部署)<br/>[函数计算 FC 部署 Qwen2.5 模型](https://www.aliyun.com/solution/tech-solution/qwen2-5-for-platforms/2859264)(官网控制台部署) | 官网控制台部署 | |
## 互联网应用开发(44 个解决方案)
### 应用架构
| 解决方案名称 | 链接 | 部署教程 | 部署方式 | Terraform Module 名称 |
| --- | --- | --- | --- | --- |
| 自动弹性,稳定交付 | [查看](https://www.aliyun.com/solution/tech-solution/improve-app-availability/2766666) | [随需而动:自动弹性,稳定交付](https://www.aliyun.com/solution/tech-solution/improve-app-availability/2766666)(官网控制台部署、ROS 模板 IaC 部署) | ROS 模板 IaC 部署、官网控制台部署 | `improve-app-availability` |
| Serverless 事件驱动架构实践 | [查看](https://www.aliyun.com/solution/tech-solution/fc-drive-file/2807391) | [告别资源瓶颈,函数计算驱动多媒体文件处理](https://www.aliyun.com/solution/tech-solution/fc-drive-file/2807391)(官网控制台部署、ROS 模板 IaC 部署) | ROS 模板 IaC 部署、官网控制台部署 | |
| 极简运维,Serverless 高可用架构 | [查看](https://www.aliyun.com/solution/tech-solution/serverless-ha/2804331) | [卓越效能,极简运维,Serverless高可用架构](https://www.aliyun.com/solution/tech-solution/serverless-ha/2804331)(官网控制台部署、ROS 模板 IaC 部署) | ROS 模板 IaC 部署、官网控制台部署 | `serverless-high-availability` |
| 云上高可用架构 | [查看](https://www.aliyun.com/solution/tech-solution/hablog/2785364) | [云上高可用架构 🆓](https://www.aliyun.com/solution/tech-solution/hablog/2785364)(官网控制台部署、Terraform 模板 IaC 部署) | Terraform 模板 IaC 部署、官网控制台部署 | |
| 快速集成分布式任务调度 | [查看](https://www.aliyun.com/solution/tech-solution/mse-schedulerx/2833797) | [灵活配置,高效执行,快速集成分布式任务调度](https://www.aliyun.com/solution/tech-solution/mse-schedulerx/2833797)(官网控制台部署、Terraform 模板 IaC 部署) | Terraform 模板 IaC 部署、官网控制台部署 | `mse-schedulerx` |
| 服务迁移时保持公网 IP 不变 | [查看](https://www.aliyun.com/solution/tech-solution/eip-service/2644995) | [服务迁移时保持公网 IP 不变](https://www.aliyun.com/solution/tech-solution/eip-service/2644995)(官网控制台部署) | 官网控制台部署 | |
| ALB 实现跨地域负载均衡 | [查看](https://www.aliyun.com/solution/tech-solution/alb-acrlb/2503501) | [ALB实现跨地域负载均衡](https://www.aliyun.com/solution/tech-solution/alb-acrlb/2503501)(官网控制台部署) | 官网控制台部署 | `alb-cross-region-load-balancing` |
| 高可用及共享存储 Web 服务 | [查看](https://www.aliyun.com/solution/tech-solution/ha-web/2400018) | [高可用及共享存储Web服务](https://www.aliyun.com/solution/tech-solution/ha-web/2400018)(官网控制台部署、Terraform 模板 IaC 部署) | Terraform 模板 IaC 部署、官网控制台部署 | `high-availability-web-shared-storage` |
| 云消息队列 RabbitMQ 实践 | [查看](https://www.aliyun.com/solution/tech-solution/rabbitmq-serverless/2835649) | [高弹性,低成本,云消息队列 RabbitMQ实践](https://www.aliyun.com/solution/tech-solution/rabbitmq-serverless/2835649)(官网控制台部署、Terraform 模板 IaC 部署) | Terraform 模板 IaC 部署、官网控制台部署 | `rabbitmq-serverless` |
| MSE 实现全链路灰度 | [查看](https://www.aliyun.com/solution/tech-solution/iflgbomse/2510285) | [MSE实现全链路灰度](https://www.aliyun.com/solution/tech-solution/iflgbomse/2510285)(官网控制台部署) | 官网控制台部署 | |
| 通过 RocketMQ 实现分布式事务 | [查看](https://www.aliyun.com/solution/tech-solution/rocketmq-data-consistency/2835990) | [通过RocketMQ事务消息实现分布式事务](https://www.aliyun.com/solution/tech-solution/rocketmq-data-consistency/2835990)(官网控制台部署、ROS 模板 IaC 部署) | ROS 模板 IaC 部署、官网控制台部署 | `rocketmq-data-consistency` |
| 构建高性能秒杀系统 | [查看](https://www.aliyun.com/solution/tech-solution/build-a-high-performance-flash-sales-system/2861065) | [构建高性能秒杀系统](https://www.aliyun.com/solution/tech-solution/build-a-high-performance-flash-sales-system/2861065)(官网控制台部署、ROS 模板 IaC 部署) | ROS 模板 IaC 部署、官网控制台部署 | |
| 高效实现前后端分离架构升级 | [查看](https://www.aliyun.com/solution/tech-solution/the-headless-architecture-solution-of-alibaba-cloud/2867383) | [前后端分离架构升级(ECS版) 🆓](https://www.aliyun.com/solution/tech-solution/the-headless-architecture-solution-of-alibaba-cloud/2867383)(官网控制台部署、Terraform 模板 IaC 部署)<br/>[前后端分离架构升级(SAE版) 🆓](https://www.aliyun.com/solution/tech-solution/the-headless-architecture-solution-of-alibaba-cloud/2866912)(官网控制台部署、Terraform 模板 IaC 部署) | Terraform 模板 IaC 部署、官网控制台部署 | `ecs-headless-architecture`<br/>`sae-headless-architecture` |
| MSE 助力实现全方位流量防护 | [查看](https://www.aliyun.com/solution/tech-solution/use-mse-to-implement-comprehensive-traffic-protection/2869233) | [MSE 助力实现全方位流量防护](https://www.aliyun.com/solution/tech-solution/use-mse-to-implement-comprehensive-traffic-protection/2869233)(官网控制台部署、ROS 模板 IaC 部署) | ROS 模板 IaC 部署、官网控制台部署 | `mse-traffic-protection` |
| Tair 实现即时通信场景中的消息多端同步 | [查看](https://www.aliyun.com/solution/tech-solution/tair-im/2932553) | [Tair 实现即时通信场景中的消息多端同步](https://www.aliyun.com/solution/tech-solution/tair-im/2932553)(官网控制台部署) | 官网控制台部署 | |
| 基于数据闪回,快速恢复数据 | [查看](https://www.aliyun.com/solution/tech-solution/tair-flashback/2929053) | [基于数据闪回,快速恢复数据](https://www.aliyun.com/solution/tech-solution/tair-flashback/2929053)(官网控制台部署) | 官网控制台部署 | |
| 容器化应用的弹性伸缩攻略 | [查看](https://www.aliyun.com/solution/tech-solution/ack-hpa/2796618) | [容器化应用的弹性伸缩攻略](https://www.aliyun.com/solution/tech-solution/ack-hpa/2796618)(官网控制台部署、Terraform 模板 IaC 部署) | Terraform 模板 IaC 部署、官网控制台部署 | |
| 部署 Nginx 并通过 Ingress 暴露服务 | [查看](https://www.aliyun.com/solution/tech-solution/nginx-ingress/2400022) | [部署 Nginx 并通过 Ingress 暴露服务](https://www.aliyun.com/solution/tech-solution/nginx-ingress/2400022)(官网控制台部署、Terraform 模板 IaC 部署) | Terraform 模板 IaC 部署、官网控制台部署 | `nginx-ingress-deployment` |
| 容器化应用的持续集成与部署 | [查看](https://www.aliyun.com/solution/tech-solution/ack-cicd/2868455) | [容器化应用的持续集成与部署](https://www.aliyun.com/solution/tech-solution/ack-cicd/2868455)(官网控制台部署) | 官网控制台部署 | |
| 基于 Supabase 高效构建轻量级应用 | [查看](https://www.aliyun.com/solution/tech-solution/rds-supabase/2949834) | [基于 Supabase 高效构建轻量级应用](https://www.aliyun.com/solution/tech-solution/rds-supabase/2949834)(官网控制台部署) | 官网控制台部署 | |
| 通过 MSE Ingress实现容器应用的流量管理 | [查看](https://www.aliyun.com/solution/tech-solution/mse-ingress/2949883) | [通过 MSE Ingress实现容器应用的流量管理](https://www.aliyun.com/solution/tech-solution/mse-ingress/2949883)(官网控制台部署) | 官网控制台部署 | |
### 搜索与推荐
| 解决方案名称 | 链接 | 部署教程 | 部署方式 | Terraform Module 名称 |
| --- | --- | --- | --- | --- |
| 精准分析检索,打造商品推荐体验 | [查看](https://www.aliyun.com/solution/tech-solution/elasticsearch-server) | (暂无) | — | |
| PolarDB 列存索引加速复杂查询 | [查看](https://www.aliyun.com/solution/tech-solution/accelerating-complex-e-commerce-queries-with-the-imci-feature-of-polardb-for-mysql) | (暂无) | — | |
| 极速构建实时全文检索系统 | [查看](https://www.aliyun.com/solution/tech-solution/rapid-construction-of-a-real-time-full-text-search-system) | (暂无) | — | |
### 短视频与直播
| 解决方案名称 | 链接 | 部署教程 | 部署方式 | Terraform Module 名称 |
| --- | --- | --- | --- | --- |
| 高效存储和处理多媒体数据 | [查看](https://www.aliyun.com/solution/tech-solution/efficient-storage-and-processing-of-multimedia-data/2507865) | [高效存储和处理多媒体数据](https://www.aliyun.com/solution/tech-solution/efficient-storage-and-processing-of-multimedia-data/2507865)(官网控制台部署、ROS 模板 IaC 部署) | ROS 模板 IaC 部署、官网控制台部署 | |
| 视频网站的存储与媒体处理方案 | [查看](https://www.aliyun.com/solution/tech-solution/vsaps/2362801) | [视频网站的存储与媒体处理方案](https://www.aliyun.com/solution/tech-solution/vsaps/2362801)(官网控制台部署、ROS 模板 IaC 部署) | ROS 模板 IaC 部署、官网控制台部署 | |
| 构建视频直播系统 | [查看](https://www.aliyun.com/solution/tech-solution/building-a-live-video-streaming-system/2861675) | [构建视频直播系统](https://www.aliyun.com/solution/tech-solution/building-a-live-video-streaming-system/2861675)(官网控制台部署) | 官网控制台部署 | |
| 一站式搭建短剧平台 | [查看](https://www.aliyun.com/solution/tech-solution/build-a-vod-short-play-platform/2878387) | [一站式搭建短剧平台](https://www.aliyun.com/solution/tech-solution/build-a-vod-short-play-platform/2878387)(官网控制台部署) | 官网控制台部署 | |
| 超低延时直播:400-600ms延迟,追求极致实时性 | [查看](https://www.aliyun.com/solution/tech-solution/ultra-low-latency-live-broadcast/2979340) | [超低延时直播:400-600ms延迟,追求极致实时性](https://www.aliyun.com/solution/tech-solution/ultra-low-latency-live-broadcast/2979340)(官网控制台部署) | 官网控制台部署 | |
### 网站性能优化
| 解决方案名称 | 链接 | 部署教程 | 部署方式 | Terraform Module 名称 |
| --- | --- | --- | --- | --- |
| 网站静态资源访问加速 | [查看](https://www.aliyun.com/solution/tech-solution/oss-x-cdn) | (暂无) | — | |
| 文件下载加速及成本优化 | [查看](https://www.aliyun.com/solution/tech-solution/fdaaco) | (暂无) | — | |
| 利用 Redis 缓存实现极速响应 | [查看](https://www.aliyun.com/solution/tech-solution/redis-cache-speedup) | (暂无) | — | |
| RDS 到 Redis 实时同步方案 | [查看](https://www.aliyun.com/solution/tech-solution/rtsorarctebcc) | (暂无) | — | |
| 通过 ESA 加速和保护互联网流量 | [查看](https://www.aliyun.com/solution/tech-solution/esa-helps-e-commerce-sites-improve-access-experience) | (暂无) | — | |
| 通过 RDS 读写分离提升数据库性能 | [查看](https://www.aliyun.com/solution/tech-solution/read-write-splitting-through-rds-proxy) | (暂无) | — | `rds-read-write-splitting` |
| Redis 通过 Proxy 组件实现读写分离 | [查看](https://www.aliyun.com/solution/tech-solution/read-write-splitting-through-tair-proxy) | (暂无) | — | `redis-read-write-splitting-tair-proxy` |
| 网站静态资源加速与安全优化 | [查看](https://www.aliyun.com/solution/tech-solution/website-static-resource-acceleration-and-security-optimization) | (暂无) | — | |
### 网站搭建
| 解决方案名称 | 链接 | 部署教程 | 部署方式 | Terraform Module 名称 |
| --- | --- | --- | --- | --- |
| 低代码高效构建企业门户网站 | [查看](https://www.aliyun.com/solution/tech-solution/build-a-website/2715404) | [低代码高效构建企业门户网站](https://www.aliyun.com/solution/tech-solution/build-a-website/2715404)(官网控制台部署、Terraform 模板 IaC 部署) | Terraform 模板 IaC 部署、官网控制台部署 | `build-enterprise-portal-website` |
| 高效构建移动 App | [查看](https://www.aliyun.com/solution/tech-solution/develop-apps/2693289) | [移动开发秘籍:云上高效构建App](https://www.aliyun.com/solution/tech-solution/develop-apps/2693289)(官网控制台部署、ROS 模板 IaC 部署) | ROS 模板 IaC 部署、官网控制台部署 | `develop-apps` |
| 一键部署幻兽帕鲁游戏服务器 | [查看](https://www.aliyun.com/solution/tech-solution/palworld) | (暂无) | — | |
| 搭建微信、支付宝小程序 | [查看](https://www.aliyun.com/solution/tech-solution/develop-your-wechat-mini-program-in-10-minutes/2856534) | [搭建微信小程序](https://www.aliyun.com/solution/tech-solution/develop-your-wechat-mini-program-in-10-minutes/2856534)(官网控制台部署、Terraform 模板 IaC 部署)<br/>[搭建支付宝小程序](https://www.aliyun.com/solution/tech-solution/develop-your-wechat-mini-program-in-10-minutes/2869587)(官网控制台部署、Terraform 模板 IaC 部署) | Terraform 模板 IaC 部署、官网控制台部署 | `wechat-mini-program-infrastructure` |
| 极速构建持续集成与部署流程 | [查看](https://www.aliyun.com/solution/tech-solution/swiftly-building-an-effective-ci-cd-pipeline/2861142) | [极速构建后端持续集成与部署流程](https://www.aliyun.com/solution/tech-solution/swiftly-building-an-effective-ci-cd-pipeline/2861142)(官网控制台部署)<br/>[极速构建前端持续集成与部署流程](https://www.aliyun.com/solution/tech-solution/swiftly-building-an-effective-ci-cd-pipeline/2868069)(官网控制台部署) | 官网控制台部署 | |
| 函数和Pages+MCP:一键实现全球部署 | [查看](https://www.aliyun.com/solution/tech-solution/edge-function-mcp-one-click-global-deployment/2927469) | [边缘函数+MCP:一键实现全球部署](https://www.aliyun.com/solution/tech-solution/edge-function-mcp-one-click-global-deployment/2927469)(官网控制台部署) | 官网控制台部署 | |
| 高效编排与管理容器化应用 | [查看](https://www.aliyun.com/solution/tech-solution/ack-services/2808202) | [高效编排与管理容器化应用](https://www.aliyun.com/solution/tech-solution/ack-services/2808202)(官网控制台部署、Terraform 模板 IaC 部署) | Terraform 模板 IaC 部署、官网控制台部署 | `ack-services` |
## 大数据(31 个解决方案)
### 数据分析与智能应用
| 解决方案名称 | 链接 | 部署教程 | 部署方式 | Terraform Module 名称 |
| --- | --- | --- | --- | --- |
| 快捷搭建企业经营数据大屏 | [查看](https://www.aliyun.com/solution/tech-solution/datav-for-digitalization/2839075) | [快捷搭建企业经营数据大屏](https://www.aliyun.com/solution/tech-solution/datav-for-digitalization/2839075)(官网控制台部署、Terraform 模板 IaC 部署) | Terraform 模板 IaC 部署、官网控制台部署 | `datav-for-digitalization` |
| AI 时代的分布式多模态数据处理实践 | [查看](https://www.aliyun.com/solution/tech-solution/maxframe-for-multimodal-data-processing/2872006) | [AI 时代的分布式多模态数据处理实践](https://www.aliyun.com/solution/tech-solution/maxframe-for-multimodal-data-processing/2872006)(官网控制台部署) | 官网控制台部署 | |
| 快速构建企业级数据分析 Agent | [查看](https://www.aliyun.com/solution/tech-solution/hologres-mcp/2922180) | [快速构建企业级数据分析 Agent](https://www.aliyun.com/solution/tech-solution/hologres-mcp/2922180)(官网控制台部署) | 官网控制台部署 | |
| 一站式时空决策,释放空间数据价值 | [查看](https://www.aliyun.com/solution/tech-solution/datav-for-atlas/2922076) | [一站式时空决策,释放空间数据价值](https://www.aliyun.com/solution/tech-solution/datav-for-atlas/2922076)(官网控制台部署) | 官网控制台部署 | `datav-atlas-solution` |
| 原生 SQL 轻松实现多模态智能检索 | [查看](https://www.aliyun.com/solution/tech-solution/polardb-ai-search/2922763) | [原生 SQL 轻松实现多模态智能检索 🆓](https://www.aliyun.com/solution/tech-solution/polardb-ai-search/2922763)(官网控制台部署、Terraform 模板 IaC 部署) | Terraform 模板 IaC 部署、官网控制台部署 | `polardb-ai-search` |
| MCP 赋能可视化 OLAP 智能体应用 | [查看](https://www.aliyun.com/solution/tech-solution/polardb-mysql-mcp/2925827) | [MCP 赋能可视化 OLAP 智能体应用 🆓](https://www.aliyun.com/solution/tech-solution/polardb-mysql-mcp/2925827)(官网控制台部署、Terraform 模板 IaC 部署) | Terraform 模板 IaC 部署、官网控制台部署 | `polardb-mysql-mcp` |
| Elasticsearch 智能运维 AI 助手 | [查看](https://www.aliyun.com/solution/tech-solution/elasticsearch-ai-assistant/2926655) | [Elasticsearch 智能运维 AI 助手 🆓](https://www.aliyun.com/solution/tech-solution/elasticsearch-ai-assistant/2926655)(官网控制台部署、Terraform 模板 IaC 部署) | Terraform 模板 IaC 部署、官网控制台部署 | `elasticsearch-ai-assistant` |
| 阿里云 Milvus 轻松实现文搜图&图搜图 | [查看](https://www.aliyun.com/solution/tech-solution/milvus-ai/2926880) | [阿里云 Milvus 轻松实现文搜图&图搜图](https://www.aliyun.com/solution/tech-solution/milvus-ai/2926880)(官网控制台部署) | 官网控制台部署 | |
| 轻松打造一站式图像智能检索引擎 | [查看](https://www.aliyun.com/solution/tech-solution/gallery-ai/2928756) | [轻松打造一站式图像智能检索引擎](https://www.aliyun.com/solution/tech-solution/gallery-ai/2928756)(官网控制台部署) | 官网控制台部署 | |
| 分析 Agent 实现一键 AI 数据洞察 | [查看](https://www.aliyun.com/solution/tech-solution/quick-bi/2929617) | [分析 Agent 实现一键 AI 数据洞察](https://www.aliyun.com/solution/tech-solution/quick-bi/2929617)(官网控制台部署) | 官网控制台部署 | |
| MCP 助力打造数据库管理分析 AI 助手 | [查看](https://www.aliyun.com/solution/tech-solution/dms-mcp-ai/2936891) | [MCP 助力打造数据库管理分析 AI 助手](https://www.aliyun.com/solution/tech-solution/dms-mcp-ai/2936891)(官网控制台部署) | 官网控制台部署 | |
| 轻松实现客服数据智能分析与高效存储 | [查看](https://www.aliyun.com/solution/tech-solution/dify-on-dms/2948739) | [轻松实现客服数据智能分析与高效存储](https://www.aliyun.com/solution/tech-solution/dify-on-dms/2948739)(官网控制台部署) | 官网控制台部署 | |
| 构建复杂关系网络的智能洞察分析 | [查看](https://www.aliyun.com/solution/tech-solution/polardb-age/2978227) | [构建复杂关系网络的智能洞察分析 🆓](https://www.aliyun.com/solution/tech-solution/polardb-age/2978227)(官网控制台部署) | 官网控制台部署 | |
| ES Serverless 构建多模态图像检索 | [查看](https://www.aliyun.com/solution/tech-solution/elasticsearch-serverless-ai/2979696) | [ES Serverless 构建多模态图像检索 🆓](https://www.aliyun.com/solution/tech-solution/elasticsearch-serverless-ai/2979696)(官网控制台部署) | 官网控制台部署 | |
| DMS Data Agent 开启智能分析之旅 | [查看](https://www.aliyun.com/solution/tech-solution/data-agent-for-analytics/2980278) | [DMS Data Agent 开启智能分析之旅](https://www.aliyun.com/solution/tech-solution/data-agent-for-analytics/2980278)(官网控制台部署) | 官网控制台部署 | |
| Agent 赋能,一键生成智能分析报告 | [查看](https://www.aliyun.com/solution/tech-solution/quick-bi-report/2978809) | [Agent 赋能,一键生成智能分析报告](https://www.aliyun.com/solution/tech-solution/quick-bi-report/2978809)(官网控制台部署) | 官网控制台部署 | |
| 多源数据下的企业 AI 助手实践 | [查看](https://www.aliyun.com/solution/tech-solution/dts-ragflow/2990095) | [多源数据下的企业 AI 助手实践](https://www.aliyun.com/solution/tech-solution/dts-ragflow/2990095)(官网控制台部署) | 官网控制台部署 | |
| Agent 赋能企业数据治理 | [查看](https://www.aliyun.com/solution/tech-solution/agent-for-dataphin/2990061) | [Agent 赋能企业数据治理](https://www.aliyun.com/solution/tech-solution/agent-for-dataphin/2990061)(官网控制台部署) | 官网控制台部署 | |
### 数据处理与计算引擎
| 解决方案名称 | 链接 | 部署教程 | 部署方式 | Terraform Module 名称 |
| --- | --- | --- | --- | --- |
| 泛时序数据一站式分析与洞察 | [查看](https://www.aliyun.com/solution/tech-solution/lindorm-data-process/2817939) | [从海量到价值,泛时序数据一站式分析与洞察](https://www.aliyun.com/solution/tech-solution/lindorm-data-process/2817939)(官网控制台部署、Terraform 模板 IaC 部署) | Terraform 模板 IaC 部署、官网控制台部署 | `lindorm-data-process` |
| 极致性能,搭建轻量 OLAP 分析平台 | [查看](https://www.aliyun.com/solution/tech-solution/hologres-olap/2835288) | [极致性能,搭建轻量 OLAP 分析平台](https://www.aliyun.com/solution/tech-solution/hologres-olap/2835288)(官网控制台部署、Terraform 模板 IaC 部署) | Terraform 模板 IaC 部署、官网控制台部署 | `hologres-olap` |
| RDS 与 ClickHouse 构建一站式 HTAP | [查看](https://www.aliyun.com/solution/tech-solution/rdsclickhouse-htap/2369710) | [RDS 与 ClickHouse 构建一站式 HTAP](https://www.aliyun.com/solution/tech-solution/rdsclickhouse-htap/2369710)(官网控制台部署、Terraform 模板 IaC 部署) | Terraform 模板 IaC 部署、官网控制台部署 | `rds-clickhouse-htap` |
| Flink CDC 实现企业级实时数据同步 | [查看](https://www.aliyun.com/solution/tech-solution/flink-cdc-realize-data-synchronization/2860742) | [Flink CDC 实现企业级实时数据同步 🆓](https://www.aliyun.com/solution/tech-solution/flink-cdc-realize-data-synchronization/2860742)(官网控制台部署) | 官网控制台部署 | |
| SelectDB实现日志高效存储与实时分析 | [查看](https://www.aliyun.com/solution/tech-solution/real-time-log-analysis-with-selectdb/2869895) | [SelectDB 实现日志高效存储与实时分析 🆓](https://www.aliyun.com/solution/tech-solution/real-time-log-analysis-with-selectdb/2869895)(官网控制台部署、Terraform 模板 IaC 部署) | Terraform 模板 IaC 部署、官网控制台部署 | `real-time-log-analysis-selectdb` |
| 海量异构数据预处理破局之道 | [查看](https://www.aliyun.com/solution/tech-solution/process-big-data-with-maxcompute/2979396) | [海量异构数据预处理破局之道](https://www.aliyun.com/solution/tech-solution/process-big-data-with-maxcompute/2979396)(官网控制台部署) | 官网控制台部署 | |
### 数据存储与湖仓构建
| 解决方案名称 | 链接 | 部署教程 | 部署方式 | Terraform Module 名称 |
| --- | --- | --- | --- | --- |
| Flink 与 Hologres 搭建实时数仓 | [查看](https://www.aliyun.com/solution/tech-solution/flink-hologres) | (暂无) | — | |
| 云原生企业级数据湖 | [查看](https://www.aliyun.com/solution/tech-solution/datalake) | (暂无) | — | |
| OpenLake 与 AI 一体化解决方案 | [查看](https://www.aliyun.com/solution/tech-solution/openlake-ai-solution) | (暂无) | — | |
| 实现 MySQL 到 ADB 秒级分析性能 | [查看](https://www.aliyun.com/solution/tech-solution/analyticdb-analysis-service) | (暂无) | — | |
| 构建实时/离线一体化数据分析平台 | [查看](https://www.aliyun.com/solution/tech-solution/analyticdb-real-time-data-synchronization) | (暂无) | — | |
| 低成本、高性能的湖仓一体化架构 | [查看](https://www.aliyun.com/solution/tech-solution/selectdb-lakehouse) | (暂无) | — | |
| 流批一体 LakeHouse 架构实践 | [查看](https://www.aliyun.com/solution/tech-solution/streaming-lakehouse) | (暂无) | — | |
## 安全(17 个解决方案)
### 办公安全
| 解决方案名称 | 链接 | 部署教程 | 部署方式 | Terraform Module 名称 |
| --- | --- | --- | --- | --- |
| 快速实现办公环境安全访问云资源 | [查看](https://www.aliyun.com/solution/tech-solution/quickly-realize-secure-access-to-cloud-resources-in-office-environment/2975895) | [快速实现办公环境下安全访问云资源](https://www.aliyun.com/solution/tech-solution/quickly-realize-secure-access-to-cloud-resources-in-office-environment/2975895)(官网控制台部署) | 官网控制台部署 | |
### 合规与审计
| 解决方案名称 | 链接 | 部署教程 | 部署方式 | Terraform Module 名称 |
| --- | --- | --- | --- | --- |
| 全面安全保障:等保 2.0 解决方案 | [查看](https://www.aliyun.com/solution/tech-solution/mlps-compliance-solution) | (暂无) | — | |
| 高效构建安全合规的企业新账号 | [查看](https://www.aliyun.com/solution/tech-solution/ecosacna) | (暂无) | — | |
| 企业多账号配置统一合规审计 | [查看](https://www.aliyun.com/solution/tech-solution/ucafmac) | (暂无) | — | |
| 日志安全审计与合规性评估 | [查看](https://www.aliyun.com/solution/tech-solution/log-security-audit) | (暂无) | — | |
### 应用安全
| 解决方案名称 | 链接 | 部署教程 | 部署方式 | Terraform Module 名称 |
| --- | --- | --- | --- | --- |
| 高效防护 Web 应用 | [查看](https://www.aliyun.com/solution/tech-solution/web-protection/2714251) | [高效防护 Web 应用 🆓](https://www.aliyun.com/solution/tech-solution/web-protection/2714251)(官网控制台部署) | 官网控制台部署 | |
| 构建大模型应用的安全防护体系 | [查看](https://www.aliyun.com/solution/tech-solution/build-large-model-application-security-system/2880886) | [构建大模型应用的全方位安全防护体系](https://www.aliyun.com/solution/tech-solution/build-large-model-application-security-system/2880886)(官网控制台部署、Terraform 模板 IaC 部署) | Terraform 模板 IaC 部署、官网控制台部署 | `large-language-model-security-system` |
### 数据安全
| 解决方案名称 | 链接 | 部署教程 | 部署方式 | Terraform Module 名称 |
| --- | --- | --- | --- | --- |
| 网站文本内容安全检测 | [查看](https://www.aliyun.com/solution/tech-solution/lvwang) | (暂无) | — | |
| 部署SSL证书,实现Web服务加密访问 | [查看](https://www.aliyun.com/solution/tech-solution/ssl) | (暂无) | — | |
| ECS 数据备份与保护 | [查看](https://www.aliyun.com/solution/tech-solution/data-backup) | (暂无) | — | |
| 无代理 ECS 备份与高效环境搭建 | [查看](https://www.aliyun.com/solution/tech-solution/ecs-backup) | (暂无) | — | |
| 企业级云灾备与数据管理 | [查看](https://www.aliyun.com/solution/tech-solution/elcdradm) | (暂无) | — | |
| 数据护航:数据库敏感数据防护 | [查看](https://www.aliyun.com/solution/tech-solution/database-sensitive-data-protection) | (暂无) | — | |
| 数据守护:防勒索攻击数据保障 | [查看](https://www.aliyun.com/solution/tech-solution/use-the-anti-ransomware-feature-of-security-center-to-protect-your-data) | (暂无) | — | |
### 账号管理
| 解决方案名称 | 链接 | 部署教程 | 部署方式 | Terraform Module 名称 |
| --- | --- | --- | --- | --- |
| 企业多账号身份权限集中管理 | [查看](https://www.aliyun.com/solution/tech-solution/cmomaip/2506076) | [企业多账号身份权限集中管理](https://www.aliyun.com/solution/tech-solution/cmomaip/2506076)(官网控制台部署、Terraform 模板 IaC 部署) | Terraform 模板 IaC 部署、官网控制台部署 | |
| 云防火墙企业多账号统一管理 | [查看](https://www.aliyun.com/solution/tech-solution/umomaicf/2509670) | [云防火墙企业多账号统一管理](https://www.aliyun.com/solution/tech-solution/umomaicf/2509670)(官网控制台部署、Terraform 模板 IaC 部署) | Terraform 模板 IaC 部署、官网控制台部署 | |
| 限制企业仅使用已批准的云服务 | [查看](https://www.aliyun.com/solution/tech-solution/retouacs/2508616) | [限制企业仅使用已批准的云服务](https://www.aliyun.com/solution/tech-solution/retouacs/2508616)(官网控制台部署、Terraform 模板 IaC 部署) | Terraform 模板 IaC 部署、官网控制台部署 | |
## 网络(6 个解决方案)
### 云网络架构设计
| 解决方案名称 | 链接 | 部署教程 | 部署方式 | Terraform Module 名称 |
| --- | --- | --- | --- | --- |
| 企业云上网络架构规划 | [查看](https://www.aliyun.com/solution/tech-solution/ecnap/2412629) | [企业云上网络架构规划](https://www.aliyun.com/solution/tech-solution/ecnap/2412629)(官网控制台部署、Terraform 模板 IaC 部署) | Terraform 模板 IaC 部署、官网控制台部署 | |
| 实现跨地域跨账号网络互通 | [查看](https://www.aliyun.com/solution/tech-solution/cracani/2401623) | [跨地域跨账号网络互通方案](https://www.aliyun.com/solution/tech-solution/cracani/2401623)(官网控制台部署、Terraform 模板 IaC 部署) | Terraform 模板 IaC 部署、官网控制台部署 | |
### 网络优化
| 解决方案名称 | 链接 | 部署教程 | 部署方式 | Terraform Module 名称 |
| --- | --- | --- | --- | --- |
| 互联网应用全球加速 | [查看](https://www.aliyun.com/solution/tech-solution/gaoia) | (暂无) | — | |
### 网络安全
| 解决方案名称 | 链接 | 部署教程 | 部署方式 | Terraform Module 名称 |
| --- | --- | --- | --- | --- |
| 高效安全:企业统一公网出口 | [查看](https://www.aliyun.com/solution/tech-solution/nat-service/2808484) | [高效安全:企业统一公网出口](https://www.aliyun.com/solution/tech-solution/nat-service/2808484)(官网控制台部署、Terraform 模板 IaC 部署) | Terraform 模板 IaC 部署、官网控制台部署 | |
| 通过私网安全高效访问 AI 模型服务 | [查看](https://www.aliyun.com/solution/tech-solution/access-model-services-over-private-networks/2879581) | [通过私有网络安全高效访问百炼服务](https://www.aliyun.com/solution/tech-solution/access-model-services-over-private-networks/2879581)(官网控制台部署) | 官网控制台部署 | |
### 网络高可用
| 解决方案名称 | 链接 | 部署教程 | 部署方式 | Terraform Module 名称 |
| --- | --- | --- | --- | --- |
| 两地三中心异地多活网络 | [查看](https://www.aliyun.com/solution/tech-solution/tltcamanidl/2412632) | [两地三中心异地多活网络](https://www.aliyun.com/solution/tech-solution/tltcamanidl/2412632)(官网控制台部署、Terraform 模板 IaC 部署) | Terraform 模板 IaC 部署、官网控制台部署 | `multi-region-active-active-disaster-recovery` |
## 可观测(8 个解决方案)
### 云资源监控
| 解决方案名称 | 链接 | 部署教程 | 部署方式 | Terraform Module 名称 |
| --- | --- | --- | --- | --- |
| 通过 Prometheus 构建云产品实时监控 | [查看](https://www.aliyun.com/solution/tech-solution/comprehensive-real-time-monitoring-of-cloud-services-through-managed-service-for-prometheus/2873195) | [通过 Prometheus 构建云产品实时监控](https://www.aliyun.com/solution/tech-solution/comprehensive-real-time-monitoring-of-cloud-services-through-managed-service-for-prometheus/2873195)(官网控制台部署、Terraform 模板 IaC 部署) | Terraform 模板 IaC 部署、官网控制台部署 | `prometheus-cloud-monitoring` |
### 应用监控
| 解决方案名称 | 链接 | 部署教程 | 部署方式 | Terraform Module 名称 |
| --- | --- | --- | --- | --- |
| 构建面向应用日志的实时监控 | [查看](https://www.aliyun.com/solution/tech-solution/log-monitoring-alarming/2754416) | [实时可观测,即时应对风险 🆓](https://www.aliyun.com/solution/tech-solution/log-monitoring-alarming/2754416)(官网控制台部署、Terraform 模板 IaC 部署) | Terraform 模板 IaC 部署、官网控制台部署 | `log-monitoring-alarming` |
| 端到端全链路追踪诊断 | [查看](https://www.aliyun.com/solution/tech-solution/end-to-end-tracing-and-diagnostics/2861708) | [端到端全链路追踪诊断](https://www.aliyun.com/solution/tech-solution/end-to-end-tracing-and-diagnostics/2861708)(官网控制台部署、Terraform 模板 IaC 部署) | Terraform 模板 IaC 部署、官网控制台部署 | `end-to-end-tracing-diagnostics` |
| 低成本搭建 AI 应用全链路可观测体系 | [查看](https://www.aliyun.com/solution/tech-solution/build-an-obsearvability-system-for-ai-applications-at-low-costs/2882786) | [快速搭建百炼 AI 应用可观测体系](https://www.aliyun.com/solution/tech-solution/build-an-obsearvability-system-for-ai-applications-at-low-costs/2882786)(官网控制台部署、Terraform 模板 IaC 部署)<br/>[使用ARMS监控自建大模型应用实现可观测](https://www.aliyun.com/solution/tech-solution/build-an-obsearvability-system-for-ai-applications-at-low-costs/2922005)(官网控制台部署、Terraform 模板 IaC 部署) | Terraform 模板 IaC 部署、官网控制台部署 | `ai-observability-system` |
### 日志管理
| 解决方案名称 | 链接 | 部署教程 | 部署方式 | Terraform Module 名称 |
| --- | --- | --- | --- | --- |
| 应用日志数据归档 | [查看](https://www.aliyun.com/solution/tech-solution/oss-nginx) | (暂无) | — | `oss-nginx-log-archiving` |
| 跨阿里云账号采集日志 | [查看](https://www.aliyun.com/solution/tech-solution/cacac-logs) | (暂无) | — | |
| 开源ELK上云:构建低成本日志平台 | [查看](https://www.aliyun.com/solution/tech-solution/build-large-scale-low-cost-real-time-log-management-platform) | (暂无) | — | `log-management-platform` |
### 网络监控
| 解决方案名称 | 链接 | 部署教程 | 部署方式 | Terraform Module 名称 |
| --- | --- | --- | --- | --- |
| 高效构建全球网络服务性能观测体系 | [查看](https://www.aliyun.com/solution/tech-solution/monitoring-and-analysis-of-network-quality-through-dial-testing/2865415) | [通过拨测对网络质量进行监控与分析](https://www.aliyun.com/solution/tech-solution/monitoring-and-analysis-of-network-quality-through-dial-testing/2865415)(官网控制台部署) | 官网控制台部署 | |
## 上云与迁云(7 个解决方案)
### 上云
| 解决方案名称 | 链接 | 部署教程 | 部署方式 | Terraform Module 名称 |
| --- | --- | --- | --- | --- |
| 企业上云框架 Landing Zone | [查看](https://www.aliyun.com/solution/tech-solution/ecflz/2506085) | [企业上云框架 Landing Zone](https://www.aliyun.com/solution/tech-solution/ecflz/2506085)(官网控制台部署、Terraform 模板 IaC 部署) | Terraform 模板 IaC 部署、官网控制台部署 | |
### 数据迁移
| 解决方案名称 | 链接 | 部署教程 | 部署方式 | Terraform Module 名称 |
| --- | --- | --- | --- | --- |
| 自建 MongoDB 迁移到云数据库 | [查看](https://www.aliyun.com/solution/tech-solution/migrate-self-managed-mongodb-to-cloud/2925785) | [自建 MongoDB 迁移到云数据库 🆓](https://www.aliyun.com/solution/tech-solution/migrate-self-managed-mongodb-to-cloud/2925785)(官网控制台部署、Terraform 模板 IaC 部署) | Terraform 模板 IaC 部署、官网控制台部署 | `mongodb-migration` |
| 自建 MySQL 迁移至 PolarDB-X | [查看](https://www.aliyun.com/solution/tech-solution/mysql-migration-polardb-x/2974720) | [自建 MySQL 迁移至 PolarDB-X 🆓](https://www.aliyun.com/solution/tech-solution/mysql-migration-polardb-x/2974720)(官网控制台部署) | 官网控制台部署 | |
| 自建 Redis 迁移到云数据库 | [查看](https://www.aliyun.com/solution/tech-solution/migrate-self-managed-redis-to-cloud/2937841) | [自建 Redis 迁移到云数据库 🆓](https://www.aliyun.com/solution/tech-solution/migrate-self-managed-redis-to-cloud/2937841)(官网控制台部署) | 官网控制台部署 | |
| 自建数据库迁移到云数据库 | [查看](https://www.aliyun.com/solution/tech-solution/mysql-rds/2391660) | [自建数据库迁移到云数据库 🆓](https://www.aliyun.com/solution/tech-solution/mysql-rds/2391660)(官网控制台部署、Terraform 模板 IaC 部署) | Terraform 模板 IaC 部署、官网控制台部署 | `mysql-rds-wordpress` |
| RDS MySQL 迁移至 PolarDB MySQL 版 | [查看](https://www.aliyun.com/solution/tech-solution/rds-polardb/2367642) | [RDS MySQL 迁移至 PolarDB MySQL 版 🆓](https://www.aliyun.com/solution/tech-solution/rds-polardb/2367642)(官网控制台部署) | 官网控制台部署 | |
### 迁云
| 解决方案名称 | 链接 | 部署教程 | 部署方式 | Terraform Module 名称 |
| --- | --- | --- | --- | --- |
| CentOS 到 Alinux 操作系统迁移 | [查看](https://www.aliyun.com/solution/tech-solution/centos-alinux/2510051) | [CentOS到Alinux操作系统迁移](https://www.aliyun.com/solution/tech-solution/centos-alinux/2510051)(官网控制台部署、Terraform 模板 IaC 部署) | Terraform 模板 IaC 部署、官网控制台部署 | `centos-alinux-migration` |
FILE:references/aliyun-cli-installation-guide.md
# Aliyun CLI Installation & Configuration Guide
Complete guide for installing and configuring Aliyun CLI.
> **Aliyun CLI 3.3.0+**: Supports installing and using all published Alibaba Cloud product plugins. Make sure to upgrade to 3.3.0 or later for full plugin ecosystem coverage.
## Installation
### macOS
**Using Homebrew (Recommended)**
```bash
brew install aliyun-cli
# Upgrade to latest
brew upgrade aliyun-cli
# Verify version (>= 3.3.0)
aliyun version
```
**Using Binary**
```bash
# Download
wget https://aliyuncli.alicdn.com/aliyun-cli-macosx-latest-amd64.tgz
# Extract
tar -xzf aliyun-cli-macosx-latest-amd64.tgz
# Move to PATH
sudo mv aliyun /usr/local/bin/
# Verify
aliyun version
```
### Linux
**Debian/Ubuntu**
```bash
# Download
wget https://aliyuncli.alicdn.com/aliyun-cli-linux-latest-amd64.tgz
# Extract and install
tar -xzf aliyun-cli-linux-latest-amd64.tgz
sudo mv aliyun /usr/local/bin/
# Verify
aliyun version
```
**CentOS/RHEL**
```bash
# Download
wget https://aliyuncli.alicdn.com/aliyun-cli-linux-latest-amd64.tgz
# Extract and install
tar -xzf aliyun-cli-linux-latest-amd64.tgz
sudo mv aliyun /usr/local/bin/
# Verify
aliyun version
```
**ARM64 Architecture**
```bash
# Download ARM64 version
wget https://aliyuncli.alicdn.com/aliyun-cli-linux-latest-arm64.tgz
# Extract and install
tar -xzf aliyun-cli-linux-latest-arm64.tgz
sudo mv aliyun /usr/local/bin/
```
### Windows
**Using Binary**
1. Download from: https://aliyuncli.alicdn.com/aliyun-cli-windows-latest-amd64.zip
2. Extract the ZIP file
3. Add the directory to your PATH environment variable
4. Open new Command Prompt or PowerShell
5. Verify: `aliyun version`
**Using PowerShell**
```powershell
# Download
Invoke-WebRequest -Uri "https://aliyuncli.alicdn.com/aliyun-cli-windows-latest-amd64.zip" -OutFile "aliyun-cli.zip"
# Extract
Expand-Archive -Path aliyun-cli.zip -DestinationPath C:\aliyun-cli
# Add to PATH (requires admin privileges)
$env:Path += ";C:\aliyun-cli"
[Environment]::SetEnvironmentVariable("Path", $env:Path, [System.EnvironmentVariableTarget]::Machine)
# Verify
aliyun version
```
## Configuration
### Quick Start
```bash
aliyun configure set \
--mode AK \
--access-key-id <your-access-key-id> \
--access-key-secret <your-access-key-secret> \
--region cn-hangzhou
```
All `aliyun configure` commands support non-interactive flags, which is the recommended approach —
it works in scripts, CI/CD pipelines, and agent-driven automation without hanging on stdin prompts.
**Where to Get Access Keys**
1. Log in to Aliyun Console: https://ram.console.aliyun.com/
2. Navigate to: AccessKey Management
3. Create a new AccessKey pair
4. Save the secret immediately — it's only shown once
### Configuration Modes
Aliyun CLI supports 6 authentication modes. All examples below use non-interactive flags.
#### 1. AK Mode (Access Key)
Most common mode for personal accounts and scripts.
```bash
aliyun configure set \
--mode AK \
--access-key-id LTAI5tXXXXXXXX \
--access-key-secret 8dXXXXXXXXXXXXXXXXXXXXXXXX \
--region cn-hangzhou
```
Configuration is stored in `~/.aliyun/config.json`:
```json
{
"current": "default",
"profiles": [
{
"name": "default",
"mode": "AK",
"access_key_id": "LTAI5tXXXXXXXX",
"access_key_secret": "8dXXXXXXXXXXXXXXXXXXXXXXXX",
"region_id": "cn-hangzhou",
"output_format": "json",
"language": "en"
}
]
}
```
#### 2. StsToken Mode (Temporary Credentials)
For short-lived access (tokens expire in 1-12 hours).
```bash
aliyun configure set \
--mode StsToken \
--access-key-id LTAI5tXXXXXXXX \
--access-key-secret 8dXXXXXXXXXXXXXXXXXXXXXXXX \
--sts-token v1.0:XXXXXXXXXXXXXXXX \
--region cn-hangzhou
```
Use cases: CI/CD pipelines, temporary access for external contractors, cross-account access.
#### 3. RamRoleArn Mode (Assume RAM Role)
Assume a RAM role for elevated or cross-account access.
```bash
aliyun configure set \
--mode RamRoleArn \
--access-key-id LTAI5tXXXXXXXX \
--access-key-secret 8dXXXXXXXXXXXXXXXXXXXXXXXX \
--ram-role-arn acs:ram::123456789012:role/AdminRole \
--role-session-name my-session \
--region cn-hangzhou
```
Use cases: cross-account resource access, temporary elevated privileges, role-based access control.
#### 4. EcsRamRole Mode (ECS Instance RAM Role)
Use the RAM role attached to an ECS instance — no credentials needed.
```bash
aliyun configure set \
--mode EcsRamRole \
--ram-role-name MyEcsRole \
--region cn-hangzhou
```
Requirements: must be running on an ECS instance with a RAM role attached.
Use cases: scripts and automation running on ECS instances.
#### 5. RsaKeyPair Mode (RSA Key Pair)
Use RSA key pair for authentication (generate key pair in Aliyun Console first).
```bash
aliyun configure set \
--mode RsaKeyPair \
--private-key /path/to/private-key.pem \
--key-pair-name my-key-pair \
--region cn-hangzhou
```
#### 6. RamRoleArnWithEcs Mode (ECS + RAM Role)
Combine ECS instance role with RAM role assumption for cross-account access from ECS.
```bash
aliyun configure set \
--mode RamRoleArnWithEcs \
--ram-role-name MyEcsRole \
--ram-role-arn acs:ram::123456789012:role/TargetRole \
--role-session-name my-session \
--region cn-hangzhou
```
### Environment Variables
**Highest priority** - overrides config file
**Access Key Mode**
```bash
export ALIBABA_CLOUD_ACCESS_KEY_ID=your_access_key_id
export ALIBABA_CLOUD_ACCESS_KEY_SECRET=your_access_key_secret
export ALIBABA_CLOUD_REGION_ID=cn-hangzhou
```
**STS Token Mode**
```bash
export ALIBABA_CLOUD_ACCESS_KEY_ID=your_access_key_id
export ALIBABA_CLOUD_ACCESS_KEY_SECRET=your_access_key_secret
export ALIBABA_CLOUD_SECURITY_TOKEN=your_sts_token
export ALIBABA_CLOUD_REGION_ID=cn-hangzhou
```
**ECS RAM Role Mode**
```bash
export ALIBABA_CLOUD_ECS_METADATA=role_name
```
**Use Case**:
- CI/CD pipelines
- Docker containers
- Temporary credential override
### Managing Multiple Profiles
**Create Named Profiles**
```bash
aliyun configure set --profile projectA \
--mode AK \
--access-key-id LTAI5tAAAAAAAA \
--access-key-secret 8dAAAAAAAAAAAAAAAAAAAAAAAA \
--region cn-hangzhou
aliyun configure set --profile projectB \
--mode AK \
--access-key-id LTAI5tBBBBBBBB \
--access-key-secret 8dBBBBBBBBBBBBBBBBBBBBBBBB \
--region cn-shanghai
```
**Use Specific Profile**
```bash
aliyun ecs describe-instances --profile projectA
export ALIBABA_CLOUD_PROFILE=projectA
aliyun ecs describe-instances # Uses projectA
```
**List and Switch Profiles**
```bash
aliyun configure list # List all profiles
aliyun configure set --current projectA # Switch default profile
```
### Credential Priority
Credentials are loaded in this order (first found wins):
1. **Command-line flag**: `--profile <name>`
2. **Environment variable**: `ALIBABA_CLOUD_PROFILE`
3. **Environment credentials**: `ALIBABA_CLOUD_ACCESS_KEY_ID`, etc.
4. **Configuration file**: `~/.aliyun/config.json` (current profile)
5. **ECS Instance RAM Role**: If running on ECS with attached role
## Verification
### Test Authentication
```bash
# Basic test - list regions
aliyun ecs describe-regions
# Expected output: JSON array of regions
```
**If successful**, you'll see:
```json
{
"Regions": {
"Region": [
{
"RegionId": "cn-hangzhou",
"RegionEndpoint": "ecs.cn-hangzhou.aliyuncs.com",
"LocalName": "华东 1(杭州)"
},
...
]
},
"RequestId": "..."
}
```
**If failed**, you'll see error messages:
- `InvalidAccessKeyId.NotFound` - Wrong Access Key ID
- `SignatureDoesNotMatch` - Wrong Access Key Secret
- `InvalidSecurityToken.Expired` - STS token expired (for StsToken mode)
- `Forbidden.RAM` - Insufficient permissions
### Debug Configuration
```bash
# Show current configuration
aliyun configure get
# Test with debug logging
aliyun ecs describe-regions --log-level=debug
# Check credential provider
aliyun configure get mode
```
## Security Best Practices
### 1. Use RAM Users (Not Root Account)
❌ **Don't**: Use Aliyun root account credentials
✅ **Do**: Create RAM users with specific permissions
```bash
# Create RAM user in console
# Attach only necessary policies
# Use RAM user's access keys
```
### 2. Principle of Least Privilege
Grant only the minimum permissions needed:
```bash
# Example: Read-only ECS access
# Attach policy: AliyunECSReadOnlyAccess
```
### 3. Rotate Access Keys Regularly
```bash
# Create new access key in RAM Console, then update configuration
aliyun configure set --access-key-id NEW_KEY --access-key-secret NEW_SECRET
# Delete old access key from console
```
### 4. Use STS Tokens for Temporary Access
```bash
aliyun configure set --mode StsToken \
--access-key-id XXXX --access-key-secret XXXX \
--sts-token XXXX --region cn-hangzhou
```
### 5. Use ECS RAM Roles When Possible
```bash
aliyun configure set --mode EcsRamRole --ram-role-name MyRole --region cn-hangzhou
```
### 6. Never Commit Credentials
```bash
# Add to .gitignore
echo "~/.aliyun/config.json" >> .gitignore
# Use environment variables in CI/CD instead
```
### 7. Secure Config File
```bash
# Restrict permissions
chmod 600 ~/.aliyun/config.json
```
## Troubleshooting
### Issue: Command Not Found
```bash
# Check installation
which aliyun
# Check PATH
echo $PATH
# Reinstall or add to PATH
```
### Issue: Authentication Failed
```bash
# Verify configuration
aliyun configure get
# Test with debug
aliyun ecs describe-regions --log-level=debug
# Check credentials in console
# Verify access key is active
```
### Issue: Permission Denied
```bash
# Error: Forbidden.RAM
# Check RAM user permissions
# Attach necessary policies in RAM console
# Example: AliyunECSFullAccess for ECS operations
```
### Issue: STS Token Expired
```bash
# Error: InvalidSecurityToken.Expired
# Reconfigure with new token
aliyun configure set --mode StsToken \
--access-key-id XXXX --access-key-secret XXXX \
--sts-token NEW_TOKEN --region cn-hangzhou
```
### Issue: Wrong Region
```bash
# Some resources may not exist in the specified region
# Check available regions
aliyun ecs describe-regions
# Update default region
aliyun configure set region cn-shanghai
```
## Advanced Configuration
### Custom Endpoint
```bash
# Use custom or private endpoint
export ALIBABA_CLOUD_ECS_ENDPOINT=ecs-vpc.cn-hangzhou.aliyuncs.com
```
### Proxy Settings
```bash
# HTTP proxy
export HTTP_PROXY=http://proxy.example.com:8080
export HTTPS_PROXY=http://proxy.example.com:8080
# No proxy for specific domains
export NO_PROXY=localhost,127.0.0.1,.aliyuncs.com
```
### Timeout Settings
```bash
# Connection timeout (default: 10s)
export ALIBABA_CLOUD_CONNECT_TIMEOUT=30
# Read timeout (default: 10s)
export ALIBABA_CLOUD_READ_TIMEOUT=30
```
## Next Steps
After installation and configuration:
1. **Install plugins** for services you need (v3.3.0+ supports all published product plugins):
```bash
aliyun plugin install --names ecs vpc rds
# List all available plugins
aliyun plugin list-remote
```
2. **Explore commands**:
```bash
aliyun ecs --help
aliyun fc --help
```
3. **Read documentation**:
- [Command Syntax Guide](./command-syntax.md)
- [Global Flags Reference](./global-flags.md)
- [Common Scenarios](./common-scenarios.md)
## References
- Official Documentation: https://help.aliyun.com/zh/cli/
- RAM Console: https://ram.console.aliyun.com/
- Access Key Management: https://ram.console.aliyun.com/manage/ak
- Plugin Repository: https://github.com/aliyun/aliyun-cli
FILE:references/intent-mapping.md
# Intent Mapping — 场景关键词映射解决方案
用户通常不会直接说解决方案名称,需要从模糊描述推断意图。以下是常见场景的关键词映射:
| 用户描述关键词 | 匹配的解决方案 |
|---|---|
| "搭个网站" / "建站" / "企业门户" | `build-a-website` |
| "AI 问答" / "智能客服" / "RAG" / "知识库" | `analyticdb-rag`, `elasticsearch-ai-assistant`, `tongyi-langchain` |
| "日志分析" / "日志平台" / "实时日志" | `real-time-log-analysis-selectdb`, `log-management-platform` |
| "监控告警" / "Prometheus" / "可观测" | `prometheus-cloud-monitoring`, `end-to-end-tracing-diagnostics` |
| "高可用" / "容灾" / "多活" | `serverless-ha`, `tltcamanidl` |
| "小程序" / "微信" | `develop-your-wechat-mini-program-in-10-minutes` |
| "AI 绘画" / "Stable Diffusion" / "图像生成" | `pai-eas` |
| "数据库迁移" / "MongoDB 迁移" | `migrate-self-managed-mongodb-to-cloud` |
| "读写分离" | `rds-read-write-splitting` 或 `redis-read-write-splitting-tair-proxy` |
| "DeepSeek" / "个人网站 + AI" | `ecs-and-deepseek-build-personal-website` |
| "消息队列" / "RocketMQ" / "RabbitMQ" | `rocketmq-*`, `rabbitmq-serverless` |
| "微服务" / "流量治理" / "限流熔断" | `mse-traffic-protection` |
| "容器" / "ACK" / "K8s" | `ack-services`, `nginx-ingress` |
| "无服务器" / "Serverless" | `serverless-ha` |
| "数据可视化" / "大屏" / "DataV" | `datav-for-atlas`, `datav-for-digitalization` |
| "大模型安全" / "LLM 安全" | `large-language-model-security-system` |
| "AI 应用" / "百炼" / "Model Studio" | `ai-applications-model-studio` |
| "WordPress" / "博客" / "MySQL 建站" | `mysql-rds` |
| "ClickHouse" / "HTAP" | `rds-clickhouse-htap` |
| "Hologres" / "OLAP" | `hologres-olap` |
| "PolarDB + AI" / "PolarDB 向量搜索" | `polardb-ai-search`, `polardb-mysql-mcp` |
| "物联网" / "时序数据" | `lindorm-data-process` |
| "CentOS 迁移" / "系统迁移" | `centos-alinux-migration` |
| "分布式任务调度" / "定时任务" | `mse-schedulerx` |
| "OLAP 数仓" | `hologres-olap`, `rds-clickhouse-htap` |
## 匹配规则
1. **Exact match first** — 用户说了解决方案名称,直接匹配
2. **Keyword match** — 用户描述包含上述关键词,映射到对应方案
3. **Partial match OK** — 描述与某个方案的领域有部分重叠,作为候选
4. **Ambiguous → list candidates** — 2-3个方案都匹配时,列出让用户选择:
```
找到以下几个匹配的方案,请选择:
1. analyticdb-rag — 基于 AnalyticDB + 通义千问的 RAG 智能问答
2. elasticsearch-ai-assistant — Elasticsearch + Kibana 智能运维助手
3. tongyi-langchain — 通义千问 + LangChain 对话服务
```
FILE:references/ram-policies.md
# RAM Policies for Alibaba Cloud Solution Deploy
This document lists all RAM permissions required by the Skill's built-in scripts.
> **Note**: This Skill is a *meta-tool* — it helps users deploy various Alibaba Cloud solutions. The permissions below cover **only the Skill's own helper scripts**. Each specific solution deployment will require additional product-level permissions (ECS, VPC, RDS, etc.), which are presented to the user for confirmation in the execution plan (Step B.4) before any resources are created.
## Required RAM Permissions
### Overview
The Skill's scripts call two Alibaba Cloud services:
| Service | Endpoint | Scripts |
|---------|----------|---------|
| **OpenAPI Explorer** | `openapi-mcp.cn-hangzhou.aliyuncs.com` | `search_apis.py`, `search_documents.py`, `diagnose_cli_command.py`, `lsit_products.py`, `lsit_api_overview.py` |
| **IaCService (Terraform Runtime)** | `iac.cn-zhangjiakou.aliyuncs.com` | `terraform_runtime_online.sh` |
| **STS** | (default) | `verify_env.sh` |
### Detailed API-Level Permissions
```json
{
"Version": "1",
"Statement": [
{
"Effect": "Allow",
"Action": [
"sts:GetCallerIdentity"
],
"Resource": "*",
"Condition": {}
},
{
"Effect": "Allow",
"Action": [
"openapiexplorer:SearchApis",
"openapiexplorer:SearchDocuments",
"openapiexplorer:DiagnoseCLI",
"openapiexplorer:ListProducts",
"openapiexplorer:ListApiOverviews"
],
"Resource": "*",
"Condition": {}
},
{
"Effect": "Allow",
"Action": [
"iacservice:ValidateModule",
"iacservice:ExecuteTerraformPlan",
"iacservice:ExecuteTerraformApply",
"iacservice:ExecuteTerraformDestroy",
"iacservice:GetExecuteState"
],
"Resource": "*",
"Condition": {}
}
]
}
```
### Permission Details by Script
| Script | API Action | Permission |
|--------|-----------|------------|
| `verify_env.sh` | `GetCallerIdentity` | `sts:GetCallerIdentity` |
| `search_apis.py` | `SearchApis` | `openapiexplorer:SearchApis` |
| `search_documents.py` | `SearchDocuments` | `openapiexplorer:SearchDocuments` |
| `diagnose_cli_command.py` | `DiagnoseCLI` | `openapiexplorer:DiagnoseCLI` |
| `lsit_products.py` | `ListProducts` | `openapiexplorer:ListProducts` |
| `lsit_api_overview.py` | `ListApiOverviews` | `openapiexplorer:ListApiOverviews` |
| `terraform_runtime_online.sh` | `ValidateModule` | `iacservice:ValidateModule` |
| `terraform_runtime_online.sh` | `ExecuteTerraformPlan` | `iacservice:ExecuteTerraformPlan` |
| `terraform_runtime_online.sh` | `ExecuteTerraformApply` | `iacservice:ExecuteTerraformApply` |
| `terraform_runtime_online.sh` | `ExecuteTerraformDestroy` | `iacservice:ExecuteTerraformDestroy` |
| `terraform_runtime_online.sh` | `GetExecuteState` | `iacservice:GetExecuteState` |
## How to Attach Policies
### Option 1: Creating Custom Policy (Recommended — Least Privilege)
1. Log in to [RAM Console](https://ram.console.aliyun.com/)
2. Navigate to **Permissions** > **Policies**
3. Click **Create Policy**
4. Select **Script** mode
5. Copy and paste the JSON policy from "Detailed API-Level Permissions" above
6. Name the policy: `AlibabaCloudSolutionDeploySkillPolicy`
7. Click **OK** to create
8. Navigate to **Identities** > **Users**
9. Find your RAM user and click **Add Permissions**
10. Select **Custom Policy** and choose `AlibabaCloudSolutionDeploySkillPolicy`
11. Click **OK** to attach
### Permission Verification
```bash
# Verify STS access
aliyun sts GetCallerIdentity --user-agent AlibabaCloud-Agent-Skills
# Verify OpenAPI Explorer access (search for any API)
python3 scripts/search_apis.py 'DescribeInstances'
# Verify IaCService access (validate empty module)
bash scripts/terraform_runtime_online.sh validate 'resource "null_resource" "test" {}'
```
## Common Permission Errors
| Error Code | Description | Solution |
|------------|-------------|----------|
| `Forbidden.RAM` | RAM user lacks permission for the action | Attach the custom policy above |
| `InvalidAccessKeyId.NotFound` | Access Key ID invalid | Verify credentials via `aliyun configure list` |
| `NoPermission` | No permission for the resource | Check policy is correctly attached |
FILE:references/terraform-defaults.md
# Terraform 默认参数
Path A 使用 Terraform 模块部署时,以下参数作为默认值。**必须向用户展示并确认**,不可静默使用。
## 通用默认参数
| Parameter | Default | Notes |
|-----------|---------|-------|
| `region` | `cn-hangzhou` | 杭州;可改为 cn-beijing / cn-shanghai / cn-shenzhen |
| `availability_zone` | `cn-hangzhou-h` | 跟随 region 对应的可用区 |
| `vpc_cidr` | `172.16.0.0/12` | |
| `vswitch_cidr` | `172.16.0.0/24` | |
| `instance_type` | `ecs.c7.large` | 2C4G;GPU 场景改为 `ecs.gn6i-c8g1.2xlarge` |
| `instance_name` | `<solution-name>-server` | 以方案名为前缀 |
| `disk_size` | `40` (GB) | 系统盘 |
| `rds_instance_type` | `mysql.n2.medium.1` | 2C4G RDS |
| `password` | *(must ask user)* | Passwords are sensitive credentials — never generate or assume one. The user must provide it. |
## 确认格式示例
```
将使用以下参数部署,请确认或告知需要修改:
• Region: cn-hangzhou
• Instance type: ecs.c7.large
• VPC CIDR: 172.16.0.0/12
• Password: (请提供)
```
## 模块特定参数
不同模块有额外参数,运行时检查模块 README:
- Terraform Registry: `https://registry.terraform.io/modules/alibabacloud-automation/<module_name>/alicloud/latest`
FILE:references/terraform-online-runtime.md
# Terraform Online Runtime — Usage Guide
Execute Terraform configurations remotely through Alibaba Cloud's IaCService using a single pre-built script. No local `terraform` CLI required.
## Prerequisites
- **aliyun CLI** (v3.2+) installed and configured with valid AK/SK credentials (`aliyun configure`)
- The credentials must have permission to call IaCService APIs and to manage whatever cloud resources the Terraform code declares
## SKILL_DIR Setup
Before running the script, set `SKILL_DIR` to the directory containing the skill's SKILL.md:
```bash
# Option A: dynamic (for use inside shell scripts)
SKILL_DIR="$(cd "$(dirname "BASH_SOURCE[0]")" && pwd)"
# Option B: explicit absolute path
SKILL_DIR="/path/to/your-skill-dir"
TF="SKILL_DIR/scripts/terraform_runtime_online.sh"
```
## Commands
```
terraform_runtime_online.sh validate <hcl_file_or_code>
terraform_runtime_online.sh plan <hcl_file_or_code> [existing_state_id]
terraform_runtime_online.sh apply <hcl_file_or_code> [--state-id <id>]
terraform_runtime_online.sh apply --state-id <id>
terraform_runtime_online.sh destroy <state_id>
terraform_runtime_online.sh poll <state_id> [max_attempts] [interval_seconds]
```
## Command Usage
### validate — Validate HCL syntax
```bash
$TF validate main.tf
$TF validate 'resource "alicloud_vpc" "vpc" { vpc_name = "test" cidr_block = "172.16.0.0/12" }'
```
Exit codes: `0` = Valid, `1` = Invalid / error.
### plan — Preview changes
```bash
plan_output=$($TF plan main.tf)
STATE_ID=$(echo "$plan_output" | grep '^STATE_ID=' | cut -d= -f2)
PLAN_FILE=$(echo "$plan_output" | grep '^PLAN_OUTPUT_FILE=' | cut -d= -f2)
# Compact plan summary is printed to stderr automatically.
# To view full details: cat "$PLAN_FILE"
```
Exit codes: `0` = Planned, `1` = Errored.
### apply — Create or update infrastructure
```bash
# Fresh apply (no prior state)
STATE_ID=$($TF apply main.tf | grep '^STATE_ID=' | cut -d= -f2)
echo "STATE_ID=$STATE_ID" >> terraform_state_ids.env
# Incremental update against existing state
STATE_ID=$($TF apply updated.tf --state-id "$EXISTING_STATE_ID" | grep '^STATE_ID=' | cut -d= -f2)
echo "STATE_ID=$STATE_ID" >> terraform_state_ids.env
```
Exit codes: `0` = Applied, `1` = Errored.
### destroy — Destroy resources
```bash
$TF destroy "$STATE_ID" --force
```
Without `--force`, the script lists resources and exits without destroying (safety pre-check). Always pass `--force` after confirming with the user.
Exit codes: `0` = Destroyed, `1` = Failed or not confirmed.
### poll — Poll status (standalone use)
```bash
$TF poll <state_id> [max_attempts] [interval_seconds]
```
## Workflow Patterns
### Pattern 1: Full lifecycle (plan → confirm → apply → destroy)
```bash
# 1. Write HCL
cat > main.tf << 'EOF'
resource "alicloud_vpc" "vpc" {
vpc_name = "my-vpc"
cidr_block = "172.16.0.0/12"
}
EOF
# 2. Plan
plan_output=$($TF plan main.tf)
PLAN_FILE=$(echo "$plan_output" | grep '^PLAN_OUTPUT_FILE=' | cut -d= -f2)
# ⚠️ STOP — present plan summary to user and wait for explicit confirmation before continuing
# 3. Apply (fresh apply with code; do NOT reuse the plan STATE_ID)
STATE_ID=$($TF apply main.tf | grep '^STATE_ID=' | cut -d= -f2)
echo "STATE_ID=$STATE_ID" >> terraform_state_ids.env
# 4. Destroy when done
$TF destroy "$STATE_ID" --force
```
### Pattern 2: Quick apply (skip plan)
```bash
STATE_ID=$($TF apply main.tf | grep '^STATE_ID=' | cut -d= -f2)
echo "STATE_ID=$STATE_ID" >> terraform_state_ids.env
```
### Pattern 3: Incremental update
```bash
STATE_ID=$($TF apply updated.tf --state-id "$EXISTING_STATE_ID" | grep '^STATE_ID=' | cut -d= -f2)
```
### Pattern 4: Validate before deploy
```bash
$TF validate main.tf && echo "Validation passed"
```
## Critical Rules
- **ALWAYS use `$TF <command>`** — never write inline `aliyun iacservice` commands; inline commands silently fail due to argument/endpoint quirks
- **ALWAYS save every `STATE_ID`** returned by apply to a file (e.g., `terraform_state_ids.env`) for later cleanup
- **After `plan`, ALWAYS wait for user confirmation** before calling `apply`
- **After plan, use fresh apply** (`$TF apply <code>`), NOT `--state-id` from the plan run — IaCService locks plan stateIds
## Error Reference
| Error | Likely Cause |
|-------|-------------|
| `InvalidOperation.TaskStatus` | Plan stateId is locked — use fresh apply with code instead |
| `Your account does not have enough balance` | Insufficient balance for postpaid resources |
| `InvalidAccessKeyId` | AK/SK credentials are invalid or expired |
| `InvalidImageId.NotFound` | Image ID doesn't exist in the target region |
| Provider/resource errors | Unsupported resource types or invalid arguments |
FILE:references/tf-plan/tf-solutions.md
# 技术解决方案
| 解决方案模版名称 | 描述 | 进度 | Module 名称 | Module 地址 | 备注
| --- | --- | --- | --- | --- | ---
| ack-services | 创建高可用、可自动伸缩的 Kubernetes 集群基础设施,使用阿里云 ACK 容器服务,支持集群自动伸缩(CAS)和水平 Pod 自动伸缩(HPA),适用于需要容器化应用编排和管理的企业 | 已完成 | ack-services | https://registry.terraform.io/modules/alibabacloud-automation/ack-services/alicloud/latest |
| alb-acrlb | 通过阿里云 ALB 应用负载均衡和 CEN 云企业网实现跨地域流量调度与负载均衡,支持多地域 ECS 实例部署,适用于需要跨地域高可用与容灾的企业应用 | 已完成 | alb-cross-region-load-balancing | https://registry.terraform.io/modules/alibabacloud-automation/alb-cross-region-load-balancing/alicloud/latest | 多 region 抽象子Module
| analyticdb-rag | 基于 AnalyticDB for PostgreSQL 和通义千问构建智能客服 RAG 系统,实现检索增强生成架构,适用于需要 AI 智能问答和企业知识库应用的场景 | 已完成 | analyticdb-rag | https://registry.terraform.io/modules/alibabacloud-automation/analyticdb-rag/alicloud/latest |
| build-a-website | 创建企业门户网站基础架构,包含 VPC、RDS MySQL 数据库和 Mobi 低代码开发平台集成,适用于快速构建现代企业网站和低代码应用开发 | 已完成 | build-enterprise-portal-website | https://registry.terraform.io/modules/alibabacloud-automation/build-enterprise-portal-website/alicloud/latest |
| build-ai-applications-based-on-alibaba-cloud-model-studio | 基于阿里云百炼 Model Studio 构建 AI 应用和智能体(Agent)工作流,自动部署 ECS 实例和 AI 应用环境,适用于企业快速构建和部署 AI 驱动的应用 | 已完成 | ai-applications-model-studio | https://registry.terraform.io/modules/alibabacloud-automation/ai-applications-model-studio/alicloud/latest |
| build-an-observability-system-for-ai-applications-at-low-costs | 使用 ARMS 应用实时监控服务构建 AI 应用低成本可观测系统,集成 VPC、ECS 和监控告警功能,适用于需要实时监控 AI 应用性能和运行状态的企业 | 已完成 | ai-observability-system | https://registry.terraform.io/modules/alibabacloud-automation/ai-observability-system/alicloud/latest |
| build-large-model-application-security-system | 为大语言模型应用构建全面安全防护体系,包含 VPC 网络隔离、ECS 计算资源、RAM 身份管理和自动化安全工具部署,适用于保护 AI 应用免受内容安全和访问控制等安全威胁 | 已完成 | large-language-model-security-system | https://registry.terraform.io/modules/alibabacloud-automation/large-language-model-security-system/alicloud/latest |
| build-large-scale-low-cost-real-time-log-management-platform | 构建大规模低成本实时日志管理平台,使用 SLS 日志服务、ECS 和 Kibana 可视化,适用于需要实时日志收集、处理和分析的企业级应用 | 已完成 | log-management-platform | https://registry.terraform.io/modules/alibabacloud-automation/log-management-platform/alicloud/latest |
| centos-alinux | 将 CentOS 系统迁移至阿里云 Linux 操作系统的自动化解决方案,在 CentOS 7 系统上自动部署迁移环境,适用于需要将自建 CentOS 服务器平滑迁移到阿里云 Linux 的企业 | 已完成 | centos-alinux-migration | https://registry.terraform.io/modules/alibabacloud-automation/centos-alinux-migration/alicloud/latest |
| comprehensive-real-time-monitoring-of-cloud-services-through-managed-service-for-prometheus | 通过 Prometheus 托管服务对云上资源进行全面实时监控,集成 VPC、ECS、RDS、Redis、RocketMQ 和 MSE 等多种服务,适用于云原生应用的统一可观测性监控与告警 | 已完成 | prometheus-cloud-monitoring | https://registry.terraform.io/modules/alibabacloud-automation/prometheus-cloud-monitoring/alicloud/latest |
| datav-for-atlas | 构建 DataV Atlas 时空决策平台,使用 RDS PostgreSQL 存储空间数据并进行可视化分析,适用于需要时空数据分析和可视化大屏决策的企业 | 已完成 | datav-atlas-solution | https://registry.terraform.io/modules/alibabacloud-automation/datav-atlas-solution/alicloud/latest |
| datav-for-digitalization | 快速构建企业数字化管理大屏,部署 VPC、VSwitch、安全组和 RDS MySQL 数据库,为 DataV 数字孪生大屏提供数据存储和网络安全基础设施,适用于需要搭建企业经营数据可视化看板的场景 | 已完成 | datav-for-digitalization | https://registry.terraform.io/modules/alibabacloud-automation/datav-for-digitalization/alicloud/latest |
| develop-apps | 基于阿里云 EMAS 移动研发平台和云效研发协作平台,构建云上移动应用开发完整基础设施(VPC、ECS、RDS),提供移动应用从开发、测试到运维的全生命周期管理能力 | 已完成 | develop-apps | https://registry.terraform.io/modules/alibabacloud-automation/develop-apps/alicloud/latest |
| develop-your-wechat-mini-program-in-10-minutes | 快速搭建微信/支付宝小程序后端基础设施,自动部署 VPC、ECS、RDS MySQL 数据库并完成 WordPress 配置,适用于小程序后端开发和内容管理网站的快速搭建 | 已完成 | wechat-mini-program-infrastructure | https://registry.terraform.io/modules/alibabacloud-automation/wechat-mini-program-infrastructure/alicloud/latest |
| ecs-and-deepseek-build-personal-website | 在 ECS 上一键部署 DeepSeek AI 个人网站,自动创建 VPC、ECS 实例、安全组和 RAM 用户并完成 DeepSeek 应用配置,适用于开发者快速搭建个人 AI 助手网站 | 已完成 | deepseek-personal-website | https://registry.terraform.io/modules/alibabacloud-automation/deepseek-personal-website/alicloud/latest |
| ecs-deploy-deepsite-application | 在 ECS 上自动化部署 DeepSite 应用,DeepSite 是阿里云 AI 前端代码生成工具,可将自然语言描述转换为 Web 应用,支持 Qwen 和 DeepSeek 等大模型,适用于 Web 工具开发和产品快速原型场景 | 已完成 | ecs-deploy-deepsite-application | https://registry.terraform.io/modules/alibabacloud-automation/ecs-deploy-deepsite-application/alicloud/latest |
| elasticsearch-ai-assistant | 构建 Elasticsearch 智能运维助手,部署 VPC、Elasticsearch 实例和 Kibana,提供分布式系统下的日志分析和智能运维可视化能力,适用于需要智能运维监控和日志检索的场景 | 已完成 | elasticsearch-ai-assistant | https://registry.terraform.io/modules/alibabacloud-automation/elasticsearch-ai-assistant/alicloud/latest |
| end-to-end-tracing-and-diagnostics | 构建分布式应用全链路追踪与诊断系统,部署 VPC、ECS、RDS、Redis、RocketMQ 和 MSE 等资源,提供微服务架构下的性能监控与故障定位能力,适用于分布式微服务架构的可观测性建设 | 已完成 | end-to-end-tracing-diagnostics | https://registry.terraform.io/modules/alibabacloud-automation/end-to-end-tracing-diagnostics/alicloud/latest |
| ha-web | 构建高可用 Web 共享存储服务,部署多 ECS 实例、NAS 共享文件存储和 CLB 负载均衡,提供可横向扩展的 Web 架构,适用于需要高可用性和多节点共享存储的 Web 应用场景 | 已完成 | high-availability-web-shared-storage | https://registry.terraform.io/modules/alibabacloud-automation/high-availability-web-shared-storage/alicloud/latest |
| hologres-olap | 基于阿里云 Hologres 实时数仓构建高性能轻量级 OLAP 分析平台,创建 VPC、VSwitch 和 Hologres 实例,适用于需要对大规模数据进行实时 OLAP 多维分析的场景 | 已完成 | hologres-olap | https://registry.terraform.io/modules/alibabacloud-automation/hologres-olap/alicloud/latest |
| improve-app-availability | 通过 ALB 应用负载均衡和 ESS 弹性伸缩提升应用可用性,支持基于负载的自动扩缩容,适用于需要高可用性和弹性伸缩能力的 Web 应用场景 | 已完成 | improve-app-availability | https://registry.terraform.io/modules/alibabacloud-automation/improve-app-availability/alicloud/latest |
| lindorm-data-process | 构建统一时序数据分析处理平台,部署 VPC、ECS 和 Lindorm 时序数据库,适用于物联网、工业互联网等场景下海量时序数据的高效处理与分析 | 已完成 | lindorm-data-process | https://registry.terraform.io/modules/alibabacloud-automation/lindorm-data-process/alicloud/latest |
| log-monitoring-alarming | 创建基于 SLS 日志服务的全面日志监控告警解决方案,部署 VPC、ECS、SLS 项目及日志采集配置,实现应用日志实时采集与告警通知,适用于需要实时监控应用日志并快速响应异常的企业 | 已完成 | log-monitoring-alarming | https://registry.terraform.io/modules/alibabacloud-automation/log-monitoring-alarming/alicloud/latest |
| migrate-self-managed-mongodb-to-cloud | 将自建 MongoDB 迁移至阿里云云数据库 MongoDB 的完整解决方案,自动创建 VPC、ECS、ApsaraDB for MongoDB 并执行迁移脚本,适用于需要将自建 MongoDB 平滑迁移上云的企业 | 已完成 | mongodb-migration | https://registry.terraform.io/modules/alibabacloud-automation/mongodb-migration/alicloud/latest |
| mse-schedulerx | 基于 MSE SchedulerX 构建分布式任务调度完整解决方案,部署 VPC、ECS、RDS MySQL 并自动部署 SchedulerX 示例应用,适用于需要可靠分布式定时任务和批量任务调度的企业应用 | 已完成 | mse-schedulerx | https://registry.terraform.io/modules/alibabacloud-automation/mse-schedulerx/alicloud/latest |
| nginx-ingress | 在阿里云 ACK Kubernetes 集群上部署 Nginx 并通过 Ingress 对外暴露服务,集成 Nginx Ingress Controller、SLS 日志和 ARMS Prometheus 监控,适用于需要在 Kubernetes 上统一管理 HTTP/HTTPS 流量入口的场景 | 已完成 | nginx-ingress-deployment | https://registry.terraform.io/modules/alibabacloud-automation/nginx-ingress-deployment/alicloud/latest |
| oss-nginx | 将 Nginx 访问日志通过 SLS 日志服务自动采集并归档到 OSS 对象存储,部署 VPC、ECS、SLS 和 OSS 资源,适用于需要低成本长期归档应用访问日志的场景 | 已完成 | oss-nginx-log-archiving | https://registry.terraform.io/modules/alibabacloud-automation/oss-nginx-log-archiving/alicloud/latest |
| pai-eas | 在阿里云 PAI-EAS 上部署 Stable Diffusion WebUI AI 绘图服务,集成 NAS 文件存储、NAT Gateway 和 GPU 计算资源,适用于需要在云上提供文生图/图生图 AI 绘画服务的场景 | 已完成 | pai-eas-stable-diffusion | https://registry.terraform.io/modules/alibabacloud-automation/pai-eas-stable-diffusion/alicloud/latest |
| polardb-ai-search | 基于 PolarDB for PostgreSQL 的原生 SQL 实现多模态 AI 智能搜索能力,部署 VPC、PolarDB 集群和 OSS 存储资源,适用于需要对图片、文本等多模态内容进行向量检索和 AI 搜索的场景 | 已完成 | polardb-ai-search | https://registry.terraform.io/modules/alibabacloud-automation/polardb-ai-search/alicloud/latest |
| polardb-mysql-mcp | 通过 MCP(Model Context Protocol)协议赋能 PolarDB MySQL,构建支持可视化 OLAP 智能体应用的数据库环境,部署 VPC、PolarDB 集群并开启公网访问端点,适用于 AI 大模型直接操作数据库进行数据分析的场景 | 已完成 | polardb-mysql-mcp | https://registry.terraform.io/modules/alibabacloud-automation/polardb-mysql-mcp/alicloud/latest |
| rabbitmq-serverless | 创建 RabbitMQ Serverless 消息队列实例及完整路由配置(虚拟主机、Exchange、队列和绑定),含 RAM 用户权限管理,适用于需要快速接入 Serverless 消息队列实现系统解耦和异步通信的场景 | 已完成 | rabbitmq-serverless | https://registry.terraform.io/modules/alibabacloud-automation/rabbitmq-serverless/alicloud/latest |
| rdsclickhouse-htap | 使用 RDS MySQL 和 ClickHouse 构建 HTAP(混合事务分析处理)一体化解决方案,部署 VPC、RDS(事务处理)、ClickHouse(分析处理)和 ECS,适用于同时需要高并发写入和实时数据分析的业务场景 | 已完成 | rds-clickhouse-htap | https://registry.terraform.io/modules/alibabacloud-automation/rds-clickhouse-htap/alicloud/latest |
| read-write-splitting-through-rds-proxy | 通过 RDS 数据库代理实现 MySQL 读写分离,自动将读请求路由到只读实例以提升数据库性能,部署 VPC、ECS、RDS 主实例+只读副本和代理,适用于读多写少、需要提升数据库查询吞吐量的应用 | 已完成 | rds-read-write-splitting | https://registry.terraform.io/modules/alibabacloud-automation/rds-read-write-splitting/alicloud/latest |
| read-write-splitting-through-tair-proxy | 通过 Tair 代理实现 Redis 读写分离,自动将读请求路由到只读节点以提升 Redis 并发性能,部署 VPC、ECS 和 Tair(Redis 企业版)实例,适用于 Redis 高并发读多写少场景 | 已完成 | redis-read-write-splitting-tair-proxy | https://registry.terraform.io/modules/alibabacloud-automation/redis-read-write-splitting-tair-proxy/alicloud/latest |
| real-time-log-analysis-with-selectdb | 使用 SelectDB 构建高效实时日志存储与分析平台,部署 VPC、ECS 日志处理实例和 SelectDB 数据库,适用于需要对海量日志进行实时分析和多维查询的业务场景 | 已完成 | real-time-log-analysis-selectdb | https://registry.terraform.io/modules/alibabacloud-automation/real-time-log-analysis-selectdb/alicloud/latest |
| rocketmq-data-consistency | 使用 RocketMQ 事务消息实现分布式事务与跨服务数据一致性,部署 VPC、ECS、RDS 和 RocketMQ 资源,适用于电商订单、支付等需要保证多服务间数据强一致性的分布式系统 | 已完成 | rocketmq-data-consistency | https://registry.terraform.io/modules/alibabacloud-automation/rocketmq-data-consistency/alicloud/latest |
| rocketmq-for-multi-agent-communication | 基于 RocketMQ 实现多智能体(Multi-Agent)系统异步通信,创建 VPC、VSwitch、ECS 和安全组等基础设施,适用于 AI 多 Agent 协同工作时的消息传递和任务协调场景 | 已完成 | rocketmq-multi-agent-communication | https://registry.terraform.io/modules/alibabacloud-automation/rocketmq-multi-agent-communication/alicloud/latest |
| serverless-ha | 基于 PolarDB MySQL Serverless、ALB 和 SAE 构建 Serverless 高可用架构,支持自动弹性伸缩和多可用区高可用,适用于需要极简运维、按需付费的 Serverless Web 应用场景 | 已完成 | serverless-high-availability | https://registry.terraform.io/modules/alibabacloud-automation/serverless-high-availability/alicloud/latest |
| the-headless-architecture-solution-of-alibaba-cloud-ecs | 基于 ECS 实现前后端分离(Headless)架构,前端 Nginx 与后端 Java 服务跨多可用区部署,通过 ALB 实现流量分发,适用于需要高可用前后端分离 Web 应用的场景 | 已完成 | ecs-headless-architecture | https://registry.terraform.io/modules/alibabacloud-automation/ecs-headless-architecture/alicloud/latest |
| the-headless-architecture-solution-of-alibaba-cloud-sae | 基于 SAE Serverless 应用引擎实现前后端分离(Headless)架构,通过 SLB 负载均衡分发流量,适用于需要无需管理服务器即可快速部署前后端分离 Web 应用的场景 | 已完成 | sae-headless-architecture | https://registry.terraform.io/modules/alibabacloud-automation/sae-headless-architecture/alicloud/latest |
| tltcamanidl | 构建多地域同城双活灾备架构,通过 CEN 云企业网跨区域互联、DTS 数据同步和 PolarDB 集群实现 RPO/RTO 极低的高可用容灾,适用于金融、电商等需要跨地域容灾保障的关键业务系统 | 已完成 | multi-region-active-active-disaster-recovery | https://registry.terraform.io/modules/alibabacloud-automation/multi-region-active-active-disaster-recovery/alicloud/latest |
| tongyi-langchain | 基于通义千问和 LangChain 框架构建智能对话服务,使用 PAI-EAS 部署 AI 模型推理服务、NAS 文件存储等资源,适用于快速构建企业级 AI 问答和对话应用的场景 | 已完成 | tongyi-langchain | https://registry.terraform.io/modules/alibabacloud-automation/tongyi-langchain/alicloud/latest |
| use-mse-to-implement-comprehensive-traffic-protection | 基于 MSE 微服务引擎实现全面流量防护,提供限流降级、熔断、服务发现和配置管理能力,适用于微服务架构下需要保障服务稳定性、防止流量洪峰打垮下游服务的场景 | 已完成 | mse-traffic-protection | https://registry.terraform.io/modules/alibabacloud-automation/mse-traffic-protection/alicloud/latest |
| mysql-rds | 使用 MySQL RDS 数据库部署 WordPress 的完整建站解决方案,自动化创建 VPC、ECS Web 服务器和 RDS MySQL 数据库并配置 WordPress,适用于中小企业和个人快速搭建网站或博客的场景 | 已完成 | mysql-rds-wordpress | https://registry.terraform.io/modules/alibabacloud-automation/mysql-rds-wordpress/alicloud/latest |
FILE:scripts/diagnose_cli_command.py
# -*- coding: utf-8 -*-
"""Diagnose an Alibaba Cloud CLI command error.
Usage:
python3 scripts/diagnose_cli_command.py <command> <error>
Example:
python3 scripts/diagnose_cli_command.py 'aliyun ecs DescribeInstances' 'InvalidAccessKeyId.NotFound'
"""
import sys
import json
from alibabacloud_tea_openapi.client import Client as OpenApiClient
from alibabacloud_credentials.client import Client as CredentialClient
from alibabacloud_tea_openapi import models as open_api_models
from alibabacloud_tea_util import models as util_models
def validate_input(value, name, max_length=2000):
"""Validate input value for length and non-empty."""
if not value or len(value) > max_length:
print(f"Error: {name} exceeds {max_length} chars or is empty", file=sys.stderr)
sys.exit(1)
def sanitize_response(obj):
"""Recursively sanitize sensitive fields in response object."""
sensitive_keys = {'accesskeyid', 'accesskeysecret', 'securitytoken', 'password', 'secret', 'accountid', 'credential'}
if isinstance(obj, dict):
sanitized = {}
for key, value in obj.items():
if key.lower() in sensitive_keys:
sanitized[key] = "***REDACTED***"
else:
sanitized[key] = sanitize_response(value)
return sanitized
elif isinstance(obj, list):
return [sanitize_response(item) for item in obj]
else:
return obj
def create_client() -> OpenApiClient:
credential = CredentialClient()
config = open_api_models.Config(credential=credential)
config.endpoint = 'openapi-mcp.cn-hangzhou.aliyuncs.com'
config.user_agent = 'AlibabaCloud-Agent-Skills'
return OpenApiClient(config)
def diagnose_cli(command: str, error: str) -> dict:
client = create_client()
params = open_api_models.Params(
action='DiagnoseCLI',
version='2024-11-30',
protocol='HTTPS',
method='POST',
auth_type='AK',
style='ROA',
pathname='/diagnoseCLI',
req_body_type='json',
body_type='json'
)
body = {'command': command, 'error': error}
runtime = util_models.RuntimeOptions(read_timeout=60000)
request = open_api_models.OpenApiRequest(body=body)
return client.call_api(params, request, runtime)
if __name__ == '__main__':
if len(sys.argv) < 3:
print("Usage: python3 scripts/diagnose_cli_command.py <command> <error>", file=sys.stderr)
sys.exit(1)
command = sys.argv[1]
error = sys.argv[2]
validate_input(command, 'command', max_length=2000)
validate_input(error, 'error', max_length=4000)
result = diagnose_cli(command, error)
sanitized = sanitize_response(result)
print(json.dumps(sanitized, ensure_ascii=False, indent=2))
FILE:scripts/lsit_api_overview.py
# -*- coding: utf-8 -*-
"""List API overviews for a given Alibaba Cloud product.
Usage:
python3 scripts/lsit_api_overview.py <product> <version> [filter]
Example:
python3 scripts/lsit_api_overview.py Ecs 2014-05-26
python3 scripts/lsit_api_overview.py Ecs 2014-05-26 '云助手'
"""
import sys
import json
import re
from alibabacloud_tea_openapi.client import Client as OpenApiClient
from alibabacloud_credentials.client import Client as CredentialClient
from alibabacloud_tea_openapi import models as open_api_models
from alibabacloud_tea_util import models as util_models
from alibabacloud_openapi_util.client import Client as OpenApiUtilClient
def validate_product(product):
"""Validate product matches ^[a-zA-Z][a-zA-Z0-9-]{0,49}$."""
if not re.match(r'^[a-zA-Z][a-zA-Z0-9-]{0,49}$', product):
print(f"Error: product must start with letter and contain only alphanumeric or hyphen, max 50 chars", file=sys.stderr)
sys.exit(1)
def validate_version(version):
r"""Validate version matches ^\d{4}-\d{2}-\d{2}$."""
if not re.match(r'^\d{4}-\d{2}-\d{2}$', version):
print(f"Error: version must be in YYYY-MM-DD format", file=sys.stderr)
sys.exit(1)
def validate_input(value, name, max_length=2000):
"""Validate input value for length and non-empty."""
if not value or len(value) > max_length:
print(f"Error: {name} exceeds {max_length} chars or is empty", file=sys.stderr)
sys.exit(1)
def sanitize_response(obj):
"""Recursively sanitize sensitive fields in response object."""
sensitive_keys = {'accesskeyid', 'accesskeysecret', 'securitytoken', 'password', 'secret', 'accountid', 'credential'}
if isinstance(obj, dict):
sanitized = {}
for key, value in obj.items():
if key.lower() in sensitive_keys:
sanitized[key] = "***REDACTED***"
else:
sanitized[key] = sanitize_response(value)
return sanitized
elif isinstance(obj, list):
return [sanitize_response(item) for item in obj]
else:
return obj
def create_client() -> OpenApiClient:
credential = CredentialClient()
config = open_api_models.Config(credential=credential)
config.endpoint = 'openapi-mcp.cn-hangzhou.aliyuncs.com'
config.user_agent = 'AlibabaCloud-Agent-Skills'
return OpenApiClient(config)
def list_api_overviews(product: str, version: str, filter_keyword: str = '') -> dict:
client = create_client()
params = open_api_models.Params(
action='ListApiOverviews',
version='2024-11-30',
protocol='HTTPS',
method='GET',
auth_type='AK',
style='ROA',
pathname='/listApiOverviews',
req_body_type='json',
body_type='json'
)
queries = {'product': product, 'version': version}
if filter_keyword:
queries['filter'] = filter_keyword
runtime = util_models.RuntimeOptions(read_timeout=30000)
request = open_api_models.OpenApiRequest(
query=OpenApiUtilClient.query(queries)
)
return client.call_api(params, request, runtime)
if __name__ == '__main__':
if len(sys.argv) < 3:
print("Usage: python3 scripts/lsit_api_overview.py <product> <version> [filter]", file=sys.stderr)
sys.exit(1)
product = sys.argv[1]
version = sys.argv[2]
filter_kw = sys.argv[3] if len(sys.argv) > 3 else ''
validate_product(product)
validate_version(version)
if filter_kw:
validate_input(filter_kw, 'filter', max_length=200)
result = list_api_overviews(product, version, filter_kw)
sanitized = sanitize_response(result)
print(json.dumps(sanitized, ensure_ascii=False, indent=2))
FILE:scripts/lsit_products.py
# -*- coding: utf-8 -*-
"""List Alibaba Cloud products by keyword filter.
Usage:
python3 scripts/lsit_products.py <filter_keyword>
Example:
python3 scripts/lsit_products.py '云网络'
python3 scripts/lsit_products.py 'ECS'
"""
import sys
import json
from alibabacloud_tea_openapi.client import Client as OpenApiClient
from alibabacloud_credentials.client import Client as CredentialClient
from alibabacloud_tea_openapi import models as open_api_models
from alibabacloud_tea_util import models as util_models
from alibabacloud_openapi_util.client import Client as OpenApiUtilClient
def validate_input(value, name, max_length=2000):
"""Validate input value for length and non-empty."""
if not value or len(value) > max_length:
print(f"Error: {name} exceeds {max_length} chars or is empty", file=sys.stderr)
sys.exit(1)
def sanitize_response(obj):
"""Recursively sanitize sensitive fields in response object."""
sensitive_keys = {'accesskeyid', 'accesskeysecret', 'securitytoken', 'password', 'secret', 'accountid', 'credential'}
if isinstance(obj, dict):
sanitized = {}
for key, value in obj.items():
if key.lower() in sensitive_keys:
sanitized[key] = "***REDACTED***"
else:
sanitized[key] = sanitize_response(value)
return sanitized
elif isinstance(obj, list):
return [sanitize_response(item) for item in obj]
else:
return obj
def create_client() -> OpenApiClient:
credential = CredentialClient()
config = open_api_models.Config(credential=credential)
config.endpoint = 'openapi-mcp.cn-hangzhou.aliyuncs.com'
config.user_agent = 'AlibabaCloud-Agent-Skills'
return OpenApiClient(config)
def list_products(filter_keyword: str) -> dict:
client = create_client()
params = open_api_models.Params(
action='ListProducts',
version='2024-11-30',
protocol='HTTPS',
method='GET',
auth_type='AK',
style='ROA',
pathname='/listProducts',
req_body_type='json',
body_type='json'
)
queries = {}
if filter_keyword:
queries['filter'] = filter_keyword
runtime = util_models.RuntimeOptions(read_timeout=30000)
request = open_api_models.OpenApiRequest(
query=OpenApiUtilClient.query(queries)
)
return client.call_api(params, request, runtime)
if __name__ == '__main__':
if len(sys.argv) < 2:
print("Usage: python3 scripts/lsit_products.py <filter_keyword>", file=sys.stderr)
sys.exit(1)
filter_keyword = sys.argv[1]
validate_input(filter_keyword, 'filter_keyword', max_length=200)
result = list_products(filter_keyword)
sanitized = sanitize_response(result)
print(json.dumps(sanitized, ensure_ascii=False, indent=2))
FILE:scripts/search_apis.py
# -*- coding: utf-8 -*-
"""Search Alibaba Cloud APIs by natural language prompt.
Usage:
python3 scripts/search_apis.py <prompt> [limit]
Example:
python3 scripts/search_apis.py '创建ECS实例'
python3 scripts/search_apis.py '创建ECS实例' 5
"""
import sys
import json
from alibabacloud_tea_openapi.client import Client as OpenApiClient
from alibabacloud_credentials.client import Client as CredentialClient
from alibabacloud_tea_openapi import models as open_api_models
from alibabacloud_tea_util import models as util_models
def validate_input(value, name, max_length=2000):
"""Validate input value for length and non-empty."""
if not value or len(value) > max_length:
print(f"Error: {name} exceeds {max_length} chars or is empty", file=sys.stderr)
sys.exit(1)
def validate_int_range(value, name, min_val, max_val):
"""Validate integer is within range."""
if value < min_val or value > max_val:
print(f"Error: {name} must be between {min_val} and {max_val}", file=sys.stderr)
sys.exit(1)
def sanitize_response(obj):
"""Recursively sanitize sensitive fields in response object."""
sensitive_keys = {'accesskeyid', 'accesskeysecret', 'securitytoken', 'password', 'secret', 'accountid', 'credential'}
if isinstance(obj, dict):
sanitized = {}
for key, value in obj.items():
if key.lower() in sensitive_keys:
sanitized[key] = "***REDACTED***"
else:
sanitized[key] = sanitize_response(value)
return sanitized
elif isinstance(obj, list):
return [sanitize_response(item) for item in obj]
else:
return obj
def create_client() -> OpenApiClient:
credential = CredentialClient()
config = open_api_models.Config(credential=credential)
config.endpoint = 'openapi-mcp.cn-hangzhou.aliyuncs.com'
config.user_agent = 'AlibabaCloud-Agent-Skills'
return OpenApiClient(config)
def search_apis(prompt: str, limit: int = 5) -> dict:
client = create_client()
params = open_api_models.Params(
action='SearchApis',
version='2024-11-30',
protocol='HTTPS',
method='POST',
auth_type='AK',
style='ROA',
pathname='/searchApis',
req_body_type='json',
body_type='json'
)
body = {'prompt': prompt, 'limit': limit}
runtime = util_models.RuntimeOptions(read_timeout=60000)
request = open_api_models.OpenApiRequest(body=body)
return client.call_api(params, request, runtime)
if __name__ == '__main__':
if len(sys.argv) < 2:
print("Usage: python3 scripts/search_apis.py <prompt> [limit]", file=sys.stderr)
sys.exit(1)
prompt = sys.argv[1]
limit = int(sys.argv[2]) if len(sys.argv) > 2 else 5
validate_input(prompt, 'prompt', max_length=2000)
validate_int_range(limit, 'limit', 1, 100)
result = search_apis(prompt, limit)
sanitized = sanitize_response(result)
print(json.dumps(sanitized, ensure_ascii=False, indent=2))
FILE:scripts/search_documents.py
# -*- coding: utf-8 -*-
"""Search Alibaba Cloud documents by keyword.
Usage:
python3 scripts/search_documents.py <query> [limit]
Example:
python3 scripts/search_documents.py 'ECS实例规格'
python3 scripts/search_documents.py 'VPC网络配置' 5
"""
import sys
import json
from alibabacloud_tea_openapi.client import Client as OpenApiClient
from alibabacloud_credentials.client import Client as CredentialClient
from alibabacloud_tea_openapi import models as open_api_models
from alibabacloud_tea_util import models as util_models
def validate_input(value, name, max_length=2000):
"""Validate input value for length and non-empty."""
if not value or len(value) > max_length:
print(f"Error: {name} exceeds {max_length} chars or is empty", file=sys.stderr)
sys.exit(1)
def validate_int_range(value, name, min_val, max_val):
"""Validate integer is within range."""
if value < min_val or value > max_val:
print(f"Error: {name} must be between {min_val} and {max_val}", file=sys.stderr)
sys.exit(1)
def sanitize_response(obj):
"""Recursively sanitize sensitive fields in response object."""
sensitive_keys = {'accesskeyid', 'accesskeysecret', 'securitytoken', 'password', 'secret', 'accountid', 'credential'}
if isinstance(obj, dict):
sanitized = {}
for key, value in obj.items():
if key.lower() in sensitive_keys:
sanitized[key] = "***REDACTED***"
else:
sanitized[key] = sanitize_response(value)
return sanitized
elif isinstance(obj, list):
return [sanitize_response(item) for item in obj]
else:
return obj
def create_client() -> OpenApiClient:
credential = CredentialClient()
config = open_api_models.Config(credential=credential)
config.endpoint = 'openapi-mcp.cn-hangzhou.aliyuncs.com'
config.user_agent = 'AlibabaCloud-Agent-Skills'
return OpenApiClient(config)
def search_documents(query: str, limit: int = 5) -> dict:
client = create_client()
params = open_api_models.Params(
action='SearchDocuments',
version='2024-11-30',
protocol='HTTPS',
method='POST',
auth_type='AK',
style='ROA',
pathname='/searchDocuments',
req_body_type='json',
body_type='json'
)
body = {'query': query, 'limit': limit}
runtime = util_models.RuntimeOptions(read_timeout=60000)
request = open_api_models.OpenApiRequest(body=body)
return client.call_api(params, request, runtime)
if __name__ == '__main__':
if len(sys.argv) < 2:
print("Usage: python3 scripts/search_documents.py <query> [limit]", file=sys.stderr)
sys.exit(1)
query = sys.argv[1]
limit = int(sys.argv[2]) if len(sys.argv) > 2 else 5
validate_input(query, 'query', max_length=2000)
validate_int_range(limit, 'limit', 1, 100)
result = search_documents(query, limit)
sanitized = sanitize_response(result)
print(json.dumps(sanitized, ensure_ascii=False, indent=2))
FILE:scripts/terraform_runtime_online.sh
#!/usr/bin/env bash
set -euo pipefail
# terraform_runtime_online.sh - Execute Terraform via Alibaba Cloud IaCService
#
# Usage:
# terraform_runtime_online.sh validate <hcl_file_or_code>
# terraform_runtime_online.sh plan <hcl_file_or_code> [existing_state_id]
# terraform_runtime_online.sh apply <hcl_file_or_code> # fresh apply (first time)
# terraform_runtime_online.sh apply <hcl_file_or_code> --state-id <id> # retry failed apply / update existing state
# terraform_runtime_online.sh apply --state-id <id> # apply a previously planned state
# terraform_runtime_online.sh destroy <state_id> [--force]
# terraform_runtime_online.sh poll <state_id> [max_attempts] [interval_seconds]
#
# ⚠️ STATE_ID REUSE RULE:
# - plan → apply: do NOT pass the plan stateId to apply (IaCService locks plan states)
# - Once a STATE_ID exists (from a previous apply), ALL subsequent changes to the same
# deployment MUST reuse it via --state-id, including:
# • Retrying after a failed/partial apply
# • Adding new resources to main.tf
# • Modifying existing resource configuration
# Only the very first apply of a brand-new deployment runs without --state-id.
# A fresh apply without --state-id creates a NEW state and causes duplicate resources.
ENDPOINT="iac.cn-zhangjiakou.aliyuncs.com"
SELF="$(cd "$(dirname "BASH_SOURCE[0]")" && pwd)/$(basename "BASH_SOURCE[0]")"
# ---------------------------------------------------------------------------
# Color helpers (degrade gracefully if tput unavailable)
# ---------------------------------------------------------------------------
_green() { command -v tput &>/dev/null && tput setaf 2; }
_red() { command -v tput &>/dev/null && tput setaf 1; }
_yellow() { command -v tput &>/dev/null && tput setaf 3; }
_reset() { command -v tput &>/dev/null && tput sgr0; }
# ---------------------------------------------------------------------------
# Shared helper: resolve file-or-inline input to CODE variable
# ---------------------------------------------------------------------------
_read_input() {
local input="$1"
if [[ -f "$input" ]]; then
cat "$input"
else
printf '%s' "$input"
fi
}
# ---------------------------------------------------------------------------
# cmd: validate
# ---------------------------------------------------------------------------
cmd_validate() {
if [[ $# -lt 1 || "-" == "--help" || "-" == "-h" ]]; then
echo "Usage: $0 validate <hcl_file_or_code>"
echo "Exit 0 = Validated, 1 = Errored"
exit 1
fi
local input="$1"
local code
code=$(_read_input "$input")
echo "Validating: $input" >&2
local token response status message
token="$(uuidgen)"
response=$(aliyun iacservice validate-module \
--endpoint "$ENDPOINT" \
--client-token "$token" \
--source Upload \
--code "$code" 2>&1) || { echo "$(_red)Error: validate-module failed$(_reset)" >&2; echo "$response" >&2; exit 1; }
status=$(echo "$response" | python3 -c "
import sys,json
try: print(json.load(sys.stdin).get('status','Unknown'))
except: print('Unknown')
" 2>/dev/null) || status="Unknown"
message=$(echo "$response" | python3 -c "
import sys,json
try: print(json.load(sys.stdin).get('message',''))
except: print('')
" 2>/dev/null) || message=""
echo "" >&2
if [[ "$status" == "Validated" ]]; then
echo "$(_green)Validated$(_reset)" >&2
[[ -n "$message" ]] && echo "$message" >&2
exit 0
else
echo "$(_red)Validation failed: $status$(_reset)" >&2
[[ -n "$message" ]] && echo "$message" >&2
exit 1
fi
}
# ---------------------------------------------------------------------------
# cmd: poll
# ---------------------------------------------------------------------------
cmd_poll() {
if [[ $# -lt 1 || "-" == "--help" || "-" == "-h" ]]; then
echo "Usage: $0 poll <state_id> [max_attempts] [interval_seconds]"
echo "Exit 0 = terminal state reached, 1 = timeout or Errored"
exit 1
fi
local state_id="$1"
local max="-60"
local interval="-10"
local terminal_states=("Planned" "PlannedAndFinished" "Applied" "Errored" "Canceled" "Discarded")
_is_terminal() {
local s="$1"
for t in "terminal_states[@]"; do [[ "$s" == "$t" ]] && return 0; done
return 1
}
local attempt=0 response status
while [[ $attempt -lt $max ]]; do
attempt=$((attempt + 1))
response=$(aliyun iacservice get-execute-state --endpoint "$ENDPOINT" --state-id "$state_id" 2>&1) || true
status=$(echo "$response" | python3 -c "
import sys,json
try: print(json.load(sys.stdin).get('status','Unknown'))
except: print('Unknown')
" 2>/dev/null) || status="Unknown"
if [[ "$status" == "Errored" ]]; then
echo "[$attempt/$max] $(_red)Status: $status$(_reset)" >&2
elif _is_terminal "$status"; then
echo "[$attempt/$max] $(_green)Status: $status$(_reset)" >&2
else
echo "[$attempt/$max] $(_yellow)Status: $status$(_reset)" >&2
fi
if _is_terminal "$status"; then
if [[ "$status" == "Errored" ]]; then
local errmsg
errmsg=$(echo "$response" | python3 -c "
import sys,json
try: print(json.load(sys.stdin).get('errorMessage','Unknown error'))
except: print('Unknown error')
" 2>/dev/null) || errmsg="Unknown error"
echo "$(_red)Error: $errmsg$(_reset)" >&2
exit 1
fi
exit 0
fi
[[ $attempt -lt $max ]] && sleep "$interval"
done
echo "$(_red)Timeout: $max attempts reached$(_reset)" >&2
exit 1
}
# ---------------------------------------------------------------------------
# cmd: plan
# ---------------------------------------------------------------------------
cmd_plan() {
if [[ $# -lt 1 || "-" == "--help" || "-" == "-h" ]]; then
echo "Usage: $0 plan <hcl_file_or_code> [existing_state_id]"
echo "Output: STATE_ID=<id> PLAN_OUTPUT_FILE=<path>"
echo "Exit 0 = Planned/PlannedAndFinished, 1 = Errored"
exit 1
fi
local input="$1"
local state_id="-"
local code token aliyun_cmd response new_state_id
code=$(_read_input "$input")
echo "Planning: $input" >&2
[[ -n "$state_id" ]] && echo "Using existing state: $state_id" >&2
token="$(uuidgen)"
aliyun_cmd="aliyun iacservice execute-terraform-plan --endpoint $ENDPOINT --client-token $token --code \"\$code\""
[[ -n "$state_id" ]] && aliyun_cmd="$aliyun_cmd --state-id $state_id"
response=$(eval "$aliyun_cmd" 2>&1) || { echo "$(_red)Error: execute-terraform-plan failed$(_reset)" >&2; echo "$response" >&2; exit 1; }
new_state_id=$(echo "$response" | python3 -c "
import sys,json
try: print(json.load(sys.stdin).get('stateId',''))
except: print('')
" 2>/dev/null) || new_state_id=""
[[ -z "$new_state_id" ]] && { echo "$(_red)Error: no stateId in response$(_reset)" >&2; echo "$response" >&2; exit 1; }
echo "STATE_ID=$new_state_id"
echo "" >&2; echo "Plan started. stateId: $new_state_id" >&2; echo "Polling..." >&2; echo "" >&2
"$SELF" poll "$new_state_id" || { echo "$(_red)Plan failed$(_reset)" >&2; exit 1; }
local final_response final_status error_message
final_response=$(aliyun iacservice get-execute-state --endpoint "$ENDPOINT" --state-id "$new_state_id" 2>&1) || true
final_status=$(echo "$final_response" | python3 -c "
import sys,json
try: print(json.load(sys.stdin).get('status','Unknown'))
except: print('Unknown')
" 2>/dev/null) || final_status="Unknown"
echo "" >&2
if [[ "$final_status" == "Planned" || "$final_status" == "PlannedAndFinished" ]]; then
echo "$(_green)Plan completed: $final_status$(_reset)" >&2
local plan_file="/tmp/tf_plan_new_state_id.txt"
local plan_summary
plan_summary=$(echo "$final_response" | python3 -c "
import sys,json,re
plan_file=sys.argv[1]
try:
data=json.loads(sys.stdin.read(),strict=False)
lf=data.get('logFile',{})
log=lf.get('tf-plan.run.log','') if isinstance(lf,dict) else (lf if isinstance(lf,str) else '')
if not log: print(' No plan details available'); sys.exit(0)
clean=re.sub(r'\x1b\[[0-9;]*[a-zA-Z]','',log)
open(plan_file,'w').write(clean)
lines=clean.split('\n')
summary=[l for l in lines if ('# ' in l and ('will be' in l or 'must be' in l)) or l.strip().startswith('Plan:') or 'No changes' in l]
for s in (summary or [' (see full output for details)']): print(' '+s.strip())
except Exception as e: print(f' Could not parse: {e}')
" "$plan_file" 2>/dev/null) || plan_summary=" Could not parse plan details"
echo "" >&2
echo "=== Plan Summary ===" >&2
echo "$plan_summary" >&2
[[ -f "$plan_file" ]] && { echo "" >&2; echo "Full output: cat $plan_file" >&2; }
echo "====================" >&2
echo "PLAN_OUTPUT_FILE=$plan_file"
exit 0
elif [[ "$final_status" == "Errored" ]]; then
error_message=$(echo "$final_response" | python3 -c "
import sys,json
try: m=json.load(sys.stdin).get('errorMessage',''); m and print(m)
except: pass
" 2>/dev/null) || error_message=""
echo "$(_red)Plan failed: $final_status$(_reset)" >&2
[[ -n "$error_message" ]] && echo "$(_red)Error: $error_message$(_reset)" >&2
exit 1
else
echo "$(_yellow)Plan status: $final_status$(_reset)" >&2
exit 0
fi
}
# ---------------------------------------------------------------------------
# cmd: apply
# ---------------------------------------------------------------------------
cmd_apply() {
if [[ $# -lt 1 || "-" == "--help" || "-" == "-h" ]]; then
echo "Usage:"
echo " $0 apply <hcl_file_or_code> # first apply of a brand-new deployment"
echo " $0 apply <hcl_file_or_code> --state-id <id> # any subsequent change to an existing deployment"
echo " $0 apply --state-id <id> # apply a previously planned state"
echo ""
echo " STATE_ID REUSE RULE:"
echo " Once a STATE_ID exists, ALL subsequent operations on the same deployment MUST"
echo " pass --state-id, including: retry after failure, add resources, modify config."
echo " Starting a fresh apply (without --state-id) creates a NEW state and causes"
echo " duplicate resource creation."
echo ""
echo "Output: STATE_ID=<id>"
echo "Exit 0 = Applied, 1 = Errored"
exit 1
fi
local input="" state_id="" code=""
while [[ $# -gt 0 ]]; do
case "$1" in
--state-id) state_id="-"; shift 2 ;;
--help|-h) cmd_apply --help ;;
*) input="$1"; shift ;;
esac
done
[[ -z "$input" && -z "$state_id" ]] && { echo "$(_red)Error: provide HCL code/file or --state-id$(_reset)" >&2; exit 1; }
[[ -n "$input" ]] && { code=$(_read_input "$input"); echo "Applying: $input" >&2; }
[[ -n "$state_id" ]] && echo "Using existing state: $state_id" >&2
local token aliyun_cmd response new_state_id
local max_retries=6 retry_delay=10 retry=0
token="$(uuidgen)"
_build_cmd() {
local cmd="aliyun iacservice execute-terraform-apply --endpoint $ENDPOINT --client-token $token"
[[ -n "$code" ]] && cmd="$cmd --code \"\$code\""
[[ -n "$state_id" ]] && cmd="$cmd --state-id $state_id"
echo "$cmd"
}
aliyun_cmd=$(_build_cmd)
while true; do
response=$(eval "$aliyun_cmd" 2>&1) && break
if echo "$response" | grep -q "InvalidOperation.TaskStatus"; then
retry=$((retry + 1))
if [[ $retry -ge $max_retries ]]; then
echo "$(_red)Error: state lock not released after $max_retries retries$(_reset)" >&2
echo "$response" >&2; exit 1
fi
echo "$(_yellow)[Retry $retry/$max_retries] State lock not released, waiting retry_delays...$(_reset)" >&2
sleep "$retry_delay"
token="$(uuidgen)"; aliyun_cmd=$(_build_cmd)
else
echo "$(_red)Error: execute-terraform-apply failed$(_reset)" >&2; echo "$response" >&2; exit 1
fi
done
new_state_id=$(echo "$response" | python3 -c "
import sys,json
try: print(json.load(sys.stdin).get('stateId',''))
except: print('')
" 2>/dev/null) || new_state_id=""
[[ -z "$new_state_id" ]] && { echo "$(_red)Error: no stateId in response$(_reset)" >&2; echo "$response" >&2; exit 1; }
echo "STATE_ID=$new_state_id"
echo "" >&2; echo "Apply started. stateId: $new_state_id" >&2; echo "Polling..." >&2; echo "" >&2
"$SELF" poll "$new_state_id" || { echo "$(_red)Apply failed$(_reset)" >&2; exit 1; }
local final_response final_status error_message
final_response=$(aliyun iacservice get-execute-state --endpoint "$ENDPOINT" --state-id "$new_state_id" 2>&1) || true
final_status=$(echo "$final_response" | python3 -c "
import sys,json
try: print(json.load(sys.stdin).get('status','Unknown'))
except: print('Unknown')
" 2>/dev/null) || final_status="Unknown"
echo "" >&2
if [[ "$final_status" == "Applied" ]]; then
echo "$(_green)Apply completed: $final_status$(_reset)" >&2
echo "" >&2; echo "Resources:" >&2
echo "$final_response" | python3 -c "
import sys,json
try:
data=json.load(sys.stdin)
s=data.get('state','')
state=json.loads(s) if isinstance(s,str) else s
resources=state.get('resources',[]) if state else []
if resources:
for r in resources:
for i in r.get('instances',[]):
print(f' {r[\"type\"]}.{r[\"name\"]}: {i.get(\"attributes\",{}).get(\"id\",\"N/A\")}')
else: print(' No resources found')
except Exception as e: print(f' Could not parse resources: {e}')
" 2>/dev/null || echo " Could not parse resources" >&2
exit 0
elif [[ "$final_status" == "Errored" ]]; then
error_message=$(echo "$final_response" | python3 -c "
import sys,json
try: m=json.load(sys.stdin).get('errorMessage',''); m and print(m)
except: pass
" 2>/dev/null) || error_message=""
echo "$(_red)Apply failed: $final_status$(_reset)" >&2
[[ -n "$error_message" ]] && echo "$(_red)Error: $error_message$(_reset)" >&2
exit 1
else
echo "$(_yellow)Apply status: $final_status$(_reset)" >&2; exit 0
fi
}
# ---------------------------------------------------------------------------
# cmd: destroy
# ---------------------------------------------------------------------------
cmd_destroy() {
if [[ $# -lt 1 || "-" == "--help" || "-" == "-h" ]]; then
echo "Usage: $0 destroy <state_id> [--force]"
echo "Exit 0 = Destroyed, 1 = Failed or not confirmed"
exit 1
fi
local state_id="" force=false
while [[ $# -gt 0 ]]; do
case "$1" in
--force) force=true; shift ;;
--help|-h) cmd_destroy --help ;;
*) state_id="$1"; shift ;;
esac
done
[[ -z "$state_id" ]] && { echo "$(_red)Error: state_id required$(_reset)" >&2; exit 1; }
# Pre-check: get current state and list resources
echo "Pre-check: querying state $state_id ..." >&2
local pre_response pre_status
pre_response=$(aliyun iacservice get-execute-state --endpoint "$ENDPOINT" --state-id "$state_id" 2>&1) || {
echo "$(_red)Error: cannot query state $state_id$(_reset)" >&2
echo "$pre_response" >&2; exit 1
}
pre_status=$(echo "$pre_response" | python3 -c "
import sys,json
try: print(json.load(sys.stdin).get('status','Unknown'))
except: print('Unknown')
" 2>/dev/null) || pre_status="Unknown"
echo "" >&2
echo "$(_yellow)⚠️ The following resources will be DESTROYED:$(_reset)" >&2
echo "$pre_response" | python3 -c "
import sys,json
try:
data=json.load(sys.stdin)
s=data.get('state','')
state=json.loads(s) if isinstance(s,str) else s
resources=state.get('resources',[]) if state else []
if resources:
for r in resources:
for i in r.get('instances',[]):
print(f' {r[\"type\"]}.{r[\"name\"]}: {i.get(\"attributes\",{}).get(\"id\",\"N/A\")}')
else: print(' (no resources found in state)')
except Exception as e: print(f' Could not parse resources: {e}')
" 2>/dev/null || echo " Could not parse resources" >&2
echo "" >&2
if [[ "$force" != true ]]; then
echo "$(_red)Destruction not confirmed. Add --force to proceed.$(_reset)" >&2
exit 1
fi
echo "Destroying resources for state: $state_id" >&2
local token response destroy_state_id
token="$(uuidgen)"
response=$(aliyun iacservice execute-terraform-destroy \
--endpoint "$ENDPOINT" \
--client-token "$token" \
--state-id "$state_id" 2>&1) || { echo "$(_red)Error: execute-terraform-destroy failed$(_reset)" >&2; echo "$response" >&2; exit 1; }
destroy_state_id=$(echo "$response" | python3 -c "
import sys,json
try:
sid=json.load(sys.stdin).get('stateId','')
print(sid if sid else '$state_id')
except: print('$state_id')
" 2>/dev/null) || destroy_state_id="$state_id"
echo "Polling..." >&2; echo "" >&2
"$SELF" poll "$destroy_state_id" || { echo "$(_red)Destroy failed$(_reset)" >&2; exit 1; }
local final_response final_status
final_response=$(aliyun iacservice get-execute-state --endpoint "$ENDPOINT" --state-id "$destroy_state_id" 2>&1) || true
final_status=$(echo "$final_response" | python3 -c "
import sys,json
try: print(json.load(sys.stdin).get('status','Unknown'))
except: print('Unknown')
" 2>/dev/null) || final_status="Unknown"
echo "" >&2
if [[ "$final_status" == "Applied" || "$final_status" == "Canceled" || "$final_status" == "Discarded" ]]; then
echo "$(_green)Destroy completed: $final_status$(_reset)" >&2; exit 0
elif [[ "$final_status" == "Errored" ]]; then
local errmsg
errmsg=$(echo "$final_response" | python3 -c "
import sys,json
try: m=json.load(sys.stdin).get('errorMessage',''); m and print(m)
except: pass
" 2>/dev/null) || errmsg=""
echo "$(_red)Destroy failed: $final_status$(_reset)" >&2
[[ -n "$errmsg" ]] && echo "$(_red)Error: $errmsg$(_reset)" >&2
exit 1
else
echo "$(_yellow)Destroy status: $final_status$(_reset)" >&2; exit 0
fi
}
# ---------------------------------------------------------------------------
# Dispatch
# ---------------------------------------------------------------------------
usage() {
echo "Usage: $0 <command> [args]"
echo ""
echo "Commands:"
echo " validate <hcl_file_or_code> Validate HCL syntax"
echo " plan <hcl_file_or_code> [state_id] Preview changes"
echo " apply <hcl_file_or_code> [--state-id id] Create/update infrastructure"
echo " apply --state-id <id> Apply planned state"
echo " destroy <state_id> [--force] Destroy resources"
echo " poll <state_id> [max] [interval] Poll execution status"
echo ""
echo "Run '$0 <command> --help' for per-command usage."
exit 1
}
COMMAND="-"
shift || true
case "$COMMAND" in
validate) cmd_validate "$@" ;;
plan) cmd_plan "$@" ;;
apply) cmd_apply "$@" ;;
destroy) cmd_destroy "$@" ;;
poll) cmd_poll "$@" ;;
*) usage ;;
esac
FILE:scripts/verify_env.sh
#!/bin/bash
# Alibaba Cloud CLI Environment Verification Script
# Usage: bash scripts/verify_env.sh
if [ -z "$BASH_VERSION" ]; then
echo "Please run this script with bash: bash $0"
exit 1
fi
TOTAL=0
PASSED=0
MISSING_ITEMS=()
check() {
local name="$1"
local result="$2"
local fix_hint="$3"
TOTAL=$((TOTAL + 1))
if [ "$result" = "0" ]; then
PASSED=$((PASSED + 1))
echo " ✅ PASS $name"
else
echo " ❌ FAIL $name"
if [ -n "$fix_hint" ]; then
MISSING_ITEMS+=("$fix_hint")
fi
fi
}
echo "========================================="
echo " Alibaba Cloud CLI Environment Check"
echo "========================================="
echo ""
# 1. Check aliyun CLI installed
echo "--- 1. Aliyun CLI ---"
if command -v aliyun &>/dev/null; then
CLI_VERSION=$(aliyun version 2>&1 | head -1)
echo " Version: $CLI_VERSION"
# Check version >= 3.3.0
MAJOR=$(echo "$CLI_VERSION" | grep -oE '[0-9]+\.[0-9]+\.[0-9]+' | head -1 | cut -d. -f1)
MINOR=$(echo "$CLI_VERSION" | grep -oE '[0-9]+\.[0-9]+\.[0-9]+' | head -1 | cut -d. -f2)
PATCH=$(echo "$CLI_VERSION" | grep -oE '[0-9]+\.[0-9]+\.[0-9]+' | head -1 | cut -d. -f3)
if [ -n "$MAJOR" ] && [ "$MAJOR" -ge 3 ] && [ "$MINOR" -ge 3 ]; then
check "Aliyun CLI >= 3.3.0" "0" ""
elif [ -n "$MAJOR" ] && [ "$MAJOR" -gt 3 ]; then
check "Aliyun CLI >= 3.3.0" "0" ""
else
check "Aliyun CLI >= 3.3.0" "1" "[CLI] Upgrade aliyun CLI to 3.3.0+: brew upgrade aliyun-cli (macOS) or download from https://aliyuncli.alicdn.com/"
fi
else
check "Aliyun CLI installed" "1" "[CLI] Install aliyun CLI: brew install aliyun-cli (macOS) or see https://help.aliyun.com/zh/cli/"
fi
echo ""
# 2. Check CLI credentials (via STS GetCallerIdentity)
echo "--- 2. CLI Credentials ---"
if command -v aliyun &>/dev/null; then
STS_OUTPUT=$(aliyun sts GetCallerIdentity 2>&1)
if echo "$STS_OUTPUT" | grep -q '"AccountId"'; then
ACCOUNT_ID=$(echo "$STS_OUTPUT" | python3 -c "import sys,json;print(json.load(sys.stdin)['AccountId'])" 2>/dev/null)
ARN=$(echo "$STS_OUTPUT" | python3 -c "import sys,json;print(json.load(sys.stdin)['Arn'])" 2>/dev/null)
MASKED_ACCOUNT="0:4****-4"
MASKED_ARN=$(echo "$ARN" | sed "s/$ACCOUNT_ID/MASKED_ACCOUNT/g")
echo " Account: $MASKED_ACCOUNT"
echo " Identity: $MASKED_ARN"
check "CLI credentials valid" "0" ""
else
echo " Error: $STS_OUTPUT"
check "CLI credentials valid" "1" "[Config] Run: aliyun configure set --mode AK --access-key-id <your-ak> --access-key-secret <your-sk> --region cn-hangzhou"
fi
else
check "CLI credentials" "1" "[CLI] Install aliyun CLI first"
fi
echo ""
# 3. Check auto-plugin-install
echo "--- 3. Auto Plugin Install ---"
if command -v aliyun &>/dev/null; then
CONFIG_JSON="$HOME/.aliyun/config.json"
if [ -f "$CONFIG_JSON" ]; then
AUTO_INSTALL=$(python3 -c "
import json
with open('$CONFIG_JSON') as f:
cfg = json.load(f)
# Check current profile
profiles = cfg.get('profiles', [])
current = cfg.get('current', 'default')
for p in profiles:
if p.get('name') == current:
print(str(p.get('auto_plugin_install', False)).lower())
break
else:
print('false')
" 2>/dev/null || echo "false")
if [ "$AUTO_INSTALL" = "true" ]; then
check "Auto plugin install enabled" "0" ""
else
check "Auto plugin install enabled" "1" "[Config] Run: aliyun configure set --auto-plugin-install true"
fi
else
check "Auto plugin install enabled" "1" "[Config] Run: aliyun configure set --auto-plugin-install true"
fi
else
check "Auto plugin install" "1" "[CLI] Install aliyun CLI first"
fi
echo ""
# 4. Check Python3 (needed for helper scripts)
echo "--- 4. Python3 (for helper scripts) ---"
if command -v python3 &>/dev/null; then
PY_VERSION=$(python3 --version 2>&1 || echo "unknown")
echo " Version: $PY_VERSION"
check "Python3 available" "0" ""
else
check "Python3 available" "1" "[Python3] Install Python 3.8+: https://www.python.org/downloads/"
fi
echo ""
# 5. Check Python SDK (needed for helper scripts only)
echo "--- 5. Python SDK (for helper scripts) ---"
if command -v python3 &>/dev/null; then
SDK_PACKAGES=(
"alibabacloud_tea_openapi"
"alibabacloud_credentials"
"alibabacloud_tea_util"
"alibabacloud_openapi_util"
)
MISSING_SDK=()
for pkg in "SDK_PACKAGES[@]"; do
if ! python3 -c "import $pkg" &>/dev/null; then
MISSING_SDK+=("$pkg")
fi
done
if [ #MISSING_SDK[@] -eq 0 ]; then
check "SDK packages for helper scripts" "0" ""
else
check "SDK packages for helper scripts (missing: MISSING_SDK[*])" "1" "[SDK] Run: pip3 install alibabacloud-tea-openapi alibabacloud-credentials alibabacloud-tea-util alibabacloud-openapi-util"
fi
else
check "SDK packages check" "1" "[Python3] Install Python 3.8+ first"
fi
echo ""
echo "========================================="
echo " Result: $PASSED/$TOTAL passed"
echo "========================================="
if [ "$PASSED" -eq "$TOTAL" ]; then
echo " ✅ All CLI environment checks passed!"
exit 0
else
echo ""
IFS=$'\n' UNIQUE_MISSING=($(sort -u <<<"MISSING_ITEMS[*]")); unset IFS
echo " ❌ $((TOTAL - PASSED)) item(s) failed. How to fix:"
echo ""
for item in "UNIQUE_MISSING[@]"; do
echo " $item"
done
echo ""
exit 1
fi
Alibaba Cloud RAM permission diagnosis and repair assistant. When an agent encounters any permission-related error while operating Alibaba Cloud resources (4...
---
name: alibabacloud-ram-permission-diagnose
description: >
Alibaba Cloud RAM permission diagnosis and repair assistant. When an agent encounters
any permission-related error while operating Alibaba Cloud resources (403, NoPermission,
Forbidden, AccessDenied, InvalidSecurityToken, etc.), or when the user describes an
Alibaba Cloud RAM permission issue, use this skill immediately. Do not wait for the user
to explicitly request it — proactively start the diagnostic process whenever a permission
error appears. Also applies when: a developer encounters permission issues while writing
Alibaba Cloud SDK code, the user asks how to configure minimum permissions for an operation,
or the user wants to know which permissions the current identity is missing.
compatibility:
tools:
- Bash # for executing aliyun CLI commands (aliyun RAM series commands)
---
# RAM Permission Diagnosis and Repair
## Installation
**Pre-check: Aliyun CLI >= 3.3.3 required**
> Run `aliyun version` to verify >= 3.3.3. If not installed or version too low,
> run `curl -fsSL https://aliyuncli.alicdn.com/setup.sh | bash` to update,
> or see `references/cli-installation-guide.md` for installation instructions.
**Pre-check: Aliyun CLI plugin update required**
> [MUST] run `aliyun configure set --auto-plugin-install true` to enable automatic plugin installation.
> [MUST] run `aliyun plugin update` to ensure that any existing plugins are always up-to-date.
At the **start** of the Core Workflow (before any CLI invocation):
**[MUST] Enable AI-Mode** — AI-mode is required for Agent Skill execution.
Run the following commands before any CLI invocation:
```bash
aliyun configure ai-mode enable
aliyun configure ai-mode set-user-agent --user-agent "AlibabaCloud-Agent-Skills/alibabacloud-ram-permission-diagnose"
```
**[MUST] Disable AI-Mode at EVERY exit point** — Before delivering the final response for ANY reason, always disable AI-mode first. This applies to ALL exit paths: workflow success, workflow failure, error/exception, user cancellation, session end, or any other scenario where no further CLI commands will be executed.
AI-mode is only used for Agent Skill invocation scenarios and MUST NOT remain enabled after the skill stops running.
```bash
aliyun configure ai-mode disable
```
**[MUST] CLI User-Agent** — Every `aliyun` CLI command invocation must include:
`--user-agent AlibabaCloud-Agent-Skills/alibabacloud-ram-permission-diagnose`
> **Execution constraint**: When executing `aliyun` CLI commands directly (not generating commands for the user to copy), always append `--user-agent AlibabaCloud-Agent-Skills/alibabacloud-ram-permission-diagnose`. Do not add this flag to commands shown to users in Path B output or Path C console guidance.
## Overview
When a RAM permission error is detected, run through these steps:
1. **Quick Analysis** — parse raw error fields (no tool calls), output a brief summary, ask the user to choose analysis depth
2. **Deep Analysis** — *(only if user selects path B)* decode if needed, run gap analysis, classify root cause
3. **Generate Recommendations** — least-privilege authorization plan
4. **Execute Repair** — present repair options and wait for user to choose
**Permission level (L0–L3)** is the agent's internal routing state, inferred implicitly from API call results during the flow. It determines diagnostic depth and available repair paths. Never declare or describe the level to the user. See `references/diagnose-flow.md` for level definitions.
---
## Step 1: Quick Analysis
Parse raw error fields without any tool calls, then let the user decide how deep to go.
### 1a. Extract from raw error
- `error_code`: e.g., `NoPermission`, `Forbidden`, `InvalidSecurityToken`
- `missing_action`: e.g., `ecs:StopInstance`
- `principal_type`: `SubUser` / `AssumedRoleUser` / `RootUser` (from `AuthPrincipalType`)
- `principal_display_name`: UserId or role:session (from `AuthPrincipalDisplayName`)
- `no_permission_type`: `ImplicitDeny` or `ExplicitDeny` (from `NoPermissionType`)
- `policy_type`: e.g., `AccountLevelIdentityBasedPolicy`, `AssumeRolePolicy` (from `PolicyType`)
- `encoded_message`: retain `EncodedDiagnosticMessage` if present, for use in Step 2 if needed
### 1b. Output brief summary
Based on the extracted fields, output a concise summary: who is affected, what action is missing, initial root cause inference.
### 1c. Present depth choice and wait for selection
Present the following and **wait for the user to select — do not proceed until a choice is made**:
- **A. Quick path** *(recommended when: ImplicitDeny + all key fields present + common service)* — skip Step 2, generate recommendations directly from raw fields and built-in knowledge
- **B. Deep path** *(recommended when: ExplicitDeny, missing fields, or unfamiliar service)* — run full Step 2 analysis for a more precise result.
> Requires two optional permissions: `ram:DecodeDiagnosticMessage` (decode encoded errors) and system policy `AliyunRAMReadOnlyAccess` (gap analysis). Missing permissions limit specific capabilities but the flow continues.
- **Skip** — stop here; output manual troubleshooting links
Mark the recommended option clearly and briefly explain why.
**If user selects A**: proceed to Step 3. Note in the recommendation that it is based on quick analysis; the user can request deep analysis at any time.
**If user selects B**: proceed to Step 2.
**If user selects Skip**: output error summary, links to RAM documentation (`https://help.aliyun.com/document_detail/93733.html`) and RAM console (`https://ram.console.aliyun.com/policies`), and a note on how to restart diagnosis.
**Edge case — ExplicitDeny with path A forced**: if `NoPermissionType = ExplicitDeny` and the user still selects A, explain that the specific Deny policy cannot be identified without deep analysis, and provide a limited recommendation with explicit uncertainty noted.
---
## Step 2: Deep Analysis
*Entered only when the user selects path B in Step 1.*
First attempt classification using the raw fields from Step 1. `DecodeDiagnosticMessage` is a supplement — invoke it only when raw data is insufficient to classify with confidence.
**Decode when raw data alone cannot resolve the root cause**: e.g., `ExplicitDeny` is present (need `MatchedPolicies`), `AccessDeniedDetail` was absent, or `PolicyType` is missing. For cases where `NoPermissionType`, `AuthAction`, `AuthPrincipalType`, and `PolicyType` are all available and point to a clear root cause, skip decode and proceed directly.
Transcribe `EncodedDiagnosticMessage` from the raw error and call:
```bash
aliyun ram decode-diagnostic-message --encoded-diagnostic-message "<transcribed-value>"
```
If the call returns `EntityNotExist`, re-run the original failing command and save its output to a temp file (use the system temp dir; name the file after the command context, e.g. `/tmp/aliyun_ecs_stopinstance.txt`). Extract `EncodedDiagnosticMessage` from the file and retry the decode. If the field is not found in the file, mark as L0 and continue.
If `SubUser` identity needs UserName resolution before gap analysis, see `references/diagnose-flow.md` → Identity Resolution. If resolution fails, mark as L0 and continue.
Root cause categories:
- **MissingAction** — identity policy lacks the required Action (most common)
- **ExplicitDeny** — a Deny statement blocks access (may be identity policy or CP control policy)
- **TrustPolicy** — role trust policy does not allow the caller to assume the role
- **STSInsufficient** — STS temporary credential lacks permission; root cause is on the originating Role
- **TokenExpired** — STS token has expired
- **SLRMissing** — service-linked role has not been created
- **ResourcePolicy** — resource-side policy (e.g., OSS Bucket Policy) is restricting access
For gap analysis trigger rules and per-root-cause handling details, see `references/diagnose-flow.md`.
**Gap analysis** (when triggered): query current policies attached to the identity, then compare against the required Action. Use `ListPoliciesForUser` (SubUser), `ListPoliciesForRole` (AssumedRoleUser), or `ListControlPolicies` (RootUser). For Custom policies, fetch the policy document with `GetPolicyVersion`. System policies: use built-in knowledge, do not call `GetPolicyVersion`.
**When permissions are insufficient**: if `DecodeDiagnosticMessage` fails (L0) or policy queries fail (L1), inform the user of the limitation and provide ready-to-use permission request materials for a RAM admin — two independent options: ① decode permission (`ram:DecodeDiagnosticMessage`) as a custom policy; ② RAM read access via system policy `AliyunRAMReadOnlyAccess` (covers gap analysis). Either or both can be requested independently. Then continue to Step 3 without waiting.
---
## Step 3: Generate Recommendations
Before generating, check for caller skill permission hints (see `references/diagnose-flow.md` → Coverage Check).
Knowledge source priority:
1. **Built-in knowledge** — for popular services (ECS, OSS, RDS, FC, SLB, VPC, SLS, STS, etc.), use known Action semantics directly. Reference `references/hot-services-ram.md`.
2. **Caller skill hints** — if `ram-policies.md` was found, use as supplementary context
3. **Web search** — search `{product} RAM authorization site:help.aliyun.com`; prefer manually maintained docs with business examples over auto-generated Action tables
4. **System policy fallback** — recommend `AliyunXxxReadOnlyAccess` or `AliyunXxxFullAccess` with a note to tighten further
**Custom policy naming**: suggest a name based on service and task semantics (e.g., `ai-agent-ecs-permissions`), confirm once, reuse in the same session.
**System policy**: attach directly with a single command, no naming needed.
For the Trust Policy root cause path, recommendations differ — see `references/diagnose-flow.md` → Handling Each Root Cause.
After presenting the recommendation, add a brief note: the current plan is a starting point; the user can request further refinement at any time — for example, scoping down to specific resources, adding conditions, or using resource-level policies (such as OSS bucket policies) instead of identity-level grants.
---
## Step 4: Execute Repair
Before executing any write operation, present the change summary and all available paths to the user, then **wait for the user to select a path — do not proceed or output any commands until the user has chosen**:
- Target (user or role name)
- Change summary (policy name, action, undo method)
- Path options (always present all that are available for the current level — never skip any):
- **A. Direct CLI execution** — agent runs commands now *(only at L2)*
- **B. Output CLI commands** — user copies and runs in their own terminal *(all levels)*
- **C. Console guidance** — step-by-step in RAM console *(all levels)*
- **Skip** — do not execute
For pre-query requirements before write operations, and full CLI command examples, see `references/ram-cli-commands.md` and `references/diagnose-flow.md`.
**Path A**: agent executes via Bash. On success → L3 confirmed; report result and undo command. On NoPermission → switch to Path B automatically.
**Path B at L0/L1**: output incremental Statement JSON only, with a note that existing policies could not be read and the user must merge manually.
**Path B at L2**: offer two sub-options: ① incremental Statement only, ② complete merged policy JSON.
**Path C**: provide the RAM console entry (`https://ram.console.aliyun.com/policies`) and step-by-step instructions for completing the change in the console UI.
After repair, suggest the user retry the previously failed operation. Offer to retry on their behalf if requested.
FILE:references/diagnose-flow.md
# Diagnose Flow Reference
Detailed decision logic for RAM permission diagnosis. Consult this file when encountering complex or ambiguous scenarios.
---
## Identity Resolution
`AuthPrincipalType` and `AuthPrincipalDisplayName` are available in the raw error's `AccessDeniedDetail` — no decode needed. Resolve UserName before gap analysis when identity type is `SubUser`:
| `AuthPrincipalType` | `AuthPrincipalDisplayName` format | Resolution |
|---------------------|----------------------------------|------------|
| `SubUser` | Numeric UserId (e.g., `206007273725819551`) | Call `aliyun ims get-user --user-id <DisplayName>`, use returned `User.UserName` |
| `AssumedRoleUser` | `roleName:sessionName` (e.g., `my-role:session-1`) | Take the part before the colon as RoleName — no API needed |
| `RootUser` | Primary account identifier | Use directly — no resolution needed |
If `GetUser` fails (insufficient permission): mark as L0, fall back to raw error text.
---
## Permission Level (L0–L3)
Levels are implicit routing state — never declare or describe them to the user.
| Level | Confirmed When | Effect |
|-------|---------------|--------|
| L0 | `DecodeDiagnosticMessage` returns NoPermission | Root cause from raw text only; repair: Path B (incremental) + Path C |
| L1 | Decode succeeds, but policy query returns NoPermission | Skip gap analysis; repair: Path B (incremental) + Path C |
| L2 | Policy query returns results | Full gap analysis; repair: Path A (tentative) + Path B (with merge) + Path C |
| L3 | Write operation succeeds | Repair done; report result and undo command |
**Insufficient permission criteria**: ErrorCode `NoPermission`, `Forbidden`, or `AccessDenied`.
If user reports they have updated their own permissions: re-run Step 2 policy query to refresh level state.
---
## Root Cause Classification Decision Tree
```
ExplicitDeny = true?
├─ Yes → Explicit Deny path
│ NoPermissionPolicyType = ControlPolicy?
│ ├─ Yes → Root cause: CP control policy (out of scope, guide to manual)
│ ├─ No (AccountLevelIdentityBasedPolicy) → Root cause: own policy Deny (fixable)
│ └─ Unknown (field absent) → Query both ListPoliciesForUser + ListControlPolicies
│
└─ No (or no decoded info) → Missing Action path
├─ PolicyType = AssumeRolePolicy → Root cause: role trust policy not allowing caller
├─ MissingAction = sts:AssumeRole, PolicyType absent
│ → Medium confidence: trust policy OR identity policy missing sts:AssumeRole
│ Describe both; guide user to verify before choosing repair direction
├─ PrincipalARN contains AssumedRole/STS token → Root cause: STS credential insufficient
├─ ErrorCode = InvalidSecurityToken → Root cause: STS token expired
├─ Message contains ServiceLinkedRole → Root cause: SLR missing
├─ Error from OSS Bucket Policy etc. → Root cause: resource-side policy
└─ Other → Root cause: missing Action (most common)
```
**Key principle**: When `DecodeDiagnosticMessage` succeeds and `NoPermissionPolicyType` has a clear value, treat it as authoritative. Do not append additional verification API calls to check other possible root causes.
---
## Gap Analysis Trigger Rules
| Root Cause | Trigger Gap Analysis | Notes |
|-----------|---------------------|-------|
| Missing Action | ✅ Must query | Query by identity type (see below) |
| Explicit Deny (NoPermissionPolicyType=AccountLevelIdentityBasedPolicy) | ✅ Query | Locate the Deny statement |
| Explicit Deny (NoPermissionPolicyType unknown) | ✅ Query + `ListControlPolicies` | Both policy and CP layer |
| Explicit Deny (NoPermissionPolicyType=ControlPolicy) | ❌ Skip | CP level, guide to manual |
| Trust Policy path | ✅ `GetRole` only | Get target role trust policy |
| SLR missing / resource-side policy / token expired | ❌ Skip | Direct output only |
**Identity type → Query API** (for root causes that trigger gap analysis):
| Identity Type | `AuthPrincipalType` | Query API |
|--------------|---------------------|-----------|
| RAM user | `SubUser` | `ListPoliciesForUser` (UserName from Step 1) + `GetPolicyVersion` (Custom only) |
| RAM role | `AssumedRoleUser` | `ListPoliciesForRole` (RoleName from DisplayName) + `GetPolicyVersion` (Custom only) |
| Primary account | `RootUser` | `ListControlPolicies` directly |
**System policies**: Use built-in knowledge to infer coverage — do not call `GetPolicyVersion`.
---
## Repair Pre-Query Rules
| Repair Type | Pre-query Required | Notes |
|-------------|-------------------|-------|
| Attach system policy | None | Pure write |
| Create new custom policy | None | Agent generates content |
| Append Action to existing custom policy | `GetPolicyVersion` + `ListPolicyVersions` | Must include all existing + new Actions in new version |
| Modify role Trust Policy | `GetRole` | Can reuse Step 2 result if already fetched |
| Create SLR | None | Pure write |
---
## Coverage Check (for caller skill permission hints)
Before generating recommendations in Step 3:
1. Scan conversation context for the most recent `Base directory: <path>` injected by a skill invocation
2. If found, try reading `<path>/references/ram-policies.md`
3. If either file is read, perform a **Coverage Check**:
- Does the actual missing Action from the error appear covered? (exact match, wildcard, or reasonably implied)
- **If clearly NOT covered**: include the missing Action in the primary recommendation; add note: "⚠ The Action `{missing_action}` triggered by this error is not declared in the skill's permission hints file and has been automatically added. Consider notifying the skill maintainer to update `references/ram-policies.md`."
- **Otherwise**: use file as supplementary context, normal flow continues
4. If no file found: skip silently, no impact on flow
---
## Handling Each Root Cause
**Missing Action / own policy Deny**: Proceed to Step 3 recommendations → Step 4 repair.
**Role trust policy not allowing caller** (PolicyType=AssumeRolePolicy or medium-confidence sts:AssumeRole):
- Explain: trust policy of the target role must be updated to add the caller's ARN to Principal
- If role name is known: provide modification command directly (see `references/ram-cli-commands.md` → Trust Policy section)
- If unknown: provide `aliyun ram list-roles` and a template for the user to fill in
- Also note: caller's identity policy must also have `sts:AssumeRole` (see `AliyunSTSAssumeRoleAccess`)
- For medium-confidence: describe both possible root causes and guide user to verify first
**STS credential insufficient**:
- Explain: using STS temporary credential; missing permission must be added to the Role that generated the STS
- Provide Role name (from PrincipalARN) and suggested actions; do not auto-repair
**STS token expired**: Prompt user to re-obtain STS token; provide renewal command.
**SLR missing**: Provide creation command:
```bash
aliyun resourcemanager create-service-linked-role --service-name <service>.aliyuncs.com
```
**CP control policy**: Beyond single-account RAM scope; contact ResourceDirectory administrator.
**Resource-side policy (OSS Bucket Policy etc.)**: Explain distinction; provide resource-side modification guidance; do not follow RAM repair flow.
FILE:references/error-codes.md
# Alibaba Cloud RAM Permission ErrorCode Reference
## Insufficient Permission (requires authorization repair)
| ErrorCode | Description | Typical Scenario |
|-----------|-------------|-----------------|
| `NoPermission` | The current identity does not have permission to perform this operation | Most common — RAM user/role missing the required Action |
| `Forbidden` | Operation denied | Some services use this code instead of NoPermission |
| `AccessDenied` | Access denied | Commonly used by OSS, STS, and other services |
| `Forbidden.RAM` | Denied by RAM policy | Contains information related to RAM sub-accounts |
| `Forbidden.NotSupportRAM` | This operation does not support RAM sub-accounts | Requires primary account operation or special authorization |
## STS / Token Issues (requires renewal or reconfiguration)
| ErrorCode | Description | How to Handle |
|-----------|-------------|---------------|
| `InvalidSecurityToken.Expired` | STS Token has expired | Re-run AssumeRole to obtain a new token |
| `InvalidSecurityToken.MismatchWithAccessKey` | Token does not match the AK | Verify that AK/SK/Token all come from the same AssumeRole call |
| `InvalidSecurityToken` | Token is invalid | Check token format and validity |
| `SecurityTokenExpired` | Security token expired (used by some services) | Same as above — re-obtain token |
## Service-Linked Role Issues (requires creating an SLR)
| ErrorCode | Description | How to Handle |
|-----------|-------------|---------------|
| `ServiceRoleNotFound` | Service-linked role does not exist | Create the SLR for the corresponding service |
| `ServiceLinkedRoleNotExist` | Same as above (used by some services) | Create the SLR for the corresponding service |
## Permission Level Probing Reference
The following ErrorCodes indicate **the identity has permission but the parameter or resource has an issue** — they do not indicate insufficient permission. Encountering these codes during probing means the permission exists at that level:
- `InvalidParameter`, `MissingParameter`
- `EntityNotExist`, `EntityNotExists`
- `NotFound`, `ResourceNotFound`
- `InvalidInput`
The following ErrorCodes explicitly indicate **insufficient permission** — stop probing and record the level upon encountering them:
- `NoPermission`, `Forbidden`, `AccessDenied`
- `Forbidden.RAM`, `Forbidden.NotSupportRAM`
FILE:references/hot-services-ram.md
# Popular Services RAM Action Reference
> Used for Step 3 built-in knowledge priority. The following Actions are grouped by common task scenarios and can be used directly to generate minimum-privilege policies.
## ECS (Elastic Compute Service)
### Common Action Groups
| Scenario | Required Actions | Resource Pattern |
|----------|-----------------|-----------------|
| List / describe instances | `ecs:DescribeInstances`, `ecs:DescribeInstanceStatus` | `acs:ecs:*:*:instance/*` |
| Start / stop instances | `ecs:StartInstance`, `ecs:StopInstance`, `ecs:RebootInstance` | `acs:ecs:*:*:instance/*` |
| Create instances | `ecs:RunInstances`, `ecs:DescribeImages`, `ecs:DescribeSecurityGroups` | `acs:ecs:*:*:*` |
| Change instance type | `ecs:ModifyInstanceSpec`, `ecs:DescribeResourcesModification` | `acs:ecs:*:*:instance/*` |
| Disk snapshots | `ecs:CreateSnapshot`, `ecs:DescribeSnapshots`, `ecs:DescribeDisks` | `acs:ecs:*:*:disk/*` |
| Security group management | `ecs:DescribeSecurityGroups`, `ecs:AuthorizeSecurityGroup`, `ecs:RevokeSecurityGroup` | `acs:ecs:*:*:securitygroup/*` |
### Recommended System Policies
- Read-only operations: `AliyunECSReadOnlyAccess`
- Operational access (no create/delete): `AliyunECSOperatorAccess`
- Full control: `AliyunECSFullAccess`
---
## OSS (Object Storage Service)
### Common Action Groups
| Scenario | Required Actions | Resource Pattern |
|----------|-----------------|-----------------|
| Read objects | `oss:GetObject`, `oss:HeadObject` | `acs:oss:*:*:<bucket-name>/*` |
| Upload objects | `oss:PutObject`, `oss:InitiateMultipartUpload`, `oss:UploadPart` | `acs:oss:*:*:<bucket-name>/*` |
| Delete objects | `oss:DeleteObject` | `acs:oss:*:*:<bucket-name>/*` |
| List objects | `oss:ListObjects`, `oss:ListBuckets` | `acs:oss:*:*:<bucket-name>` |
| Bucket management | `oss:CreateBucket`, `oss:DeleteBucket`, `oss:GetBucketInfo` | `acs:oss:*:*:*` |
### Recommended System Policies
- Read-only: `AliyunOSSReadOnlyAccess`
- Full control: `AliyunOSSFullAccess`
---
## RDS (Relational Database Service)
### Common Action Groups
| Scenario | Required Actions | Resource Pattern |
|----------|-----------------|-----------------|
| Query instances / databases | `rds:DescribeDBInstances`, `rds:DescribeDBInstanceAttribute` | `acs:rds:*:*:dbinstance/*` |
| Create database accounts | `rds:CreateAccount`, `rds:DescribeAccounts` | `acs:rds:*:*:dbinstance/*` |
| Backup management | `rds:CreateBackup`, `rds:DescribeBackups` | `acs:rds:*:*:dbinstance/*` |
| Change instance type | `rds:ModifyDBInstanceSpec` | `acs:rds:*:*:dbinstance/*` |
| Whitelist management | `rds:ModifySecurityIps`, `rds:DescribeDBInstanceIPArrayList` | `acs:rds:*:*:dbinstance/*` |
### Recommended System Policies
- Read-only: `AliyunRDSReadOnlyAccess`
- Full control: `AliyunRDSFullAccess`
---
## FC (Function Compute)
### Common Action Groups
| Scenario | Required Actions | Resource Pattern |
|----------|-----------------|-----------------|
| Invoke functions | `fc:InvokeFunction` | `acs:fc:*:*:services/*/functions/*` |
| Query functions | `fc:GetFunction`, `fc:ListFunctions`, `fc:GetService` | `acs:fc:*:*:services/*` |
| Deploy functions | `fc:CreateFunction`, `fc:UpdateFunction`, `fc:CreateService` | `acs:fc:*:*:*` |
| Trigger management | `fc:CreateTrigger`, `fc:UpdateTrigger`, `fc:ListTriggers` | `acs:fc:*:*:services/*/functions/*/triggers/*` |
### Recommended System Policies
- Read-only: `AliyunFCReadOnlyAccess`
- Full control: `AliyunFCFullAccess`
---
## SLB (Server Load Balancer)
### Common Action Groups
| Scenario | Required Actions | Resource Pattern |
|----------|-----------------|-----------------|
| Query instances | `slb:DescribeLoadBalancers`, `slb:DescribeLoadBalancerAttribute` | `acs:slb:*:*:loadbalancer/*` |
| Listener management | `slb:CreateLoadBalancerHTTPListener`, `slb:StartLoadBalancerListener` | `acs:slb:*:*:loadbalancer/*` |
| Backend servers | `slb:AddBackendServers`, `slb:RemoveBackendServers` | `acs:slb:*:*:loadbalancer/*` |
### Recommended System Policies
- Read-only: `AliyunSLBReadOnlyAccess`
- Full control: `AliyunSLBFullAccess`
---
## VPC (Virtual Private Cloud)
### Common Action Groups
| Scenario | Required Actions | Resource Pattern |
|----------|-----------------|-----------------|
| Query VPCs / VSwitches | `vpc:DescribeVpcs`, `vpc:DescribeVSwitches` | `acs:vpc:*:*:vpc/*` |
| Security groups / routing | `vpc:DescribeRouteTables`, `vpc:DescribeRouteEntryList` | `acs:vpc:*:*:routetable/*` |
| EIP management | `vpc:AllocateEipAddress`, `vpc:AssociateEipAddress`, `vpc:DescribeEipAddresses` | `acs:vpc:*:*:eip/*` |
### Recommended System Policies
- Read-only: `AliyunVPCReadOnlyAccess`
- Full control: `AliyunVPCFullAccess`
---
## SLS (Log Service)
### Common Action Groups
| Scenario | Required Actions | Resource Pattern |
|----------|-----------------|-----------------|
| Query logs | `log:GetLogStore`, `log:GetLogs`, `log:ListLogStores` | `acs:log:*:*:project/*` |
| Write logs | `log:PostLogStoreLogs` | `acs:log:*:*:project/*/logstore/*` |
| Project management | `log:CreateProject`, `log:ListProject` | `acs:log:*:*:*` |
### Recommended System Policies
- Read-only: `AliyunLogReadOnlyAccess`
- Full control: `AliyunLogFullAccess`
FILE:references/ram-cli-commands.md
# RAM-Related aliyun CLI Command Reference
> All commands are executed via the `aliyun` CLI. Credentials must be configured in advance (`aliyun configure`).
## Diagnostic Commands
### Decode Encrypted Diagnostic Message
Transcribe `EncodedDiagnosticMessage` from the error output and call directly:
```bash
aliyun ram decode-diagnostic-message --encoded-diagnostic-message "<transcribed-value>"
```
If `EntityNotExist` is returned (transcription error), re-run the original failing command to a temp file and extract the token:
```bash
aliyun <product> <operation> [params] > /tmp/<context>.txt 2>&1
aliyun ram decode-diagnostic-message \
--encoded-diagnostic-message "$(grep -o 'EncodedDiagnosticMessage:[^ ]*' /tmp/<context>.txt | cut -d: -f2)"
```
### Query Current Identity
```bash
aliyun ram get-user
```
### Resolve User Identity (UserId → UserName)
When `DecodeDiagnosticMessage` returns `AuthPrincipalType = SubUser`, the `AuthPrincipalDisplayName` is a numeric UserId that cannot be used directly in RAM APIs. Use the following command to resolve the UserName:
```bash
aliyun ims get-user --user-id <UserId>
# Use User.UserName from the response for subsequent RAM operations
```
### List Policies Attached to a User
```bash
aliyun ram list-policies-for-user --user-name <username>
```
### List Policies Attached to a Role
```bash
aliyun ram list-policies-for-role --role-name <rolename>
```
### Read Policy Content (get current version document)
```bash
# First get the policy default version
aliyun ram get-policy --policy-name <policy-name> --policy-type Custom
# Read the policy document for a specific version
aliyun ram get-policy-version \
--policy-name <policy-name> \
--policy-type Custom \
--version-id <version-id>
```
### List Policy Versions
```bash
aliyun ram list-policy-versions \
--policy-name <policy-name> \
--policy-type Custom
```
---
## System Policy Repair Commands
### Attach System Policy to a RAM User
```bash
aliyun ram attach-policy-to-user \
--policy-name <system-policy-name> \
--policy-type System \
--user-name <username>
```
### Attach System Policy to a RAM Role
```bash
aliyun ram attach-policy-to-role \
--policy-name <system-policy-name> \
--policy-type System \
--role-name <rolename>
```
### Detach System Policy
```bash
# Detach from user
aliyun ram detach-policy-from-user \
--policy-name <system-policy-name> \
--policy-type System \
--user-name <username>
# Detach from role
aliyun ram detach-policy-from-role \
--policy-name <system-policy-name> \
--policy-type System \
--role-name <rolename>
```
---
## Custom Policy Repair Commands
### Create Custom Policy (first time)
```bash
aliyun ram create-policy \
--policy-name <policy-name> \
--policy-document '{"Version":"1","Statement":[{"Effect":"Allow","Action":["svc:Action"],"Resource":"acs:svc:*:*:*"}]}'
```
### Attach Custom Policy to a User
```bash
aliyun ram attach-policy-to-user \
--policy-name <policy-name> \
--policy-type Custom \
--user-name <username>
```
### Attach Custom Policy to a Role
```bash
aliyun ram attach-policy-to-role \
--policy-name <policy-name> \
--policy-type Custom \
--role-name <rolename>
```
### Append New Actions (update policy version)
```bash
# Step 1: Get current policy content (check version first)
aliyun ram get-policy --policy-name <policy-name> --policy-type Custom
# Note the DefaultVersion field value, e.g., v3
# Step 2: Read the current version document
aliyun ram get-policy-version \
--policy-name <policy-name> \
--policy-type Custom \
--version-id v3
# Step 3 (if 5 versions already exist): delete the oldest non-default version
aliyun ram delete-policy-version \
--policy-name <policy-name> \
--version-id v1
# Step 4: Create new version (complete JSON with existing + new Actions)
aliyun ram create-policy-version \
--policy-name <policy-name> \
--policy-document '{"Version":"1","Statement":[...all Actions...]}' \
--set-as-default true
```
### Detach Custom Policy
```bash
# Detach from user
aliyun ram detach-policy-from-user \
--policy-name <policy-name> \
--policy-type Custom \
--user-name <username>
# Detach from role
aliyun ram detach-policy-from-role \
--policy-name <policy-name> \
--policy-type Custom \
--role-name <rolename>
```
### Delete Custom Policy (all versions + the policy itself)
```bash
# First delete all non-default versions
aliyun ram delete-policy-version --policy-name <policy-name> --version-id v1
# ...repeat until only the default version remains
# Then delete the policy (automatically removes the last version)
aliyun ram delete-policy --policy-name <policy-name>
```
---
## Role Trust Policy Repair Commands
Use this sequence when root cause is "trust policy not allowing caller":
```bash
# Step 1: Get current trust policy content
aliyun ram get-role --role-name <role-name>
# Note the AssumeRolePolicyDocument field
# Step 2: Update trust policy (add caller ARN to Principal.RAM array)
aliyun ram update-role \
--role-name <role-name> \
--new-assume-role-policy-document '{"Statement":[{"Action":"sts:AssumeRole","Effect":"Allow","Principal":{"RAM":["acs:ram::<account-id>:root","acs:ram::<account-id>:user/<caller-username>"]}}],"Version":"1"}'
# Undo: restore original Principal by calling UpdateRole again with original JSON
aliyun ram update-role \
--role-name <role-name> \
--new-assume-role-policy-document '<original-json>'
```
If caller identity policy also lacks `sts:AssumeRole`, attach the system policy:
```bash
aliyun ram attach-policy-to-user \
--policy-name AliyunSTSAssumeRoleAccess \
--policy-type System \
--user-name <username>
# Undo
aliyun ram detach-policy-from-user \
--policy-name AliyunSTSAssumeRoleAccess \
--policy-type System \
--user-name <username>
```
If role name is unknown, list roles first:
```bash
aliyun ram list-roles
```
---
## Service-Linked Role Commands
```bash
# Create a service-linked role
aliyun resourcemanager create-service-linked-role \
--service-name <service>.aliyuncs.com
# Check whether a service-linked role exists
aliyun ram get-role --role-name AliyunServiceRole<ServiceName>
```
---
## CP Control Policy Query Commands (ResourceDirectory)
```bash
# List all control policies
aliyun resourcemanager list-control-policies
# View a specific control policy's content
aliyun resourcemanager get-control-policy --policy-id <policy-id>
```
FILE:references/ram-policies.md
# RAM Hints for ram-permission-diagnose Skill
<!-- ram-hints-version: 1 -->
## Action Permission Mapping
### Diagnostic Operations (read-only)
| Operation | Required Actions | Optional Actions | Resource Pattern |
|-----------|-----------------|-----------------|-----------------|
| Decode encrypted diagnostic message (L1) | ram:DecodeDiagnosticMessage | - | acs:ram:*:*:* |
| Query current user info (L2) | ram:GetUser | - | acs:ram:*:*:user/* |
| List policies attached to a user (L2) | ram:ListPoliciesForUser | - | acs:ram:*:*:* |
| List policies attached to a role (L2) | ram:ListPoliciesForRole | - | acs:ram:*:*:* |
| Read policy content (L2) | ram:GetPolicy,ram:GetPolicyVersion | - | acs:ram:*:*:policy/* |
| List policy versions (L2) | ram:ListPolicyVersions | - | acs:ram:*:*:policy/* |
| Query CP control policies (L2) | ram:ListControlPolicies,ram:GetControlPolicy | - | acs:ram:*:*:* |
### Repair Operations (write — required for L3)
| Operation | Required Actions | Optional Actions | Resource Pattern |
|-----------|-----------------|-----------------|-----------------|
| Create custom policy | ram:CreatePolicy | - | acs:ram:*:*:policy/* |
| Attach policy to user | ram:AttachPolicyToUser | - | acs:ram:*:*:* |
| Attach policy to role | ram:AttachPolicyToRole | - | acs:ram:*:*:* |
| Update policy version | ram:CreatePolicyVersion,ram:DeletePolicyVersion | ram:ListPolicyVersions | acs:ram:*:*:policy/* |
| Detach policy from user | ram:DetachPolicyFromUser | - | acs:ram:*:*:* |
| Detach policy from role | ram:DetachPolicyFromRole | - | acs:ram:*:*:* |
## Recommended System Policies
- Diagnostic only (L1+L2): `AliyunRAMReadOnlyAccess`
- Full functionality (L1+L2+L3): `AliyunRAMFullAccess`
## Official RAM Documentation
- https://help.aliyun.com/document_detail/28630.html (RAM authorization action list — manually maintained)
Guide users to manage Alibaba Cloud resources using the Aliyun CLI command-line tool. Covers CLI installation, credential configuration, plugin management, c...
--- name: alibabacloud-cli-guidance description: > Guide users to manage Alibaba Cloud resources using the Aliyun CLI command-line tool. Covers CLI installation, credential configuration, plugin management, command construction, and error troubleshooting. Use this skill when the user wants to operate Alibaba Cloud services from the terminal — including ECS (云服务器, cloud servers), Function Compute (函数计算, serverless), RDS (云数据库, databases), OSS (对象存储, object storage), SLS (日志服务, log service), VPC (专有网络, networking), ESS (弹性伸缩, auto scaling), and any other Alibaba Cloud product. Also use when the user mentions "aliyun", "阿里云", "阿里云CLI", "命令行", asks about CLI plugin installation, encounters Aliyun CLI errors (InvalidAccessKeyId, SignatureDoesNotMatch, Throttling), or needs help constructing aliyun commands with correct parameter syntax. license: Apache-2.0 metadata: domain: aliyun-cli owner: sdk-team contact: [email protected] allowed-tools: Bash, aliyun cli --- # Aliyun CLI Expert Guide users to manage Alibaba Cloud resources effectively using the `aliyun` command-line tool. **Required permissions** : see `./references/ram-policies.md` (`## required_permissions`). Extend **on demand** for other CLI commands. ## Instructions ### Agent execution: AI-mode and User-Agent (this skill) **Skill identifier** (same string whichever path you use): `AlibabaCloud-Agent-Skills/alibabacloud-cli-guidance` Use **exactly one** way to attach this skill to requests. **Do not combine** AI-mode (`configure ai-mode` + `set-user-agent`) with `ALIBABA_CLOUD_USER_AGENT` or a per-command env prefix for the **same** skill token — the CLI stacks those sources, and **User-Agent / attribution will duplicate** (bad for telemetry). | Path | When to use | Start | End / cleanup | | ---- | ----------- | ----- | ------------- | | **A — AI-mode (preferred for agents)** | Agent session, many `aliyun` calls | `aliyun configure ai-mode enable` then `aliyun configure ai-mode set-user-agent --user-agent "AlibabaCloud-Agent-Skills/alibabacloud-cli-guidance"` | **[MUST]** `aliyun configure ai-mode disable` before the final response on **every** exit (success, failure, error, cancel, session end). **Do not** `export ALIBABA_CLOUD_USER_AGENT` to the same value while AI-mode is on. | | **B — Environment or one-shot** | One-off commands, scripts without `configure`, or no AI-mode | `export ALIBABA_CLOUD_USER_AGENT=AlibabaCloud-Agent-Skills/alibabacloud-cli-guidance` for the session, **or** prefix each API call: `ALIBABA_CLOUD_USER_AGENT=AlibabaCloud-Agent-Skills/alibabacloud-cli-guidance aliyun ...` | If you used **`export`**, run `unset ALIBABA_CLOUD_USER_AGENT` when done so other skills are not mis-attributed. Inline prefix needs no unset. **Do not** enable AI-mode on path B for the same skill string. | Path A — start (before the first `aliyun` that hits the API; local `aliyun configure` without cloud calls may run first if needed): ```bash aliyun configure ai-mode enable aliyun configure ai-mode set-user-agent --user-agent "AlibabaCloud-Agent-Skills/alibabacloud-cli-guidance" ``` Path A — **[MUST] disable at every exit** (AI-mode must not remain on after the skill stops): ```bash aliyun configure ai-mode disable ``` Path B — examples (one carrier per workflow: `export`, inline env, or root `--user-agent`; never stack the same token or mix with path A): ```bash export ALIBABA_CLOUD_USER_AGENT=AlibabaCloud-Agent-Skills/alibabacloud-cli-guidance # … aliyun … calls … then: unset ALIBABA_CLOUD_USER_AGENT ``` ```bash ALIBABA_CLOUD_USER_AGENT=AlibabaCloud-Agent-Skills/alibabacloud-cli-guidance aliyun ecs DescribeRegions ``` Root **`--user-agent`** is path B semantics too — do not combine with path A for the same token. **Non-agent** copy-paste: path B is often enough; **agent** sessions: path A + disable on exit. Examples below use path A or B only, never both. **Pre-check: Aliyun CLI >= 3.3.3 required** — Run `aliyun version`. If too low: `curl -fsSL https://aliyuncli.alicdn.com/setup.sh | bash` or see `references/installation-guide.md`. **Pre-check: Aliyun CLI plugin update required** — [MUST] `aliyun configure set --auto-plugin-install true`; [MUST] `aliyun plugin update`. **CLI version milestones (agents and users)** | From version | What you gain | | ------------- | -------------- | | **>= 3.3.3** | Baseline for product plugins and flows in this skill (see pre-checks above). | | **>= 3.3.5** | **`aliyun upgrade`** — update the CLI from the binary itself when the subcommand exists. Prefer it over re-running the install script for routine upgrades once the CLI is new enough. | | **>= 3.3.8** | **`aliyun plugin show --name <plugin>`** — details for an **installed** plugin (version, product code, descriptions, API versions when present). On older CLIs, use `aliyun plugin list` and product `--help` only. | ### 1. Install and configure the CLI If the user hasn't installed or configured the CLI, guide them through setup. See `./references/installation-guide.md` for full details. Quick path: ```bash # Install or update (macOS / Linux — one command) /bin/bash -c "$(curl -fsSL --connect-timeout 10 --max-time 120 https://aliyuncli.alicdn.com/setup.sh)" ``` After the CLI is at **3.3.5 or newer**, routine self-updates can use **`aliyun upgrade`** instead of the curl installer (the installer remains appropriate for first-time install or when `upgrade` is not available): ```bash aliyun version # confirm >= 3.3.5 before relying on upgrade aliyun upgrade ``` #### OAuth (browser login) When a **browser can be opened** on the same machine (for example a local desktop with a GUI), **prefer OAuth** over storing AccessKey pairs: credentials are not kept as plaintext AK/SecretKey in configuration, and sign-in can use SSO. Requires Alibaba Cloud CLI **3.0.299** or later. **Not** suitable for headless environments (for example SSH-only servers without a local browser). Run interactively: ```bash aliyun configure --profile <your-profile-name> --mode OAuth ``` Full setup (administrator consent, RAM identity assignments, `CN` vs `INTL` site) is documented in [Configure OAuth authentication for Alibaba Cloud CLI](https://www.alibabacloud.com/help/en/doc-detail/2995960.html) and `./references/installation-guide.md`. ```bash # Credentials via environment variables (automation, CI/CD, headless, or when OAuth is not available) export ALIBABA_CLOUD_ACCESS_KEY_ID=<key-id> export ALIBABA_CLOUD_ACCESS_KEY_SECRET=<key-secret> export ALIBABA_CLOUD_REGION_ID=cn-hangzhou # Temporary credentials (StsToken) — add: # export ALIBABA_CLOUD_SECURITY_TOKEN=<sts-token> # API calls + this skill: use path A (ai-mode) OR path B (ALIBABA_CLOUD_USER_AGENT) — not both — see "Agent execution: AI-mode and User-Agent (this skill)" # Verify aliyun version # Should be >= 3.3.3 aliyun ecs describe-regions # Tests authentication ``` Aliyun CLI 3.3.3+ supports all published Alibaba Cloud product plugins. Newer commands (`aliyun upgrade` from **3.3.5**, `aliyun plugin show` from **3.3.8**) are summarized under **CLI version milestones** near the top of these instructions. #### Authentication modes (environment variables) For modes that use **explicit keys or tokens** (not OAuth), choose what fits the deployment context. When set, these environment variables override any values in `~/.aliyun/config.json`. | Mode | When to use | Environment variables | | ---- | ----------- | --------------------- | | **AK** | Development, long-lived credentials | `ALIBABA_CLOUD_ACCESS_KEY_ID`, `ALIBABA_CLOUD_ACCESS_KEY_SECRET`, `ALIBABA_CLOUD_REGION_ID` | | **StsToken** | CI/CD, temporary credentials | Same as AK, plus `ALIBABA_CLOUD_SECURITY_TOKEN` | | **RamRoleArn** | After AssumeRole or cross-account session | Export the temporary pair from the role session: same variables as **StsToken** (AK + secret + `ALIBABA_CLOUD_SECURITY_TOKEN`) | #### Multiple accounts or environments Use separate `export` blocks per shell session, CI job, or secret store (different `ALIBABA_CLOUD_ACCESS_KEY_ID` / `ALIBABA_CLOUD_ACCESS_KEY_SECRET` / `ALIBABA_CLOUD_REGION_ID` values). For profile-based workflows backed by the config file, see `./references/installation-guide.md`. ### 2. Consult `--help` before constructing any command Built-in commands have inconsistent parameter naming across APIs — some use PascalCase, others camelCase, and the exact names are not predictable. Guessing parameter names frequently leads to errors that require multiple retries. Running `--help` first takes seconds: ```bash aliyun <product> --help # Discover available subcommands aliyun <product> <subcommand> --help # Get exact parameter names, types, structure ``` Help output is the authoritative source. Plugin help is especially rich — it includes type info, structure fields, format hints, and constraints for every parameter. When a plugin is installed, `aliyun <product> --help` automatically shows plugin help. To view the legacy built-in (OpenAPI-style) help instead: ```bash ALIBABA_CLOUD_ORIGINAL_PRODUCT_HELP=true aliyun ecs --help ``` ### 3. Ensure service plugins are available Each Alibaba Cloud product has a CLI plugin. Plugins provide consistent kebab-case commands with comprehensive help, while the legacy built-in system has inconsistent naming and minimal help. If you know which product to use, install the plugin directly — `plugin install` is idempotent (safe to run even if already installed): ```bash aliyun plugin install --names ecs # Install (short name, case-insensitive) aliyun plugin install --names ECS VPC RDS # Multiple at once ``` To discover or verify plugins: ```bash aliyun plugin list # Installed plugins aliyun plugin list-remote # All available plugins aliyun plugin search <keyword> # Search by keyword aliyun plugin show --name ecs # Aliyun CLI >= 3.3.8 — details for one installed plugin ``` `plugin show` requires **Aliyun CLI >= 3.3.8** and only works for **installed** plugins (use `plugin list-remote` / `plugin search` to inspect the catalog). On older versions, omit `plugin show` and rely on `plugin list` plus `aliyun <product> --help`. Plugin names accept both short form (`ecs`) and full form (`aliyun-cli-ecs`), case-insensitive. Plugin lifecycle: ```bash aliyun plugin update --name ecs # Update a plugin aliyun plugin uninstall --name ecs # Remove a plugin ``` ### 4. Prefer plugin commands over built-in commands The CLI has two command styles, and the **subcommand casing** determines which system handles it: - **All-lowercase subcommand** → routed to plugin (CLI Native style) - **Contains uppercase** → routed to built-in (OpenAPI style) Plugin commands use consistent kebab-case naming for both subcommands and parameters, making them predictable. Built-in commands use PascalCase subcommands with mixed/inconsistent parameter naming that varies by API — you must check `--help` for every command to know the exact names. ```bash # Plugin (preferred): consistent kebab-case aliyun ecs describe-instances --biz-region-id cn-hangzhou # Built-in (fallback): PascalCase subcommand, inconsistent params aliyun ecs DescribeInstances --RegionId cn-hangzhou ``` Mixing styles causes silent failures — the CLI routes to different backends based on subcommand casing. A kebab-case subcommand with PascalCase parameters will be sent to the plugin system, which doesn't recognize PascalCase parameter names. Product code is always case-insensitive (`ecs`, `Ecs`, `ECS` all work). | Aspect | Plugin (CLI Native) | Built-in (OpenAPI) | | ------ | ------------------- | ------------------ | | Subcommand | `describe-instances` | `DescribeInstances` | | Parameters | kebab-case (consistent) | Mixed (inconsistent) | | ROA Body | Expanded to individual params | Single `--body` JSON | | Header params | Visible in help, usable directly | Hidden, manual `--header` only | | Help | Comprehensive with structure | Basic | ### 5. Understand global vs business parameter naming The CLI plugin system reserves certain global parameters for its own use: - `--region-id` / `--region` — controls which **API endpoint** the request is sent to (e.g. `ecs.cn-hangzhou.aliyuncs.com`). This is a routing concern, not a business field. - Other globals include `--profile`, `--api-version`, `--output`, etc. Many APIs also define their own `RegionId` or `Region` parameter in the API spec — these are **business parameters** with API-specific meaning (e.g. "the region to create this resource in"). The global `--region-id` and the API's `RegionId` serve different purposes, but they would collide on the command line. The plugin system resolves this automatically during code generation: 1. **`--biz-` prefix (default)**: the API parameter `RegionId` becomes `--biz-region-id` 2. **`--<product>-` prefix (fallback)**: if `--biz-region-id` is already taken by another parameter, the plugin falls back to `--<product>-region-id` (e.g. `--ecs-region-id`) This means in plugin commands, `--region-id` is **always** the global endpoint selector, and the business region is `--biz-region-id` (or `--<product>-region-id`). Using `--region-id` where you meant the business parameter silently changes the endpoint without setting the intended field. Always check `--help` to see the actual parameter name — it is the authoritative source for whether a given command uses `--biz-region-id`, `--<product>-region-id`, or something else. ### 6. Use structured parameter syntax Plugins support structured input that the framework serializes automatically. This avoids the error-prone legacy `--Tag.N.Key` / `--Param.N=value` syntax. **Primitives and lists:** ```bash --instance-id i-abc123 # single value --security-group-ids sg-001 sg-002 sg-003 # space-separated list --instance-id i-abc --instance-id i-def # repeated param (also valid) ``` **Key-value objects and repeatable structures:** ```bash --tag Key=env Value=prod --tag Key=app Value=web # repeatable key-value --capacity-options OnDemandBaseCapacity=12 CompensateWithOnDemand=true # object --data-disk '{"DiskName":"d1","Size":100}' # complex structure (JSON) ``` Check `--help` for each command — it shows the exact type, structure fields, and whether a parameter is repeatable. ### 7. OSS uses custom commands Unlike other products, OSS has a hand-written implementation with custom command syntax. API-style commands like `PutBucket` or `GetObject` do not exist for OSS — using them will fail silently or produce confusing errors. Always check help first: ```bash aliyun oss --help # Basic operations (cp, ls, mb, rm, etc.) aliyun ossutil --help # Advanced utilities (sync, stat, etc.) ``` The lines below are **syntax examples only** (`<your-*>` placeholders). **Do not run them verbatim** — substitute real paths, bucket names, and file names before executing. ```bash aliyun oss cp <your-file-name>.txt oss://<your-bucket-name>/ # Upload aliyun oss mb oss://<your-bucket-name> # Create bucket aliyun ossutil sync ./<your-folder-name>/ oss://<your-bucket-name>/ # Sync directory ``` ### 8. Filter and format output Use `--cli-query` (JMESPath) to extract specific fields from API responses, and `--output` to control the format. This avoids piping large JSON blobs through external tools: ```bash # JMESPath filter: only running instances, selected fields aliyun ecs describe-instances \ --biz-region-id cn-hangzhou \ --cli-query "Instances.Instance[?Status=='Running'].{ID:InstanceId,Name:InstanceName}" # Output formats aliyun ecs describe-instances --biz-region-id cn-hangzhou --output json # default aliyun ecs describe-instances --biz-region-id cn-hangzhou --output table # human-readable table aliyun ecs describe-instances --biz-region-id cn-hangzhou --output cols=InstanceId,InstanceName,Status rows="Instances.Instance[]" # custom columns ``` ### 9. Pagination Many list commands return paginated results. Use `--page-number` and `--page-size` to control: ```bash aliyun ecs describe-instances \ --biz-region-id cn-hangzhou \ --page-number 1 \ --page-size 50 ``` To fetch all pages automatically without manual loops, use `--pager`: ```bash aliyun ecs describe-instances \ --biz-region-id cn-hangzhou \ --pager path='Instances.Instance[]' PageNumber=PageNumber PageSize=PageSize ``` The `path` argument specifies which JSON field contains the page data to merge. ### 10. Wait for resource state Some commands support built-in waiters for automation — poll until a resource reaches the desired state: ```bash aliyun vpc describe-vpc-attribute \ --biz-region-id cn-shanghai \ --vpc-id <your-vpc-id> \ --waiter expr='Status' to='Available' ``` ### 11. Debugging When troubleshooting command failures, these flags reveal what's happening under the hood — the full HTTP request/response and parameter validation details: - `--log-level debug` — detailed request/response logs (shows endpoint, serialized params, response) - `--cli-dry-run` — validate command without executing (checks parameter parsing) - `ALIBABA_CLOUD_CLI_LOG_CONFIG=debug` — environment variable to set log level globally For **403**, **Forbidden**, **NoPermission**, or other RAM-style denials, the identity behind the credentials lacks permission for the underlying API action. See `./references/ram-policies.md` for the skill’s `required_permissions` table, on-demand authorization, and how to narrow permissions. ### 12. Multi-version API support Some products (e.g. ESS, SLB) ship multiple API versions with different command sets and capabilities. Using the wrong version may cause missing parameters, deprecated behavior, or entirely different command availability. Not all products have multiple versions — if `list-api-versions` returns an error, the product is single-version and no action is needed. #### Discover versions ```bash aliyun <product> list-api-versions ``` Example (ESS; `*` = default): ```text * 2014-08-28 (default) 2022-02-22 ``` Each version may expose different commands or parameter names. #### Specify version per command ```bash aliyun ess describe-scaling-groups --api-version 2022-02-22 --biz-region-id cn-hangzhou ``` #### Set a default version via environment variable To avoid passing `--api-version` on every call, set the default for a product: ```bash export ALIBABA_CLOUD_ESS_API_VERSION=2022-02-22 export ALIBABA_CLOUD_SLB_API_VERSION=2014-05-15 ``` The pattern is `ALIBABA_CLOUD_<PRODUCT_CODE>_API_VERSION` (product code in uppercase). This is especially useful in scripts or CI/CD where you want consistent version behavior across multiple commands. #### View commands for a specific version Different API versions may have different command sets. To see what's available: ```bash aliyun ess --api-version 2022-02-22 # List commands in this version aliyun ess <cmd> --api-version 2022-02-22 --help # Help for a specific command in this version ``` #### When to specify version - **Default** — enough unless you need newer features. - **`--help`** — missing parameter may exist only in another API version. - **Scripts / CI** — pin `ALIBABA_CLOUD_<PRODUCT>_API_VERSION` for reproducibility. ## Global Flags Reference These flags are available on all plugin commands: | Flag | Purpose | | ---- | ------- | | `--region <region>` | API endpoint region (global, not business region) | | `--profile <name>` | Use a named credential profile | | `--api-version <ver>` | Override API version for this command | | `--output json\|table\|cols=...` | Response format | | `--cli-query <jmespath>` | JMESPath filter on response | | `--log-level debug` | Verbose request/response logging | | `--cli-dry-run` | Validate without executing | | `--endpoint <url>` | Override service endpoint | | `--retry <n>` | Retry count for failed requests | | `--quiet` | Suppress output | | `--pager` | Auto-merge all pages for pageable APIs | ## Common Workflows ### ECS Instances ```bash aliyun plugin list | grep ecs # If missing: aliyun plugin install --names ecs aliyun ecs describe-instances --biz-region-id cn-hangzhou ``` The `create-instance` example below **provisions billable resources** (fixed image ID, instance type, and disk as illustration). **Do not run it verbatim** — adjust region, image, type, disks, network, and tags for your account and policies before executing. ```bash aliyun ecs create-instance \ --biz-region-id cn-hangzhou \ --instance-type ecs.g7.large \ --image-id ubuntu_20_04_arm64_20G_alibase_20250625.vhd \ --data-disk Category=cloud_essd Size=100 \ --tag Key=env Value=prod --tag Key=app Value=web ``` ### Function Compute (ROA Body Expansion) ```bash aliyun plugin list | grep fc # If missing: aliyun plugin install --names fc ``` The block below is a **syntax example** (`<your-function-name>` and other values are illustrative). **Do not run verbatim** — set the real function name, runtime, handler, memory, timeout, and add any required VPC or service role settings for your environment. Plugin commands expand ROA body fields into individual params (no `--body` JSON needed). ```bash aliyun fc create-function \ --function-name <your-function-name> \ --runtime python3.9 \ --handler index.handler \ --memory-size 512 \ --timeout 60 \ --description "Process uploaded images" ``` ### Multi-Version API (ESS) ```bash # Check available versions aliyun ess list-api-versions # Use the latest version for new features export ALIBABA_CLOUD_ESS_API_VERSION=2022-02-22 aliyun ess describe-scaling-groups --biz-region-id cn-hangzhou # Or specify per command without env var aliyun ess describe-scaling-groups --api-version 2022-02-22 --biz-region-id cn-hangzhou ``` ## Response Format When providing CLI commands: 1. Explain what the command does and why specific parameters are used 2. Show the complete command with all required parameters 3. Call out non-obvious values — especially `--biz-` prefixed parameters and their reason 4. Suggest `--log-level debug` when the user is troubleshooting 5. For API attribution, use **either** AI-mode + `set-user-agent` **or** env/inline `ALIBABA_CLOUD_USER_AGENT`, never both for the same skill token; agents should disable AI-mode on every exit or `unset` after `export` (see **Agent execution: AI-mode and User-Agent (this skill)**) ## References - `./references/installation-guide.md` — Installation, configuration modes, credential setup - `./references/command-syntax.md` — Complete command syntax guide - `./references/global-flags.md` — Global flags reference - `./references/ram-policies.md` — On-demand RAM, least privilege, common permission errors FILE:references/command-syntax.md # Command Syntax Guide Supplementary reference for the Aliyun CLI plugin system. For core usage instructions, see SKILL.md (the primary document). ## Basic Command Structure ```bash aliyun <product> <command> [--parameter value] [--global-flag value] ``` - `<product>`: Plugin name (ecs, fc, rds, oss, sls, etc.) - `<command>`: Operation in kebab-case (describe-instances, create-function) - `--parameter`: Command-specific parameters in kebab-case - `--global-flag`: Global flags like --region-id, --output, --log-level ## Parameter Types, Output Filtering, Global Flags, Pagination, Waiters See SKILL.md §6 (structured parameters), §8 (filter and format output), §9 (pagination), §10 (waiters), and the Global Flags Reference table. ### JSON Parameters (supplementary) For very complex structures where structured syntax is insufficient, raw JSON is supported: ```bash aliyun fc create-function \ --function-name test \ --code '{"zipFile":"base64encoded..."}' ``` ## Help System ```bash aliyun ecs --help # Product-level: list all subcommands aliyun ecs describe-instances --help # Command-level: parameters, types, structure aliyun ecs --help | grep "Available Commands" # Quick command listing ``` When a plugin is installed, `aliyun <product> --help` shows plugin help automatically. See SKILL.md §2 for details on `ALIBABA_CLOUD_ORIGINAL_PRODUCT_HELP`. ## Error Handling ### Common Error Messages 1. **Plugin not found** ```text Error: plugin 'xxx' not found Solution: aliyun plugin install --names xxx ``` 2. **Missing required parameter** ```text Error: required parameter '--instance-id' not provided Solution: Add the required parameter. Check --help for required params. ``` 3. **Invalid parameter value** ```text Error: invalid value for '--instance-type' Solution: Check valid values with --help ``` 4. **API version not supported** ```text Error: unsupported API version Solution: aliyun <product> list-api-versions ``` 5. **Authentication error** ```text Error: InvalidAccessKeyId.NotFound Solution: aliyun configure set --access-key-id <new-key> --access-key-secret <new-secret> ``` 6. **Signature mismatch** ```text Error: SignatureDoesNotMatch Solution: Verify access key secret. Check for extra whitespace in credentials. ``` ### Debugging failed commands Always add `--log-level debug` to see the full request/response cycle: ```bash aliyun ecs describe-instances \ --biz-region-id cn-hangzhou \ --log-level debug ``` This reveals: API endpoint, serialized parameters, HTTP status, and response body. FILE:references/global-flags.md # Global Flags Reference Supplementary reference for CLI global flags. For commonly used flags, see SKILL.md (Global Flags Reference table, §8 output filtering, §11 debugging). This document covers **hidden/advanced flags** and details not in SKILL.md. ## Hidden Global Flags These flags are available but not shown in `--help`: ### --waiter (advanced syntax) SKILL.md §10 shows basic waiter usage. Full syntax with timeout and interval: ```bash aliyun ecs describe-instances \ --instance-id i-xxx \ --waiter expr='Instances.Instance[0].Status' to=Running timeout=180 interval=5 ``` - `expr`: JMESPath expression to evaluate on the response - `to`: Target value to match - `timeout`: Maximum wait in seconds (default varies) - `interval`: Poll interval in seconds (default varies) ### --header Add custom HTTP headers (repeatable): ```bash aliyun ecs describe-instances \ --biz-region-id cn-hangzhou \ --header X-Custom-Header=value \ --header X-Another-Header=value2 ``` ### --body / --body-file Provide raw HTTP request body directly or from file: ```bash aliyun fc invoke-function \ --function-name test \ --body '{"key":"value"}' aliyun fc create-function \ --function-name test \ --body-file ./function-config.json ``` ### --secure / --insecure Force HTTPS or HTTP protocol: ```bash aliyun ecs describe-instances --secure # Force HTTPS aliyun ecs describe-instances --insecure # Force HTTP (not recommended) ``` ### --no-stream For SSE (Server-Sent Events) APIs: aggregate all events before displaying instead of streaming them incrementally: ```bash aliyun <product> <sse-command> --no-stream ``` ## --cli-dry-run Example Output When using `--cli-dry-run`, the CLI prints what would be sent without calling the API: ```text [DRY-RUN] API call would be made with the following details: Endpoint: https://ecs.cn-hangzhou.aliyuncs.com Method: POST Headers: Content-Type: application/x-www-form-urlencoded x-acs-action: CreateInstance Parameters: RegionId=cn-hangzhou InstanceType=ecs.g6.large ImageId=ubuntu_20_04_x64 ``` ## --output rows= Parameter Use `rows=` with `cols=` to specify the JSON path for row data: ```bash aliyun ecs describe-instances \ --output cols=InstanceId,Status rows='Instances.Instance[]' ``` ## Flag Priority When the same setting is configured in multiple places: 1. **Command-line flag** (highest) 2. **Environment variable** 3. **Config file** (`~/.aliyun/config.json`) 4. **Default value** (lowest) ```bash export ALIBABA_CLOUD_REGION_ID=cn-beijing aliyun ecs describe-instances --biz-region-id cn-hangzhou # Uses cn-hangzhou (command-line wins) ``` FILE:references/installation-guide.md # Aliyun CLI Installation & Configuration Guide Complete guide for installing and configuring Aliyun CLI. > **Aliyun CLI 3.3.3+**: Supports installing and using all published Alibaba Cloud product plugins. Make sure to upgrade to 3.3.3 or later for full plugin ecosystem coverage. ## Installation ### macOS / Linux (Recommended) One command to install or update — works on both macOS and Linux, auto-detects architecture: ```bash /bin/bash -c "$(curl -fsSL --connect-timeout 10 --max-time 120 https://aliyuncli.alicdn.com/setup.sh)" ``` After installation, verify: ```bash aliyun version # should be >= 3.3.3 ``` ### macOS — Homebrew (Alternative) ```bash brew install aliyun-cli # Upgrade to latest brew upgrade aliyun-cli ``` ### Linux — Manual Binary (Alternative) Use these only if the setup script above is not suitable. **x86_64** ```bash wget --connect-timeout=10 --read-timeout=120 --tries=3 -qO- https://aliyuncli.alicdn.com/aliyun-cli-linux-latest-amd64.tgz | tar xz sudo mv aliyun /usr/local/bin/ ``` **ARM64** ```bash wget --connect-timeout=10 --read-timeout=120 --tries=3 -qO- https://aliyuncli.alicdn.com/aliyun-cli-linux-latest-arm64.tgz | tar xz sudo mv aliyun /usr/local/bin/ ``` ### Windows **Using Binary** 1. Download from: https://aliyuncli.alicdn.com/aliyun-cli-windows-latest-amd64.zip 2. Extract the ZIP file 3. Add the directory to your PATH environment variable 4. Open new Command Prompt or PowerShell 5. Verify: `aliyun version` **Using PowerShell** ```powershell # Download Invoke-WebRequest -Uri "https://aliyuncli.alicdn.com/aliyun-cli-windows-latest-amd64.zip" -OutFile "aliyun-cli.zip" # Extract Expand-Archive -Path aliyun-cli.zip -DestinationPath C:\aliyun-cli # Add to PATH (requires admin privileges) $env:Path += ";C:\aliyun-cli" [Environment]::SetEnvironmentVariable("Path", $env:Path, [System.EnvironmentVariableTarget]::Machine) # Verify aliyun version ``` ## Configuration ### Quick Start ```bash aliyun configure set \ --mode AK \ --access-key-id <your-access-key-id> \ --access-key-secret <your-access-key-secret> \ --region cn-hangzhou ``` All `aliyun configure` commands support non-interactive flags, which is the recommended approach — it works in scripts, CI/CD pipelines, and agent-driven automation without hanging on stdin prompts. **Where to Get Access Keys** 1. Log in to Aliyun Console: https://ram.console.aliyun.com/ 2. Navigate to: AccessKey Management 3. Create a new AccessKey pair 4. Save the secret immediately — it's only shown once ### Configuration Modes **OAuth (browser login)** — If the environment can open a web browser (for example a local desktop with a GUI), **prefer OAuth** over storing AccessKey pairs in configuration: credentials are not kept as plaintext AK/SecretKey. Requires Alibaba Cloud CLI **3.0.299** or later and is **not** suitable for headless servers (for example SSH-only Linux without a browser on the same machine). Run interactively: ```bash aliyun configure --profile <your-profile-name> --mode OAuth ``` Full setup (administrator consent, RAM assignments, site `CN` vs `INTL`) is covered in the official guide: [Configure OAuth authentication for Alibaba Cloud CLI](https://www.alibabacloud.com/help/en/doc-detail/2995960.html). --- The sections below describe **six** authentication modes that are typically driven with **non-interactive** flags (scripts, CI/CD, automation). Use these when OAuth is not available or when you must supply explicit keys or tokens. #### 1. AK Mode (Access Key) Most common mode for personal accounts and scripts. ```bash aliyun configure set \ --mode AK \ --access-key-id <your-access-key-id> \ --access-key-secret <your-access-key-secret> \ --region cn-hangzhou ``` Configuration is stored in `~/.aliyun/config.json`: ```json { "current": "default", "profiles": [ { "name": "default", "mode": "AK", "access_key_id": "<your-access-key-id>", "access_key_secret": "<your-access-key-secret>", "region_id": "cn-hangzhou", "output_format": "json", "language": "en" } ] } ``` #### 2. StsToken Mode (Temporary Credentials) For short-lived access (tokens expire in 1-12 hours). ```bash aliyun configure set \ --mode StsToken \ --access-key-id <your-access-key-id> \ --access-key-secret <your-access-key-secret> \ --sts-token <your-sts-token> \ --region cn-hangzhou ``` Use cases: CI/CD pipelines, temporary access for external contractors, cross-account access. #### 3. RamRoleArn Mode (Assume RAM Role) Assume a RAM role for elevated or cross-account access. ```bash aliyun configure set \ --mode RamRoleArn \ --access-key-id <your-access-key-id> \ --access-key-secret <your-access-key-secret> \ --ram-role-arn <your-ram-role-arn> \ --role-session-name <your-role-session-name> \ --region cn-hangzhou ``` Use cases: cross-account resource access, temporary elevated privileges, role-based access control. #### 4. EcsRamRole Mode (ECS Instance RAM Role) Use the RAM role attached to an ECS instance — no credentials needed. ```bash aliyun configure set \ --mode EcsRamRole \ --ram-role-name <your-ecs-ram-role-name> \ --region cn-hangzhou ``` Requirements: must be running on an ECS instance with a RAM role attached. Use cases: scripts and automation running on ECS instances. #### 5. RsaKeyPair Mode (RSA Key Pair) Use RSA key pair for authentication (generate key pair in Aliyun Console first). ```bash aliyun configure set \ --mode RsaKeyPair \ --private-key <path-to-your-private-key.pem> \ --key-pair-name <your-key-pair-name> \ --region cn-hangzhou ``` #### 6. RamRoleArnWithEcs Mode (ECS + RAM Role) Combine ECS instance role with RAM role assumption for cross-account access from ECS. ```bash aliyun configure set \ --mode RamRoleArnWithEcs \ --ram-role-name <your-ecs-ram-role-name> \ --ram-role-arn <your-ram-role-arn> \ --role-session-name <your-role-session-name> \ --region cn-hangzhou ``` ### Environment Variables **Highest priority** - overrides config file **Access Key Mode** ```bash export ALIBABA_CLOUD_ACCESS_KEY_ID=<your-access-key-id> export ALIBABA_CLOUD_ACCESS_KEY_SECRET=<your-access-key-secret> export ALIBABA_CLOUD_REGION_ID=cn-hangzhou ``` **STS Token Mode** ```bash export ALIBABA_CLOUD_ACCESS_KEY_ID=<your-access-key-id> export ALIBABA_CLOUD_ACCESS_KEY_SECRET=<your-access-key-secret> export ALIBABA_CLOUD_SECURITY_TOKEN=<your-sts-token> export ALIBABA_CLOUD_REGION_ID=cn-hangzhou ``` **Use Case**: - CI/CD pipelines - Docker containers - Temporary credential override ### Managing Multiple Profiles **Create Named Profiles** ```bash aliyun configure set --profile projectA \ --mode AK \ --access-key-id <your-first-access-key-id> \ --access-key-secret <your-first-access-key-secret> \ --region cn-hangzhou aliyun configure set --profile projectB \ --mode AK \ --access-key-id <your-second-access-key-id> \ --access-key-secret <your-second-access-key-secret> \ --region cn-shanghai ``` **Use Specific Profile** ```bash aliyun ecs describe-instances --profile projectA export ALIBABA_CLOUD_PROFILE=projectA aliyun ecs describe-instances # Uses projectA ``` **List and Switch Profiles** ```bash aliyun configure list # List all profiles aliyun configure switch --profile projectA # Switch default profile ``` ### Credential Priority Credentials are loaded in this order (first found wins): 1. **Command-line flag**: `--profile <name>` 2. **Environment variable**: `ALIBABA_CLOUD_PROFILE` 3. **Environment credentials**: `ALIBABA_CLOUD_ACCESS_KEY_ID`, etc. 4. **Configuration file**: `~/.aliyun/config.json` (current profile) 5. **ECS Instance RAM Role**: If running on ECS with attached role ## Verification ### Test Authentication ```bash # Basic test - list regions aliyun ecs describe-regions # Expected output: JSON array of regions ``` **If successful**, you'll see: ```json { "Regions": { "Region": [ { "RegionId": "cn-hangzhou", "RegionEndpoint": "ecs.cn-hangzhou.aliyuncs.com", "LocalName": "华东 1(杭州)" }, ... ] }, "RequestId": "..." } ``` **If failed**, you'll see error messages: - `InvalidAccessKeyId.NotFound` - Wrong Access Key ID - `SignatureDoesNotMatch` - Wrong Access Key Secret - `InvalidSecurityToken.Expired` - STS token expired (for StsToken mode) - `Forbidden.RAM` - Insufficient permissions ### Debug Configuration ```bash # Show current configuration aliyun configure get # Test with debug logging aliyun ecs describe-regions --log-level debug # Check credential provider aliyun configure get mode ``` ## Security Best Practices ### 1. Use RAM Users (Not Root Account) ❌ **Don't**: Use Aliyun root account credentials ✅ **Do**: Create RAM users with specific permissions ```bash # Create RAM user in console # Attach only necessary policies # Use RAM user's access keys ``` ### 2. Principle of Least Privilege Grant only the minimum permissions needed: ```bash # Example: Read-only ECS access # Attach policy: AliyunECSReadOnlyAccess ``` ### 3. Rotate Access Keys Regularly ```bash # Create new access key in RAM Console, then update configuration aliyun configure set --access-key-id <your-access-key-id> --access-key-secret <your-access-key-secret> # Delete old access key from console ``` ### 4. Use STS Tokens for Temporary Access ```bash aliyun configure set --mode StsToken \ --access-key-id <your-access-key-id> --access-key-secret <your-access-key-secret> \ --sts-token <your-sts-token> --region cn-hangzhou ``` ### 5. Use ECS RAM Roles When Possible ```bash aliyun configure set --mode EcsRamRole --ram-role-name <your-ecs-ram-role-name> --region cn-hangzhou ``` ### 6. Never Commit Credentials ```bash # Add to .gitignore echo "~/.aliyun/config.json" >> .gitignore # Use environment variables in CI/CD instead ``` ### 7. Secure Config File ```bash # Restrict permissions chmod 600 ~/.aliyun/config.json ``` ## Troubleshooting ### Issue: Command Not Found ```bash # Check installation which aliyun # Check PATH echo $PATH # Reinstall or add to PATH ``` ### Issue: Authentication Failed ```bash # Verify configuration aliyun configure get # Test with debug aliyun ecs describe-regions --log-level debug # Check credentials in console # Verify access key is active ``` ### Issue: Permission Denied ```bash # Error: Forbidden.RAM # Check RAM user permissions # Attach necessary policies in RAM console # Example: AliyunECSFullAccess for ECS operations ``` ### Issue: STS Token Expired ```bash # Error: InvalidSecurityToken.Expired # Reconfigure with new token aliyun configure set --mode StsToken \ --access-key-id <your-access-key-id> --access-key-secret <your-access-key-secret> \ --sts-token <your-sts-token> --region cn-hangzhou ``` ### Issue: Wrong Region ```bash # Some resources may not exist in the specified region # Check available regions aliyun ecs describe-regions # Update default region aliyun configure set --region cn-shanghai ``` ## Advanced Configuration ### Timeout Settings ```bash # Connection timeout export ALIBABA_CLOUD_CONNECT_TIMEOUT=30 # Read timeout export ALIBABA_CLOUD_READ_TIMEOUT=30 ``` ## Next Steps After installation and configuration: 1. **Install plugins** for services you need (v3.3.3+ supports all published product plugins): ```bash aliyun plugin install --names ecs vpc rds # List all available plugins aliyun plugin list-remote ``` 2. **Explore commands**: ```bash aliyun ecs --help aliyun fc --help ``` ## References - Official Documentation: https://help.aliyun.com/zh/cli/ - RAM Console: https://ram.console.aliyun.com/ - Access Key Management: https://ram.console.aliyun.com/manage/ak FILE:references/ram-policies.md # RAM policies and the Aliyun CLI Every successful `aliyun` API call is authorized as **your RAM user, RAM role, or STS session**. The CLI does not bypass RAM: if an action is denied in the console, it is denied on the command line with the same identity. Use this note when choosing policies, interpreting errors, or guiding users who automate with the CLI. ## required_permissions RAM permissions for **API operations illustrated** in `SKILL.md`. Use the table format below: **one row per operation**, **`Permission Required` is exactly one** `product:Action` — do not put multiple Actions in a single cell or on one table row. These entries are **not** exhaustive for every CLI workflow. For commands not covered here, resolve Actions with `--log-level debug` and product OpenAPI / RAM docs, and authorize **on demand**. | API Operation | Description | Permission Required | | ------------- | ----------- | ------------------- | | `DescribeRegions` | List regions; auth verification in skill (`aliyun ecs describe-regions`) | `ecs:DescribeRegions` | | `DescribeInstances` | List/query ECS instances, `--cli-query`, pagination examples | `ecs:DescribeInstances` | | `DescribeImages` | Validate image ID | `ecs:DescribeImages` | | `DescribeVpcAttribute` | VPC attribute query and `--waiter` example | `vpc:DescribeVpcAttribute` | | `DescribeScalingGroups` | Query ESS scaling groups in skill examples | `ess:DescribeScalingGroups` | | `GetCallerIdentity` | Verify caller identity (e.g. OAuth verification flows) | `sts:GetCallerIdentity` | Administrators typically use a RAM-managed system policy (for example `AliyunRAMFullAccess`) only for the consenting principal, then grant least privilege to CLI users who sign in via OAuth. **`aliyun ess list-api-versions`**: implementation depend on CLI/plugin version and does not map to a single documented `ess:*` Action. **Local-only** behavior (`aliyun plugin list` for installed plugins, `aliyun <product> --help`) usually does **not** call your account’s RAM-protected APIs; `plugin install` / `plugin list-remote` need outbound network to Aliyun but often no RAM for **your** resources. ## Start from least privilege 1. Prefer **read-only** system policies or custom statements that only allow the `Describe*` / `List*` / `Get*` Actions you need. 2. Grant **write** Actions only for workflows that create, change, or delete resources. 3. Prefer **custom policies** scoped to specific resources or Actions when a system *FullAccess* policy is too broad. ## Relate policies to CLI operations - **Product plugins** (for example `aliyun ecs`, `aliyun vpc`) map to that product’s APIs. The RAM **Action** must match the underlying API (see each product’s OpenAPI and RAM authorization topic). - **Cross-product automation** may require multiple Actions — authorize each separately (**one `Permission Required` per row** in this file’s table; never combine multiple Actions in one cell). When an error names a missing `Action`, add a policy statement that allows that `product:Action` (one Action per array element in JSON policy `Action`, matching one row here). ## Common error signals Symptoms that usually mean a **RAM/policy** issue (not a wrong parameter): - HTTP **403** or messages containing **Forbidden**, **NoPermission**, **not authorized**, **Action denied** - Error codes such as `Forbidden.RAM`, `NoPermission`, or explicit `ACS:CheckSecurity` / missing action in the error body Use `--log-level debug` on the CLI to see the API and error payload. Then fix the identity’s policies (user or role) in RAM, or ask an administrator to attach policies. Authoritative policy syntax, condition keys, and the full API-to-Action mapping are maintained by Alibaba Cloud documentation and the RAM console.
Use this skill when users want to search, discover, browse, or find Alibaba Cloud (阿里云) agent skills. Triggers include: "find a skill for X", "search aliclou...
---
name: alibabacloud-find-skills
description: >
Use this skill when users want to search, discover, browse, or find Alibaba Cloud (阿里云) agent skills.
Triggers include: "find a skill for X", "search alicloud skills", "阿里云有什么 skill",
"搜索阿里云技能", "有没有管理 ECS/RDS/OSS 的 skill", "阿里云 skills 有哪些类目",
"帮我找一个 skill", "browse alicloud skills", "list alicloud skill categories",
"is there an alicloud skill that can...", "what alicloud skills are available", "XX Skill 的内容是什么", "我想了解阿里云 XX Skill 具体做什么","帮我安装阿里云 Skill"
"阿里云 agent skill 市场", "搜一下阿里云的 skill".
---
# Alibaba Cloud Agent Skills Search & Discovery
This skill helps users search, discover, and install Alibaba Cloud official Agent Skills through the `agentexplorer` CLI plugin.
## Scenario Description
This skill enables users to:
1. **Search Skills** — Find Alibaba Cloud Agent Skills by keyword, category, or both
2. **Browse Categories** — Explore available skill categories and subcategories
3. **View Skill Details** — Get detailed information about specific skills
4. **Install Skills** — Guide users through skill installation process
**Architecture**: Alibaba Cloud CLI + agentexplorer Plugin → Skills Repository
### Use Cases
- "Find a skill for managing ECS instances"
- "What Alibaba Cloud skills are available for databases?"
- "阿里云有哪些 OSS 相关的 skill?"
- "Browse all available alicloud skills"
- "Install a skill for RDS management"
## Installation
> **Pre-check: Aliyun CLI >= 3.3.3 required**
>
> Run `aliyun version` to verify >= 3.3.3. If not installed or version too low,
> run `curl -fsSL https://aliyuncli.alicdn.com/setup.sh | bash` to install/update,
> or see [references/cli-installation-guide.md](references/cli-installation-guide.md) for installation instructions.
> Then [MUST] run `aliyun configure set --auto-plugin-install true` to enable automatic plugin installation.
> Then [MUST] run `aliyun plugin update` to ensure that any existing plugins on your local machine are always up-to-date.
**[MUST] CLI User-Agent** — Every `aliyun` CLI command invocation must include:
`--user-agent AlibabaCloud-Agent-Skills/alibabacloud-find-skills`
### Enable AI-Mode
Aliyun CLI provides AI-Mode. When enabled, the CLI automatically attaches AI identity information, allowing the server to identify and optimize Agent call chains.
```bash
# Enable AI-Mode
aliyun configure ai-mode enable
# Set AI-Mode user-agent identifier
aliyun configure ai-mode set-user-agent --user-agent "AlibabaCloud-Agent-Skills/alibabacloud-find-skills"
# Disable AI-Mode
aliyun configure ai-mode disable
```
### Update Plugin
After installing plugins, update them periodically to get the latest features and fixes:
```bash
# Update installed CLI plugins
aliyun plugin update
```
### Install agentexplorer Plugin
```bash
# Install the agentexplorer plugin
aliyun plugin install --names agentexplorer
# Verify installation
aliyun agentexplorer --help --user-agent AlibabaCloud-Agent-Skills/alibabacloud-find-skills
```
## Authentication
> **Pre-check: Alibaba Cloud Credentials Required**
>
> **Security Rules:**
>
> - **NEVER** read, echo, or print AK/SK values (e.g., `echo $ALIBABA_CLOUD_ACCESS_KEY_ID` is FORBIDDEN)
> - **NEVER** ask the user to input AK/SK directly in the conversation or command line
> - **NEVER** use `aliyun configure set` with literal credential values
> - **ONLY** use `aliyun configure list` to check credential status
>
> ```bash
> aliyun configure list --user-agent AlibabaCloud-Agent-Skills/alibabacloud-find-skills
> ```
>
> Check the output for a valid profile (AK, STS, or OAuth identity).
>
> **If no valid profile exists, STOP here.**
>
> 1. Obtain credentials from [Alibaba Cloud Console](https://ram.console.aliyun.com/manage/ak)
> 2. Configure credentials **outside of this session** (via `aliyun configure` in terminal or environment variables in shell profile)
> 3. Return and re-run after `aliyun configure list` shows a valid profile
## RAM Policy
This skill uses read-only APIs from the AgentExplorer service. Required permissions: `agentexplorer:ListCategories`, `agentexplorer:SearchSkills`, `agentexplorer:GetSkillContent`. For the full RAM policy JSON, see [references/ram-policies.md](references/ram-policies.md).
> **[MUST] Permission Failure Handling:** When any command or API call fails due to permission errors at any point during execution, follow this process:
>
> 1. Read `references/ram-policies.md` to get the full list of permissions required by this SKILL
> 2. Use `ram-permission-diagnose` skill to guide the user through requesting the necessary permissions
> 3. Pause and wait until the user confirms that the required permissions have been granted
For detailed permission information, see [references/ram-policies.md](references/ram-policies.md).
## Core Workflow
### Step 1: Search Skills
Based on user intent, choose keyword search, category search, or both:
- **Keyword search**: Extract keywords from the user's request and execute search directly
- **Category search**: Call `list-categories` to get all available categories, select the best match, and search
- **Combined search**: Use both keyword and category to narrow results
```bash
# Keyword search
aliyun agentexplorer search-skills \
--keyword "<keyword>" \
--max-results 20 \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-find-skills
# Get all categories
aliyun agentexplorer list-categories \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-find-skills
# Category search
aliyun agentexplorer search-skills \
--category-code "<category-code>" \
--max-results 20 \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-find-skills
# Combined search (keyword + category)
aliyun agentexplorer search-skills \
--keyword "<keyword>" \
--category-code "<category-code>" \
--max-results 20 \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-find-skills
```
### Step 2: Iterate Until Found
If the target skill is not in the results, adjust search criteria and retry automatically:
1. Switch between Chinese and English keywords ("cloud server" → "ECS", "object storage" → "OSS")
2. Broaden keywords (drop qualifiers: "RDS backup automation" → "RDS")
3. Remove category filter, search by keyword only
4. Try synonyms or related terms ("instance" → "ECS", "bucket" → "OSS")
5. Browse the most relevant top-level category without keyword
Repeat until the target skill is found or confirmed not to exist. If all attempts fail, inform the user what was tried.
### Step 3: View Skill Details (Optional)
Optionally retrieve skill content to verify it matches user intent before installation. This step can be skipped if the search results already provide sufficient information.
```bash
aliyun agentexplorer get-skill-content \
--skill-name "<skill-name>" \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-find-skills
```
### Step 4: Install Skill
Execute the installation command for the target skill.
```bash
# Option A: Using npx skills add
npx skills add aliyun/alibabacloud-aiops-skills \
--skill <skill-name>
# Option B: Using npx clawhub install (recommended for OpenClaw ecosystem)
npx clawhub install <skill-name>
```
Verify the skill appears in the available skills list after installation.
## Command Reference
### Parameters
| Parameter Name | Required/Optional | Description | Default Value |
| --------------- | -------------------------------- | ---------------------------------------------------------------- | ------------- |
| `keyword` | Optional | Search keyword (product name, feature name, or description) | None |
| `category-code` | Optional | Category code for filtering (e.g., "computing", "computing.ecs") | None |
| `max-results` | Optional | Maximum number of results per page (1-100) | 20 |
| `next-token` | Optional | Pagination token from previous response | None |
| `skip` | Optional | Number of items to skip | 0 |
| `skill-name` | Required (for get-skill-content) | Unique skill identifier | None |
### Pagination
When search results span multiple pages, use `next-token` from the previous response to fetch the next page:
```bash
aliyun agentexplorer search-skills \
--keyword "<keyword>" \
--max-results 20 \
--next-token "<next-token-from-previous-response>" \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-find-skills
```
## Success Verification
After each operation, verify success by checking:
1. **List Categories**: Response contains categoryCode and categoryName fields
2. **Search Skills**: Response contains skills array with valid skill objects
3. **Get Skill Content**: Response contains complete skill markdown content
4. **Install Skill**: Skill appears in Claude Code skills list
For detailed verification steps, see [references/verification-method.md](references/verification-method.md).
## Search Strategies & Best Practices
### 1. Keyword Selection
- **Use product codes**: `ecs`, `rds`, `oss`, `slb`, `vpc` (English abbreviations work best)
- **Chinese names**: Also supported, e.g., "云服务器", "数据库", "对象存储"
- **Feature terms**: "backup", "monitoring", "batch operation", "deployment"
- **Generic terms**: When unsure, use broader terms like "compute", "storage", "network"
### 2. Category Filtering
- **Browse first**: Use `list-categories` to understand available categories
- **Top-level categories**: `computing`, `database`, `storage`, `networking`, `security`, etc.
- **Subcategories**: Use dot notation like `computing.ecs`, `database.rds`
- **Multiple categories**: Separate with commas: `computing,database`
### 3. Result Optimization
- **Start broad**: Begin with keyword-only search, then add category filters
- **Adjust page size**: Use `--max-results` based on display needs (20-50 typical)
- **Check install counts**: Popular skills usually have higher install counts
- **Read descriptions**: Match skill description to your specific use case
### 4. When No Results Found
```bash
# Strategy 1: Try alternative keywords
# Instead of "云服务器" try "ECS" or "instance"
# Strategy 2: Remove filters
# Drop category filter, search by keyword only
# Strategy 3: Browse by category
aliyun agentexplorer list-categories --user-agent AlibabaCloud-Agent-Skills/alibabacloud-find-skills
aliyun agentexplorer search-skills --category-code "computing" --user-agent AlibabaCloud-Agent-Skills/alibabacloud-find-skills
# Strategy 4: Use broader terms
# Instead of "RDS backup automation" try just "RDS" or "database"
```
### 5. Display Results to Users
When presenting search results, format as table:
```
Found N skills:
| Skill Name | Display Name | Description | Category | Install Count |
|------------|--------------|-------------|----------|---------------|
| alibabacloud-ecs-batch | ECS Batch Operations | Batch manage ECS instances | Computing > ECS | 245 |
| ... | ... | ... | ... | ... |
```
Include:
- **skillName**: For installation and detailed queries
- **displayName**: User-friendly name
- **description**: Brief overview
- **categoryName** + **subCategoryName**: Classification
- **installCount**: Popularity indicator
## Cleanup
This skill does not create any resources. No cleanup is required.
## Best Practices
1. **Always verify credentials first** — Use `aliyun configure list` before any search operation
2. **Iterate on search** — Automatically adjust keywords and retry until the target skill is found or confirmed absent
3. **Start with broad searches** — Narrow down with filters if too many results
4. **Show category structure** — Help users understand available categories before filtering
5. **Display results clearly** — Use tables to make skill comparison easy
6. **Provide skill names** — Always show `skillName` field for installation
7. **Handle pagination** — Offer to load more results if `nextToken` is present
8. **Check install counts** — Guide users toward popular, well-tested skills
9. **Show full details** — Use `get-skill-content` before installation recommendation
10. **Test after install** — Verify skill is available after installation
## Common Use Cases & Examples
### Example 1: Find ECS Management Skills
```bash
# User: "Find skills for managing ECS instances"
# Step 1: Search by keyword
aliyun agentexplorer search-skills \
--keyword "ECS" \
--max-results 20 \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-find-skills
# Step 2: Display results table and get details for the best match
aliyun agentexplorer get-skill-content \
--skill-name "alibabacloud-ecs-batch-command" \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-find-skills
```
### Example 2: Browse Database Skills
```bash
# User: "What database skills are available?"
# Step 1: List categories to show database category
aliyun agentexplorer list-categories \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-find-skills
# Step 2: Search database category
aliyun agentexplorer search-skills \
--category-code "database" \
--max-results 20 \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-find-skills
# Step 3: Display results grouped by subcategory
```
### Example 3: Search with Chinese Keyword
```bash
# User: "搜索 OSS 相关的 skill"
# Step 1: Search using Chinese or English keyword
aliyun agentexplorer search-skills \
--keyword "OSS" \
--max-results 20 \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-find-skills
# Step 2: Display results in user's preferred language
```
### Example 4: Narrow Down Search
```bash
# User: "Find backup skills for RDS"
# Step 1: Combined search
aliyun agentexplorer search-skills \
--keyword "backup" \
--category-code "database.rds" \
--max-results 20 \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-find-skills
# Step 2: Display targeted results
```
## Reference Documentation
| Reference | Description |
| ---------------------------------------------------------------------------- | -------------------------------------------- |
| [references/ram-policies.md](references/ram-policies.md) | Detailed RAM permission requirements |
| [references/related-commands.md](references/related-commands.md) | Complete CLI command reference |
| [references/verification-method.md](references/verification-method.md) | Success verification steps for each workflow |
| [references/cli-installation-guide.md](references/cli-installation-guide.md) | Alibaba Cloud CLI installation guide |
| [references/acceptance-criteria.md](references/acceptance-criteria.md) | Testing acceptance criteria and patterns |
| [references/category-examples.md](references/category-examples.md) | Common category codes and examples |
## Troubleshooting
### Error: "failed to load configuration"
**Cause**: Alibaba Cloud CLI not configured with credentials.
**Solution**: Follow authentication section above to configure credentials.
### Error: "Plugin not found"
**Cause**: agentexplorer plugin not installed.
**Solution**: Run `aliyun plugin install --names aliyun-cli-agentexplorer`
### No Results Returned
**Cause**: Search criteria too specific or incorrect category code.
**Solutions**:
1. Try broader keywords
2. Remove category filter
3. Use `list-categories` to verify category codes
4. Try English product codes instead of Chinese names
### Pagination Issues
**Cause**: Incorrect nextToken or skip value.
**Solution**: Use exact `nextToken` value from previous response, don't modify it.
## Notes
- **Read-only operations**: This skill only performs queries, no resources are created
- **No credentials required for browsing**: Some operations may work without full credentials
- **Multi-language support**: Keywords support both English and Chinese
- **Regular updates**: Skills catalog is regularly updated with new skills
- **Community skills**: Some skills may be community-contributed, check descriptions carefully
FILE:references/acceptance-criteria.md
# Acceptance Criteria: alibabacloud-find-skills
**Skill Name**: `alibabacloud-find-skills`
**Purpose**: Validate correct CLI command patterns and ensure skill implementation follows best practices
---
## Prerequisites Validation
### 1. Aliyun CLI Version
#### ✅ CORRECT
```bash
# CLI version check returns >= 3.3.1
aliyun version
# Output: 3.3.2 (or higher)
```
#### ❌ INCORRECT
```bash
# Version too old (< 3.3.1)
aliyun version
# Output: 3.0.0
```
**Why**: This skill requires CLI version >= 3.3.1 for plugin support and modern command features.
---
### 2. Plugin Installation
#### ✅ CORRECT
```bash
# Install agentexplorer plugin
aliyun plugin install --names aliyun-cli-agentexplorer
# Verify installation
aliyun plugin list | grep agentexplorer
```
#### ❌ INCORRECT
```bash
# Incorrect plugin name
aliyun plugin install --names agentexplorer
# Wrong command
aliyun install plugin agentexplorer
```
**Why**: The plugin name must be exact: `aliyun-cli-agentexplorer`. CLI uses `plugin install --names` subcommand.
---
## CLI Command Patterns
### 1. Product Name Verification
#### ✅ CORRECT
```bash
# Correct product name
aliyun agentexplorer list-categories --user-agent AlibabaCloud-Agent-Skills
aliyun agentexplorer search-skills --user-agent AlibabaCloud-Agent-Skills
aliyun agentexplorer get-skill-content --user-agent AlibabaCloud-Agent-Skills
```
#### ❌ INCORRECT
```bash
# Wrong product name
aliyun agent-explorer list-categories
aliyun skillexplorer search-skills
aliyun explorerAgent get-skill-content
```
**Why**: The product name is `agentexplorer` (no hyphens, no capitalization).
---
### 2. Command/Action Names
#### ✅ CORRECT
```bash
# Correct command names (lowercase with hyphens)
aliyun agentexplorer list-categories
aliyun agentexplorer search-skills
aliyun agentexplorer get-skill-content
```
#### ❌ INCORRECT
```bash
# Wrong command format (camelCase or incorrect names)
aliyun agentexplorer listCategories
aliyun agentexplorer SearchSkills
aliyun agentexplorer getSkillContent
aliyun agentexplorer list_categories
```
**Why**: Plugin mode uses lowercase with hyphens, NOT camelCase or underscores.
---
### 3. Parameter Names
#### ✅ CORRECT
```bash
# Correct parameter names
aliyun agentexplorer search-skills \
--keyword "ECS" \
--category-code "computing" \
--max-results 20 \
--next-token "abc123" \
--skip 10 \
--user-agent AlibabaCloud-Agent-Skills
aliyun agentexplorer get-skill-content \
--skill-name "alibabacloud-ecs-batch" \
--user-agent AlibabaCloud-Agent-Skills
```
#### ❌ INCORRECT
```bash
# Wrong parameter names
aliyun agentexplorer search-skills --keywords "ECS" # plural
aliyun agentexplorer search-skills --category "computing" # missing -code
aliyun agentexplorer search-skills --max-result 20 # singular
aliyun agentexplorer search-skills --nextToken "abc" # camelCase
aliyun agentexplorer get-skill-content --skillName "name" # camelCase
aliyun agentexplorer get-skill-content --name "name" # wrong parameter
```
**Why**: Parameter names must match exactly as defined in `--help` output.
---
### 4. User-Agent Flag (CRITICAL)
#### ✅ CORRECT
```bash
# Every agentexplorer command MUST include user-agent
aliyun agentexplorer list-categories \
--user-agent AlibabaCloud-Agent-Skills
aliyun agentexplorer search-skills \
--keyword "ECS" \
--user-agent AlibabaCloud-Agent-Skills
aliyun agentexplorer get-skill-content \
--skill-name "example" \
--user-agent AlibabaCloud-Agent-Skills
```
#### ❌ INCORRECT
```bash
# Missing user-agent flag
aliyun agentexplorer list-categories
aliyun agentexplorer search-skills --keyword "ECS"
# Wrong user-agent value
aliyun agentexplorer list-categories --user-agent "MyAgent"
```
**Why**: All commands MUST include `--user-agent AlibabaCloud-Agent-Skills` for tracking and compliance.
---
### 5. Required Parameters
#### ✅ CORRECT
```bash
# get-skill-content requires --skill-name
aliyun agentexplorer get-skill-content \
--skill-name "alibabacloud-ecs-batch" \
--user-agent AlibabaCloud-Agent-Skills
# search-skills works with no required parameters (but keyword or category recommended)
aliyun agentexplorer search-skills \
--user-agent AlibabaCloud-Agent-Skills
# list-categories has no required parameters
aliyun agentexplorer list-categories \
--user-agent AlibabaCloud-Agent-Skills
```
#### ❌ INCORRECT
```bash
# Missing required parameter
aliyun agentexplorer get-skill-content \
--user-agent AlibabaCloud-Agent-Skills
# ERROR: --skill-name is required
```
**Why**: `--skill-name` is mandatory for `get-skill-content`. Other commands have no required params beyond user-agent.
---
## Parameter Value Patterns
### 1. Category Code Format
#### ✅ CORRECT
```bash
# Top-level category
aliyun agentexplorer search-skills \
--category-code "computing" \
--user-agent AlibabaCloud-Agent-Skills
# Subcategory (dot notation)
aliyun agentexplorer search-skills \
--category-code "computing.ecs" \
--user-agent AlibabaCloud-Agent-Skills
# Multiple categories (comma-separated)
aliyun agentexplorer search-skills \
--category-code "computing,database,storage" \
--user-agent AlibabaCloud-Agent-Skills
# Mixed levels
aliyun agentexplorer search-skills \
--category-code "computing.ecs,database" \
--user-agent AlibabaCloud-Agent-Skills
```
#### ❌ INCORRECT
```bash
# Wrong separator for multiple categories
aliyun agentexplorer search-skills --category-code "computing database"
aliyun agentexplorer search-skills --category-code "computing;database"
# Wrong subcategory format
aliyun agentexplorer search-skills --category-code "computing/ecs"
aliyun agentexplorer search-skills --category-code "computing:ecs"
# Invalid category codes
aliyun agentexplorer search-skills --category-code "invalid-category"
```
**Why**: Use dot notation for subcategories (e.g., `category.subcategory`), comma-separated for multiple.
---
### 2. Max Results Range
#### ✅ CORRECT
```bash
# Valid range: 1-100
aliyun agentexplorer search-skills \
--max-results 1 \
--user-agent AlibabaCloud-Agent-Skills
aliyun agentexplorer search-skills \
--max-results 50 \
--user-agent AlibabaCloud-Agent-Skills
aliyun agentexplorer search-skills \
--max-results 100 \
--user-agent AlibabaCloud-Agent-Skills
# Default (omit parameter)
aliyun agentexplorer search-skills \
--user-agent AlibabaCloud-Agent-Skills
# Uses default: 20
```
#### ❌ INCORRECT
```bash
# Out of range
aliyun agentexplorer search-skills --max-results 0
aliyun agentexplorer search-skills --max-results 101
aliyun agentexplorer search-skills --max-results 1000
# Invalid type
aliyun agentexplorer search-skills --max-results "twenty"
```
**Why**: `--max-results` must be an integer between 1 and 100 (inclusive).
---
### 3. Keyword Format
#### ✅ CORRECT
```bash
# Single word
aliyun agentexplorer search-skills \
--keyword "ECS" \
--user-agent AlibabaCloud-Agent-Skills
# Multiple words (quoted)
aliyun agentexplorer search-skills \
--keyword "batch command" \
--user-agent AlibabaCloud-Agent-Skills
# Chinese characters
aliyun agentexplorer search-skills \
--keyword "云服务器" \
--user-agent AlibabaCloud-Agent-Skills
# Mixed English and Chinese
aliyun agentexplorer search-skills \
--keyword "ECS实例管理" \
--user-agent AlibabaCloud-Agent-Skills
```
#### ❌ INCORRECT
```bash
# Unquoted multi-word (may cause parsing errors)
aliyun agentexplorer search-skills --keyword batch command
# Special characters without quotes
aliyun agentexplorer search-skills --keyword ECS&RDS
```
**Why**: Multi-word keywords must be quoted. Special characters may need quoting or escaping.
---
### 4. Next Token Usage
#### ✅ CORRECT
```bash
# First page (no token)
RESULT=$(aliyun agentexplorer search-skills \
--keyword "ECS" \
--max-results 20 \
--user-agent AlibabaCloud-Agent-Skills)
# Extract nextToken from response
NEXT_TOKEN=$(echo "$RESULT" | jq -r '.nextToken')
# Second page (with token)
aliyun agentexplorer search-skills \
--keyword "ECS" \
--max-results 20 \
--next-token "$NEXT_TOKEN" \
--user-agent AlibabaCloud-Agent-Skills
```
#### ❌ INCORRECT
```bash
# Manually crafted token
aliyun agentexplorer search-skills \
--next-token "page2" \
--user-agent AlibabaCloud-Agent-Skills
# Modified token
aliyun agentexplorer search-skills \
--next-token "NEXT_TOKEN_modified" \
--user-agent AlibabaCloud-Agent-Skills
# Using skip instead of next-token for pagination
aliyun agentexplorer search-skills \
--skip 20 \
--user-agent AlibabaCloud-Agent-Skills
# Note: --skip is valid but --next-token is preferred for pagination
```
**Why**: `nextToken` must be used exactly as returned by the API, without modification.
---
## Authentication Patterns
### 1. Credential Verification
#### ✅ CORRECT
```bash
# Check credentials before operations
aliyun configure list --user-agent AlibabaCloud-Agent-Skills
# Never read/print credentials
# NEVER do: echo $ALIBABA_CLOUD_ACCESS_KEY_ID
# NEVER do: aliyun configure get --key access_key_id
```
#### ❌ INCORRECT
```bash
# Reading credentials
echo $ALIBABA_CLOUD_ACCESS_KEY_ID
echo $ALIBABA_CLOUD_ACCESS_KEY_SECRET
# Printing credentials
aliyun configure get --key access_key_id
# Asking user to input credentials in conversation
# "Please provide your Access Key ID"
```
**Why**: Credentials must NEVER be read, printed, or requested directly for security reasons.
---
### 2. Configuration Check
#### ✅ CORRECT
```bash
# Use configure list to check status
aliyun configure list --user-agent AlibabaCloud-Agent-Skills
# Check if output shows valid profile
# Example valid output:
# Profile | Credential | Valid | Region
# --------- | ------------------ | ------- | --------
# default * | AK:***abc | Valid | cn-hangzhou
```
#### ❌ INCORRECT
```bash
# Don't test credentials by making API calls
aliyun agentexplorer list-categories --user-agent AlibabaCloud-Agent-Skills
# (Use this for functionality, not credential verification)
```
**Why**: Use `configure list` specifically for credential validation before operations.
---
## Output Handling Patterns
### 1. JMESPath Filtering
#### ✅ CORRECT
```bash
# Filter for specific fields
aliyun agentexplorer search-skills \
--keyword "ECS" \
--cli-query "skills[].skillName" \
--user-agent AlibabaCloud-Agent-Skills
# Filter with conditions
aliyun agentexplorer search-skills \
--keyword "ECS" \
--cli-query "skills[?installCount > \`100\`]" \
--user-agent AlibabaCloud-Agent-Skills
# Select first item
aliyun agentexplorer search-skills \
--keyword "ECS" \
--cli-query "skills[0]" \
--user-agent AlibabaCloud-Agent-Skills
```
#### ❌ INCORRECT
```bash
# Invalid JMESPath syntax
aliyun agentexplorer search-skills --cli-query "skills.skillName" # Missing []
aliyun agentexplorer search-skills --cli-query "skills[skillName]" # Wrong syntax
```
**Why**: JMESPath syntax must be valid. Arrays require `[]`, conditions use `?`, literals use backticks.
---
### 2. Result Display
#### ✅ CORRECT
```markdown
# Display results in table format
| Skill Name | Display Name | Category | Install Count |
| ---------------------- | ------------- | --------- | ------------- |
| alibabacloud-ecs-batch | ECS Batch Ops | Computing | 245 |
# Show key fields
- **Skill Name**: alibabacloud-ecs-batch
- **Description**: Batch manage ECS instances
- **Category**: Computing > ECS
```
#### ❌ INCORRECT
```bash
# Dumping raw JSON
echo "$RESULT"
# No formatting
echo "$RESULT" | jq
```
**Why**: Users need human-readable, formatted output with relevant fields highlighted.
---
## Error Handling Patterns
### 1. Missing Plugin
#### ✅ CORRECT
```bash
# Check plugin before use
if ! aliyun plugin list | grep -q "agentexplorer"; then
echo "Installing agentexplorer plugin..."
aliyun plugin install --names aliyun-cli-agentexplorer
fi
```
#### ❌ INCORRECT
```bash
# Assume plugin is installed
aliyun agentexplorer list-categories --user-agent AlibabaCloud-Agent-Skills
# May fail if plugin not installed
```
**Why**: Verify prerequisites before execution to provide helpful error messages.
---
### 2. No Results Handling
#### ✅ CORRECT
```bash
RESULT=$(aliyun agentexplorer search-skills \
--keyword "nonexistent" \
--user-agent AlibabaCloud-Agent-Skills)
# Check if skills array is empty
if echo "$RESULT" | jq -e '.skills | length == 0' > /dev/null; then
echo "No skills found for keyword 'nonexistent'"
echo "Try: broader keywords, different category, or list all categories"
fi
```
#### ❌ INCORRECT
```bash
# Don't treat empty results as error
RESULT=$(aliyun agentexplorer search-skills --keyword "nonexistent" --user-agent AlibabaCloud-Agent-Skills)
if [ $? -ne 0 ]; then
echo "Search failed" # Wrong: empty results return exit code 0
fi
```
**Why**: Empty results are valid responses (exit code 0), not errors.
---
## Workflow Patterns
### 1. Search-Detail-Install Flow
#### ✅ CORRECT
```bash
# Step 1: Search
SEARCH_RESULT=$(aliyun agentexplorer search-skills \
--keyword "ECS" \
--user-agent AlibabaCloud-Agent-Skills)
# Step 2: Display results to user, get confirmation
echo "Found skills: ..."
# [User selects: alibabacloud-ecs-batch]
# Step 3: Get details
aliyun agentexplorer get-skill-content \
--skill-name "alibabacloud-ecs-batch" \
--user-agent AlibabaCloud-Agent-Skills
# Step 4: User confirms installation
npx skills add https://github.com/aliyun/alibabacloud-aiops-skills --skill alibabacloud-ecs-batch
```
#### ❌ INCORRECT
```bash
# Skip presenting results to user
SKILL=$(aliyun agentexplorer search-skills --keyword "ECS" --cli-query "skills[0].skillName" --user-agent AlibabaCloud-Agent-Skills)
npx skills add https://github.com/aliyun/alibabacloud-aiops-skills --skill "$SKILL"
# Wrong: Should present search results and skill details to user before installing
```
**Why**: Always present search results and skill details to the user before executing installation.
---
## Common Anti-Patterns
### ❌ ANTI-PATTERN 1: Arbitrary Hardcoded Values
```bash
# DON'T use keywords unrelated to the user's request
# e.g., User asks about databases but Agent searches for "ECS"
aliyun agentexplorer search-skills \
--keyword "ECS" \
--category-code "computing" \
--user-agent AlibabaCloud-Agent-Skills
```
**✅ CORRECT**: Derive keyword and category from the user's intent.
---
### ❌ ANTI-PATTERN 2: Missing Error Handling
```bash
# DON'T ignore errors
aliyun agentexplorer search-skills --keyword "test" --user-agent AlibabaCloud-Agent-Skills
# Continue regardless of result
```
**✅ CORRECT**: Check exit codes and handle errors.
---
### ❌ ANTI-PATTERN 3: Credential Exposure
```bash
# DON'T print or request credentials
echo "Your AK: $ALIBABA_CLOUD_ACCESS_KEY_ID"
```
**✅ CORRECT**: Use `configure list` to check status only.
---
## Testing Checklist
Before completing the skill, verify:
- [ ] All commands use correct product name: `agentexplorer`
- [ ] All commands use lowercase-with-hyphens format
- [ ] All parameters match `--help` output exactly
- [ ] Every command includes `--user-agent AlibabaCloud-Agent-Skills`
- [ ] Required parameters are always provided
- [ ] Category codes use dot notation for subcategories
- [ ] Pagination uses exact `nextToken` from response
- [ ] Credentials are never read/printed
- [ ] User confirmation required before actions
- [ ] Empty results handled gracefully
- [ ] Errors provide actionable guidance
- [ ] Output formatted for readability
---
## Verification Commands
Run these commands to validate the skill:
```bash
# Test 1: List categories
aliyun agentexplorer list-categories --user-agent AlibabaCloud-Agent-Skills
# Test 2: Search by keyword
aliyun agentexplorer search-skills --keyword "ECS" --user-agent AlibabaCloud-Agent-Skills
# Test 3: Search by category
aliyun agentexplorer search-skills --category-code "computing" --user-agent AlibabaCloud-Agent-Skills
# Test 4: Get skill content
aliyun agentexplorer get-skill-content --skill-name "example-skill" --user-agent AlibabaCloud-Agent-Skills
# Test 5: Check credentials
aliyun configure list --user-agent AlibabaCloud-Agent-Skills
```
All commands should execute without syntax errors (though some may return "no results" or "skill not found", which is acceptable).
FILE:references/category-examples.md
# Category Examples
This reference provides common category codes and examples to help users navigate the Alibaba Cloud Agent Skills catalog.
## How to Use This Reference
1. **Find your domain** — Locate the relevant top-level category
2. **Browse subcategories** — Check if there's a specific subcategory for your need
3. **Use the category code** — Copy the code for use in search commands
## Category Code Format
- **Top-level category**: Use the category code directly (e.g., `computing`)
- **Subcategory**: Use dot notation (e.g., `computing.ecs`)
- **Multiple categories**: Separate with commas (e.g., `computing,database`)
## Common Categories
This is a reference guide. For the complete, up-to-date list, always run:
```bash
aliyun agentexplorer list-categories --user-agent AlibabaCloud-Agent-Skills/alibabacloud-find-skills
```
---
## 1. Computing (计算)
**Category Code**: `computing`
**Description**: Skills related to computing resources and instance management.
### Subcategories
| Subcategory Code | Name | Example Use Cases |
|------------------|------|-------------------|
| `computing.ecs` | 云服务器 ECS | Instance creation, batch operations, monitoring |
| `computing.eci` | 弹性容器实例 ECI | Container instance management |
| `computing.sae` | Serverless 应用引擎 SAE | Serverless app deployment |
| `computing.fc` | 函数计算 FC | Function as a Service, serverless functions |
| `computing.ehpc` | 弹性高性能计算 EHPC | High-performance computing clusters |
### Example Searches
```bash
# All computing skills
aliyun agentexplorer search-skills \
--category-code "computing" \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-find-skills
# Only ECS skills
aliyun agentexplorer search-skills \
--category-code "computing.ecs" \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-find-skills
# ECS batch operations
aliyun agentexplorer search-skills \
--keyword "batch" \
--category-code "computing.ecs" \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-find-skills
```
---
## 2. Database (数据库)
**Category Code**: `database`
**Description**: Skills for database management and operations.
### Subcategories
| Subcategory Code | Name | Example Use Cases |
|------------------|------|-------------------|
| `database.rds` | 云数据库 RDS | RDS instance management, backup, migration |
| `database.polardb` | 云原生数据库 PolarDB | PolarDB operations |
| `database.mongodb` | 云数据库 MongoDB | MongoDB management |
| `database.redis` | 云数据库 Redis | Redis cache management |
| `database.memcache` | 云数据库 Memcache | Memcache operations |
| `database.oceanbase` | OceanBase | Distributed database operations |
### Example Searches
```bash
# All database skills
aliyun agentexplorer search-skills \
--category-code "database" \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-find-skills
# RDS backup skills
aliyun agentexplorer search-skills \
--keyword "backup" \
--category-code "database.rds" \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-find-skills
# Database and cache combined
aliyun agentexplorer search-skills \
--category-code "database.rds,database.redis" \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-find-skills
```
---
## 3. Storage (存储)
**Category Code**: `storage`
**Description**: Skills for object storage, file systems, and backup.
### Subcategories
| Subcategory Code | Name | Example Use Cases |
|------------------|------|-------------------|
| `storage.oss` | 对象存储 OSS | Object storage operations, bucket management |
| `storage.nas` | 文件存储 NAS | Network attached storage |
| `storage.oss-hdfs` | OSS-HDFS | HDFS-compatible object storage |
| `storage.cpfs` | 文件存储 CPFS | Parallel file system |
| `storage.hbr` | 混合云备份 HBR | Hybrid cloud backup |
### Example Searches
```bash
# All storage skills
aliyun agentexplorer search-skills \
--category-code "storage" \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-find-skills
# OSS bucket management
aliyun agentexplorer search-skills \
--keyword "bucket" \
--category-code "storage.oss" \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-find-skills
# Backup solutions
aliyun agentexplorer search-skills \
--keyword "backup" \
--category-code "storage" \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-find-skills
```
---
## 4. Networking (网络)
**Category Code**: `networking`
**Description**: Skills for VPC, load balancers, and network management.
### Subcategories
| Subcategory Code | Name | Example Use Cases |
|------------------|------|-------------------|
| `networking.vpc` | 专有网络 VPC | VPC creation, VSwitch management |
| `networking.slb` | 负载均衡 SLB | Load balancer configuration |
| `networking.eip` | 弹性公网 IP EIP | Elastic IP management |
| `networking.nat` | NAT 网关 | NAT gateway operations |
| `networking.cdn` | CDN | Content delivery network |
| `networking.ga` | 全球加速 GA | Global acceleration |
### Example Searches
```bash
# All networking skills
aliyun agentexplorer search-skills \
--category-code "networking" \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-find-skills
# VPC setup
aliyun agentexplorer search-skills \
--keyword "setup" \
--category-code "networking.vpc" \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-find-skills
# Load balancer configuration
aliyun agentexplorer search-skills \
--category-code "networking.slb" \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-find-skills
```
---
## 5. Security (安全)
**Category Code**: `security`
**Description**: Skills for security management, access control, and compliance.
### Subcategories
| Subcategory Code | Name | Example Use Cases |
|------------------|------|-------------------|
| `security.ram` | 访问控制 RAM | IAM, user/role management |
| `security.kms` | 密钥管理服务 KMS | Key management, encryption |
| `security.waf` | Web 应用防火墙 WAF | Web application firewall |
| `security.ddos` | DDoS 防护 | DDoS protection |
| `security.sas` | 云安全中心 SAS | Security center operations |
| `security.saf` | 风险识别 SAF | Risk identification |
### Example Searches
```bash
# All security skills
aliyun agentexplorer search-skills \
--category-code "security" \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-find-skills
# RAM policy management
aliyun agentexplorer search-skills \
--keyword "policy" \
--category-code "security.ram" \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-find-skills
# Encryption and key management
aliyun agentexplorer search-skills \
--category-code "security.kms" \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-find-skills
```
---
## 6. Container (容器)
**Category Code**: `container`
**Description**: Skills for Kubernetes, container registry, and container management.
### Subcategories
| Subcategory Code | Name | Example Use Cases |
|------------------|------|-------------------|
| `container.ack` | 容器服务 Kubernetes ACK | K8s cluster management |
| `container.acr` | 容器镜像服务 ACR | Container registry operations |
| `container.eci` | 弹性容器实例 ECI | Serverless containers |
| `container.ask` | Serverless Kubernetes ASK | Serverless K8s |
### Example Searches
```bash
# All container skills
aliyun agentexplorer search-skills \
--category-code "container" \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-find-skills
# Kubernetes deployment
aliyun agentexplorer search-skills \
--keyword "deployment" \
--category-code "container.ack" \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-find-skills
# Container image management
aliyun agentexplorer search-skills \
--category-code "container.acr" \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-find-skills
```
---
## 7. AI & Machine Learning (人工智能)
**Category Code**: `ai`
**Description**: Skills for AI services, machine learning, and model management.
### Subcategories
| Subcategory Code | Name | Example Use Cases |
|------------------|------|-------------------|
| `ai.pai` | 机器学习 PAI | Machine learning platform |
| `ai.nlp` | 自然语言处理 NLP | NLP services |
| `ai.vision` | 视觉智能 | Computer vision APIs |
| `ai.bailian` | 百炼 | Model service platform |
### Example Searches
```bash
# All AI skills
aliyun agentexplorer search-skills \
--category-code "ai" \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-find-skills
# Machine learning workflows
aliyun agentexplorer search-skills \
--keyword "training" \
--category-code "ai.pai" \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-find-skills
# NLP services
aliyun agentexplorer search-skills \
--category-code "ai.nlp" \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-find-skills
```
---
## 8. Big Data (大数据)
**Category Code**: `bigdata`
**Description**: Skills for data processing, analytics, and data warehousing.
### Subcategories
| Subcategory Code | Name | Example Use Cases |
|------------------|------|-------------------|
| `bigdata.maxcompute` | MaxCompute | Data warehousing, big data processing |
| `bigdata.datav` | DataV | Data visualization |
| `bigdata.emr` | E-MapReduce | Hadoop/Spark cluster management |
| `bigdata.dataworks` | DataWorks | Data development and orchestration |
| `bigdata.hologres` | Hologres | Real-time data warehouse |
### Example Searches
```bash
# All big data skills
aliyun agentexplorer search-skills \
--category-code "bigdata" \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-find-skills
# Data warehouse operations
aliyun agentexplorer search-skills \
--category-code "bigdata.maxcompute" \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-find-skills
# Data visualization
aliyun agentexplorer search-skills \
--category-code "bigdata.datav" \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-find-skills
```
---
## 9. Monitoring & Operations (监控运维)
**Category Code**: `monitoring`
**Description**: Skills for monitoring, logging, and operational management.
### Subcategories
| Subcategory Code | Name | Example Use Cases |
|------------------|------|-------------------|
| `monitoring.cms` | 云监控 CMS | Cloud monitoring, alerts |
| `monitoring.arms` | 应用实时监控 ARMS | APM, application monitoring |
| `monitoring.sls` | 日志服务 SLS | Log collection and analysis |
| `monitoring.oos` | 运维编排服务 OOS | Operation orchestration |
### Example Searches
```bash
# All monitoring skills
aliyun agentexplorer search-skills \
--category-code "monitoring" \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-find-skills
# Alert configuration
aliyun agentexplorer search-skills \
--keyword "alert" \
--category-code "monitoring.cms" \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-find-skills
# Log analysis
aliyun agentexplorer search-skills \
--category-code "monitoring.sls" \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-find-skills
```
---
## 10. Developer Tools (开发者工具)
**Category Code**: `devtools`
**Description**: Skills for CI/CD, code management, and development workflows.
### Subcategories
| Subcategory Code | Name | Example Use Cases |
|------------------|------|-------------------|
| `devtools.cr` | 容器镜像服务 CR | Container registry |
| `devtools.rdc` | 云效 DevOps | CI/CD pipelines |
| `devtools.emas` | 移动研发平台 EMAS | Mobile development |
### Example Searches
```bash
# All developer tools
aliyun agentexplorer search-skills \
--category-code "devtools" \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-find-skills
# CI/CD pipeline
aliyun agentexplorer search-skills \
--keyword "pipeline" \
--category-code "devtools.rdc" \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-find-skills
```
---
## Search Strategy Examples
### Example 1: Find Skills for a Specific Product
```bash
# I need skills for RDS database management
aliyun agentexplorer search-skills \
--keyword "RDS" \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-find-skills
# Or search within database category
aliyun agentexplorer search-skills \
--keyword "RDS" \
--category-code "database" \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-find-skills
# Or directly search RDS subcategory
aliyun agentexplorer search-skills \
--category-code "database.rds" \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-find-skills
```
### Example 2: Find Skills for Cross-Service Scenarios
```bash
# I need skills for VPC + ECS setup
aliyun agentexplorer search-skills \
--keyword "VPC ECS" \
--category-code "computing,networking" \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-find-skills
# Or search separately and combine results
aliyun agentexplorer search-skills \
--keyword "network setup" \
--category-code "computing.ecs" \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-find-skills
```
### Example 3: Find Skills by Feature
```bash
# I need backup-related skills across all services
aliyun agentexplorer search-skills \
--keyword "backup" \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-find-skills
# Or narrow to database backups
aliyun agentexplorer search-skills \
--keyword "backup" \
--category-code "database" \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-find-skills
```
### Example 4: Browse a Domain
```bash
# I want to see all security-related skills
aliyun agentexplorer search-skills \
--category-code "security" \
--max-results 50 \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-find-skills
# Narrow to specific security service
aliyun agentexplorer search-skills \
--category-code "security.ram,security.kms" \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-find-skills
```
---
## Tips for Category Selection
### 1. Start Broad, Then Narrow
```bash
# Step 1: Browse top-level category
aliyun agentexplorer search-skills \
--category-code "computing" \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-find-skills
# Step 2: If too many results, narrow to subcategory
aliyun agentexplorer search-skills \
--category-code "computing.ecs" \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-find-skills
# Step 3: Add keyword for further filtering
aliyun agentexplorer search-skills \
--keyword "batch" \
--category-code "computing.ecs" \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-find-skills
```
### 2. Use Multiple Categories for Cross-Service Skills
```bash
# Find skills that work with both ECS and RDS
aliyun agentexplorer search-skills \
--category-code "computing.ecs,database.rds" \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-find-skills
```
### 3. Combine Keyword with Category
```bash
# Most effective search strategy
aliyun agentexplorer search-skills \
--keyword "monitoring" \
--category-code "computing.ecs" \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-find-skills
```
---
## Troubleshooting
### No Results for Category Code
**Possible causes**:
1. Category code doesn't exist (check spelling)
2. No skills in that category yet
3. Wrong separator (use dot for subcategory, comma for multiple)
**Solution**:
```bash
# List all valid categories
aliyun agentexplorer list-categories --user-agent AlibabaCloud-Agent-Skills/alibabacloud-find-skills
# Verify the correct category code
```
### Too Many Results
**Solution**: Add filters
```bash
# Add keyword filter
aliyun agentexplorer search-skills \
--keyword "specific-feature" \
--category-code "category" \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-find-skills
# Reduce to subcategory
aliyun agentexplorer search-skills \
--category-code "category.subcategory" \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-find-skills
```
### Not Sure Which Category
**Solution**: Use keyword-only search first
```bash
# Search by product name only
aliyun agentexplorer search-skills \
--keyword "ECS" \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-find-skills
# Check the categoryName and subCategoryName in results
# Then refine with category filter
```
---
## Quick Reference Table
| I Want To... | Search Strategy |
|--------------|-----------------|
| Find all skills for a product | `--keyword "ProductName"` |
| Browse a service category | `--category-code "category"` |
| Find specific subcategory skills | `--category-code "category.subcategory"` |
| Search across multiple categories | `--category-code "cat1,cat2,cat3"` |
| Find cross-service solutions | `--keyword "feature" --category-code "cat1,cat2"` |
| Narrow search results | Add both `--keyword` and `--category-code` |
| See all available categories | `aliyun agentexplorer list-categories --user-agent AlibabaCloud-Agent-Skills/alibabacloud-find-skills` |
---
## Notes
- **Always use `list-categories` first**: Get the most up-to-date category structure
- **Category names may change**: Official names and codes may be updated over time
- **Chinese and English**: Many skills support both language descriptions
- **Skill count varies**: Some categories have many skills, others have few
- **New categories added regularly**: Check back for new categories and skills
FILE:references/cli-installation-guide.md
# Aliyun CLI Installation & Configuration Guide
Complete guide for installing and configuring Aliyun CLI.
> **Aliyun CLI 3.3.3+**: Supports installing and using all published Alibaba Cloud product plugins. Make sure to upgrade to 3.3.3 or later for full plugin ecosystem coverage.
## Installation
### macOS
**Using Homebrew (Recommended)**
```bash
brew install aliyun-cli
# Upgrade to latest
brew upgrade aliyun-cli
# Verify version (>= 3.3.3)
aliyun version
```
**Using Binary**
```bash
# Download
wget https://aliyuncli.alicdn.com/aliyun-cli-macosx-latest-amd64.tgz
# Extract
tar -xzf aliyun-cli-macosx-latest-amd64.tgz
# Move to PATH
sudo mv aliyun /usr/local/bin/
# Verify
aliyun version
```
### Linux
**Debian/Ubuntu**
```bash
# Download
wget https://aliyuncli.alicdn.com/aliyun-cli-linux-latest-amd64.tgz
# Extract and install
tar -xzf aliyun-cli-linux-latest-amd64.tgz
sudo mv aliyun /usr/local/bin/
# Verify
aliyun version
```
**CentOS/RHEL**
```bash
# Download
wget https://aliyuncli.alicdn.com/aliyun-cli-linux-latest-amd64.tgz
# Extract and install
tar -xzf aliyun-cli-linux-latest-amd64.tgz
sudo mv aliyun /usr/local/bin/
# Verify
aliyun version
```
**ARM64 Architecture**
```bash
# Download ARM64 version
wget https://aliyuncli.alicdn.com/aliyun-cli-linux-latest-arm64.tgz
# Extract and install
tar -xzf aliyun-cli-linux-latest-arm64.tgz
sudo mv aliyun /usr/local/bin/
```
### Windows
**Using Binary**
1. Download from: https://aliyuncli.alicdn.com/aliyun-cli-windows-latest-amd64.zip
2. Extract the ZIP file
3. Add the directory to your PATH environment variable
4. Open new Command Prompt or PowerShell
5. Verify: `aliyun version`
**Using PowerShell**
```powershell
# Download
Invoke-WebRequest -Uri "https://aliyuncli.alicdn.com/aliyun-cli-windows-latest-amd64.zip" -OutFile "aliyun-cli.zip"
# Extract
Expand-Archive -Path aliyun-cli.zip -DestinationPath C:\aliyun-cli
# Add to PATH (requires admin privileges)
$env:Path += ";C:\aliyun-cli"
[Environment]::SetEnvironmentVariable("Path", $env:Path, [System.EnvironmentVariableTarget]::Machine)
# Verify
aliyun version
```
## Configuration
### Quick Start
```bash
aliyun configure set \
--mode AK \
--access-key-id <your-access-key-id> \
--access-key-secret <your-access-key-secret> \
--region cn-hangzhou
```
All `aliyun configure` commands support non-interactive flags, which is the recommended approach —
it works in scripts, CI/CD pipelines, and agent-driven automation without hanging on stdin prompts.
**Where to Get Access Keys**
1. Log in to Aliyun Console: https://ram.console.aliyun.com/
2. Navigate to: AccessKey Management
3. Create a new AccessKey pair
4. Save the secret immediately — it's only shown once
### Configuration Modes
Aliyun CLI supports 6 authentication modes. All examples below use non-interactive flags.
#### 1. AK Mode (Access Key)
Most common mode for personal accounts and scripts.
```bash
aliyun configure set \
--mode AK \
--access-key-id LTAI5tXXXXXXXX \
--access-key-secret 8dXXXXXXXXXXXXXXXXXXXXXXXX \
--region cn-hangzhou
```
Configuration is stored in `~/.aliyun/config.json`:
```json
{
"current": "default",
"profiles": [
{
"name": "default",
"mode": "AK",
"access_key_id": "LTAI5tXXXXXXXX",
"access_key_secret": "8dXXXXXXXXXXXXXXXXXXXXXXXX",
"region_id": "cn-hangzhou",
"output_format": "json",
"language": "en"
}
]
}
```
#### 2. StsToken Mode (Temporary Credentials)
For short-lived access (tokens expire in 1-12 hours).
```bash
aliyun configure set \
--mode StsToken \
--access-key-id LTAI5tXXXXXXXX \
--access-key-secret 8dXXXXXXXXXXXXXXXXXXXXXXXX \
--sts-token v1.0:XXXXXXXXXXXXXXXX \
--region cn-hangzhou
```
Use cases: CI/CD pipelines, temporary access for external contractors, cross-account access.
#### 3. RamRoleArn Mode (Assume RAM Role)
Assume a RAM role for elevated or cross-account access.
```bash
aliyun configure set \
--mode RamRoleArn \
--access-key-id LTAI5tXXXXXXXX \
--access-key-secret 8dXXXXXXXXXXXXXXXXXXXXXXXX \
--ram-role-arn acs:ram::123456789012:role/AdminRole \
--role-session-name my-session \
--region cn-hangzhou
```
Use cases: cross-account resource access, temporary elevated privileges, role-based access control.
#### 4. EcsRamRole Mode (ECS Instance RAM Role)
Use the RAM role attached to an ECS instance — no credentials needed.
```bash
aliyun configure set \
--mode EcsRamRole \
--ram-role-name MyEcsRole \
--region cn-hangzhou
```
Requirements: must be running on an ECS instance with a RAM role attached.
Use cases: scripts and automation running on ECS instances.
#### 5. RsaKeyPair Mode (RSA Key Pair)
Use RSA key pair for authentication (generate key pair in Aliyun Console first).
```bash
aliyun configure set \
--mode RsaKeyPair \
--private-key /path/to/private-key.pem \
--key-pair-name my-key-pair \
--region cn-hangzhou
```
#### 6. RamRoleArnWithEcs Mode (ECS + RAM Role)
Combine ECS instance role with RAM role assumption for cross-account access from ECS.
```bash
aliyun configure set \
--mode RamRoleArnWithEcs \
--ram-role-name MyEcsRole \
--ram-role-arn acs:ram::123456789012:role/TargetRole \
--role-session-name my-session \
--region cn-hangzhou
```
### Environment Variables
**Highest priority** - overrides config file
**Access Key Mode**
```bash
export ALIBABA_CLOUD_ACCESS_KEY_ID=your_access_key_id
export ALIBABA_CLOUD_ACCESS_KEY_SECRET=your_access_key_secret
export ALIBABA_CLOUD_REGION_ID=cn-hangzhou
```
**STS Token Mode**
```bash
export ALIBABA_CLOUD_ACCESS_KEY_ID=your_access_key_id
export ALIBABA_CLOUD_ACCESS_KEY_SECRET=your_access_key_secret
export ALIBABA_CLOUD_SECURITY_TOKEN=your_sts_token
export ALIBABA_CLOUD_REGION_ID=cn-hangzhou
```
**ECS RAM Role Mode**
```bash
export ALIBABA_CLOUD_ECS_METADATA=role_name
```
**Use Case**:
- CI/CD pipelines
- Docker containers
- Temporary credential override
### Managing Multiple Profiles
**Create Named Profiles**
```bash
aliyun configure set --profile projectA \
--mode AK \
--access-key-id LTAI5tAAAAAAAA \
--access-key-secret 8dAAAAAAAAAAAAAAAAAAAAAAAA \
--region cn-hangzhou
aliyun configure set --profile projectB \
--mode AK \
--access-key-id LTAI5tBBBBBBBB \
--access-key-secret 8dBBBBBBBBBBBBBBBBBBBBBBBB \
--region cn-shanghai
```
**Use Specific Profile**
```bash
aliyun ecs describe-instances --profile projectA
export ALIBABA_CLOUD_PROFILE=projectA
aliyun ecs describe-instances # Uses projectA
```
**List and Switch Profiles**
```bash
aliyun configure list # List all profiles
aliyun configure set --current projectA # Switch default profile
```
### Credential Priority
Credentials are loaded in this order (first found wins):
1. **Command-line flag**: `--profile <name>`
2. **Environment variable**: `ALIBABA_CLOUD_PROFILE`
3. **Environment credentials**: `ALIBABA_CLOUD_ACCESS_KEY_ID`, etc.
4. **Configuration file**: `~/.aliyun/config.json` (current profile)
5. **ECS Instance RAM Role**: If running on ECS with attached role
## Verification
### Test Authentication
```bash
# Basic test - list regions
aliyun ecs describe-regions
# Expected output: JSON array of regions
```
**If successful**, you'll see:
```json
{
"Regions": {
"Region": [
{
"RegionId": "cn-hangzhou",
"RegionEndpoint": "ecs.cn-hangzhou.aliyuncs.com",
"LocalName": "华东 1(杭州)"
},
...
]
},
"RequestId": "..."
}
```
**If failed**, you'll see error messages:
- `InvalidAccessKeyId.NotFound` - Wrong Access Key ID
- `SignatureDoesNotMatch` - Wrong Access Key Secret
- `InvalidSecurityToken.Expired` - STS token expired (for StsToken mode)
- `Forbidden.RAM` - Insufficient permissions
### Debug Configuration
```bash
# Show current configuration
aliyun configure get
# Test with debug logging
aliyun ecs describe-regions --log-level=debug
# Check credential provider
aliyun configure get mode
```
## Security Best Practices
### 1. Use RAM Users (Not Root Account)
❌ **Don't**: Use Aliyun root account credentials
✅ **Do**: Create RAM users with specific permissions
```bash
# Create RAM user in console
# Attach only necessary policies
# Use RAM user's access keys
```
### 2. Principle of Least Privilege
Grant only the minimum permissions needed:
```bash
# Example: Read-only ECS access
# Attach policy: AliyunECSReadOnlyAccess
```
### 3. Rotate Access Keys Regularly
```bash
# Create new access key in RAM Console, then update configuration
aliyun configure set --access-key-id NEW_KEY --access-key-secret NEW_SECRET
# Delete old access key from console
```
### 4. Use STS Tokens for Temporary Access
```bash
aliyun configure set --mode StsToken \
--access-key-id XXXX --access-key-secret XXXX \
--sts-token XXXX --region cn-hangzhou
```
### 5. Use ECS RAM Roles When Possible
```bash
aliyun configure set --mode EcsRamRole --ram-role-name MyRole --region cn-hangzhou
```
### 6. Never Commit Credentials
```bash
# Add to .gitignore
echo "~/.aliyun/config.json" >> .gitignore
# Use environment variables in CI/CD instead
```
### 7. Secure Config File
```bash
# Restrict permissions
chmod 600 ~/.aliyun/config.json
```
## Troubleshooting
### Issue: Command Not Found
```bash
# Check installation
which aliyun
# Check PATH
echo $PATH
# Reinstall or add to PATH
```
### Issue: Authentication Failed
```bash
# Verify configuration
aliyun configure get
# Test with debug
aliyun ecs describe-regions --log-level=debug
# Check credentials in console
# Verify access key is active
```
### Issue: Permission Denied
```bash
# Error: Forbidden.RAM
# Check RAM user permissions
# Attach necessary policies in RAM console
# Example: AliyunECSFullAccess for ECS operations
```
### Issue: STS Token Expired
```bash
# Error: InvalidSecurityToken.Expired
# Reconfigure with new token
aliyun configure set --mode StsToken \
--access-key-id XXXX --access-key-secret XXXX \
--sts-token NEW_TOKEN --region cn-hangzhou
```
### Issue: Wrong Region
```bash
# Some resources may not exist in the specified region
# Check available regions
aliyun ecs describe-regions
# Update default region
aliyun configure set region cn-shanghai
```
## Advanced Configuration
### Custom Endpoint
```bash
# Use custom or private endpoint
export ALIBABA_CLOUD_ECS_ENDPOINT=ecs-vpc.cn-hangzhou.aliyuncs.com
```
### Proxy Settings
```bash
# HTTP proxy
export HTTP_PROXY=http://proxy.example.com:8080
export HTTPS_PROXY=http://proxy.example.com:8080
# No proxy for specific domains
export NO_PROXY=localhost,127.0.0.1,.aliyuncs.com
```
### Timeout Settings
```bash
# Connection timeout (default: 10s)
export ALIBABA_CLOUD_CONNECT_TIMEOUT=30
# Read timeout (default: 10s)
export ALIBABA_CLOUD_READ_TIMEOUT=30
```
## Next Steps
After installation and configuration:
1. **Install plugins** for services you need (v3.3.3+ supports all published product plugins):
```bash
aliyun plugin install --names ecs vpc rds
# List all available plugins
aliyun plugin list-remote
```
2. **Explore commands**:
```bash
aliyun ecs --help
aliyun fc --help
```
3. **Read documentation**:
- [Command Syntax Guide](./command-syntax.md)
- [Global Flags Reference](./global-flags.md)
- [Common Scenarios](./common-scenarios.md)
## References
- Official Documentation: https://help.aliyun.com/zh/cli/
- RAM Console: https://ram.console.aliyun.com/
- Access Key Management: https://ram.console.aliyun.com/manage/ak
- Plugin Repository: https://github.com/aliyun/aliyun-cli
FILE:references/ram-policies.md
# RAM Policies for alibabacloud-find-skills
This document lists all RAM permissions required by the `alibabacloud-find-skills` skill.
## Required Permissions
The skill uses the following AgentExplorer service APIs:
| API Operation | Description | Permission Required |
|---------------|-------------|---------------------|
| `ListCategories` | List all available skill categories | `agentexplorer:ListCategories` |
| `SearchSkills` | Search skills by keyword and category | `agentexplorer:SearchSkills` |
| `GetSkillContent` | Retrieve detailed skill content | `agentexplorer:GetSkillContent` |
## Minimal RAM Policy
```json
{
"Version": "1",
"Statement": [
{
"Effect": "Allow",
"Action": [
"agentexplorer:ListCategories",
"agentexplorer:SearchSkills",
"agentexplorer:GetSkillContent"
],
"Resource": "*"
}
]
}
```
## Policy Explanation
### agentexplorer:ListCategories
- **Purpose**: Retrieve the complete catalog of skill categories and subcategories
- **Resource**: Public catalog, no resource-specific restrictions
- **Risk Level**: Low (read-only, public data)
### agentexplorer:SearchSkills
- **Purpose**: Query skills based on keywords, categories, or filters
- **Resource**: Public skills repository, no resource-specific restrictions
- **Risk Level**: Low (read-only, public data)
### agentexplorer:GetSkillContent
- **Purpose**: Fetch the full markdown content of a specific skill
- **Resource**: Public skill content, no resource-specific restrictions
- **Risk Level**: Low (read-only, public data)
## How to Apply This Policy
### Option 1: Via Alibaba Cloud Console
1. Log in to [RAM Console](https://ram.console.aliyun.com/)
2. Navigate to **Permissions** > **Policies**
3. Click **Create Policy**
4. Select **JSON** tab
5. Paste the minimal RAM policy JSON above
6. Name the policy (e.g., `AgentExplorerReadOnly`)
7. Click **OK**
8. Attach the policy to your RAM user or role
### Option 2: Via Aliyun CLI
```bash
# Create the policy
aliyun ram create-policy \
--policy-name AgentExplorerReadOnly \
--policy-document '{
"Version": "1",
"Statement": [{
"Effect": "Allow",
"Action": [
"agentexplorer:ListCategories",
"agentexplorer:SearchSkills",
"agentexplorer:GetSkillContent"
],
"Resource": "*"
}]
}' \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-find-skills
# Attach to RAM user
aliyun ram attach-policy-to-user \
--policy-name AgentExplorerReadOnly \
--policy-type Custom \
--user-name <your-ram-user-name> \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-find-skills
```
## Permission Verification
To verify that your account has the required permissions:
```bash
# Test ListCategories permission
aliyun agentexplorer list-categories --user-agent AlibabaCloud-Agent-Skills/alibabacloud-find-skills
# Test SearchSkills permission
aliyun agentexplorer search-skills --keyword "test" --user-agent AlibabaCloud-Agent-Skills/alibabacloud-find-skills
# Test GetSkillContent permission
aliyun agentexplorer get-skill-content --skill-name "example-skill" --user-agent AlibabaCloud-Agent-Skills/alibabacloud-find-skills
```
If any command returns a permission error (e.g., `403 Forbidden`, `NoPermission`), you need to apply the RAM policy above.
## Common Permission Errors
### Error: "User not authorized to operate on the specified resource"
**Cause**: Missing one or more required permissions.
**Solution**: Apply the complete RAM policy shown above.
### Error: "The specified action is not found"
**Cause**: AgentExplorer service may not be available in your region or account type.
**Solution**: Verify that you're using a supported account type and region.
## Security Best Practices
1. **Read-only access**: These permissions only allow reading public data, no write operations
2. **Minimal scope**: Only grants access to AgentExplorer APIs, not other services
3. **No resource restrictions needed**: Skills catalog is public, no need for resource-level filtering
4. **Suitable for automation**: Safe to use in CI/CD pipelines or automated scripts
5. **No sensitive data**: Skills content is public documentation, no confidential information
## Permission Escalation
This skill does **not** require any additional permissions beyond the minimal set listed above. If you encounter permission errors after applying this policy, it may indicate:
- Account-level restrictions (contact your administrator)
- Service availability issues (check Alibaba Cloud service status)
- Incorrect policy attachment (verify policy is attached to correct user/role)
## Related Documentation
- [Alibaba Cloud RAM User Guide](https://www.alibabacloud.com/help/ram)
- [RAM Policy Syntax](https://www.alibabacloud.com/help/ram/user-guide/policy-structure-and-syntax)
- [AgentExplorer Service Documentation](https://www.alibabacloud.com/help/agentexplorer)
FILE:references/related-commands.md
# Related CLI Commands
Complete reference for all Aliyun CLI commands used in the `alibabacloud-find-skills` skill.
## Command Summary
| Command | Purpose | Required Parameters |
|---------|---------|---------------------|
| `aliyun agentexplorer list-categories` | List all skill categories | None |
| `aliyun agentexplorer search-skills` | Search for skills | None (keyword or category-code recommended) |
| `aliyun agentexplorer get-skill-content` | Get skill details | `--skill-name` (required) |
| `aliyun plugin install` | Install CLI plugins | `--names` (required) |
| `aliyun configure list` | Check credential configuration | None |
| `aliyun version` | Check CLI version | None |
---
## 1. aliyun agentexplorer list-categories
**Description**: List all available skill categories and subcategories.
**Syntax**:
```bash
aliyun agentexplorer list-categories [flags]
```
**Parameters**: None required.
**Common Flags**:
- `--user-agent AlibabaCloud-Agent-Skills/alibabacloud-find-skills` — **Required**: Identify requests from this skill
- `--cli-query <jmespath>` — Filter output using JMESPath expression
- `-q, --quiet` — Suppress output
**Example Usage**:
```bash
# List all categories
aliyun agentexplorer list-categories --user-agent AlibabaCloud-Agent-Skills/alibabacloud-find-skills
# List categories with JMESPath filtering
aliyun agentexplorer list-categories \
--cli-query "categories[].categoryName" \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-find-skills
```
**Output Structure**:
```json
{
"categories": [
{
"categoryCode": "computing",
"categoryName": "计算",
"subCategories": [
{
"categoryCode": "ecs",
"categoryName": "云服务器 ECS"
}
]
}
]
}
```
---
## 2. aliyun agentexplorer search-skills
**Description**: Search for Alibaba Cloud Agent Skills by keyword, category, or both.
**Syntax**:
```bash
aliyun agentexplorer search-skills [flags]
```
**Parameters**:
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `--keyword` | string | No | Search keyword (product name, feature, description) |
| `--category-code` | string | No | Category code filter (comma-separated for multiple) |
| `--max-results` | int | No | Maximum results per page (1-100, default: 20) |
| `--next-token` | string | No | Pagination token from previous response |
| `--skip` | int | No | Number of items to skip |
**Common Flags**:
- `--user-agent AlibabaCloud-Agent-Skills/alibabacloud-find-skills` — **Required**: Identify requests from this skill
- `--cli-query <jmespath>` — Filter output using JMESPath expression
- `--pager` — Auto-merge all pages
- `-q, --quiet` — Suppress output
**Example Usage**:
```bash
# Search by keyword only
aliyun agentexplorer search-skills \
--keyword "ECS" \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-find-skills
# Search by category only
aliyun agentexplorer search-skills \
--category-code "computing" \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-find-skills
# Search by subcategory (dot notation)
aliyun agentexplorer search-skills \
--category-code "computing.ecs" \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-find-skills
# Combined keyword and category
aliyun agentexplorer search-skills \
--keyword "backup" \
--category-code "database.rds" \
--max-results 10 \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-find-skills
# Multiple categories
aliyun agentexplorer search-skills \
--category-code "computing,database" \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-find-skills
# Paginated search (page 2)
aliyun agentexplorer search-skills \
--keyword "monitoring" \
--max-results 20 \
--next-token "<token-from-previous-response>" \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-find-skills
# Skip first N results
aliyun agentexplorer search-skills \
--keyword "OSS" \
--skip 10 \
--max-results 20 \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-find-skills
# Filter results with JMESPath
aliyun agentexplorer search-skills \
--keyword "ECS" \
--cli-query "skills[].skillName" \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-find-skills
```
**Output Structure**:
```json
{
"skills": [
{
"skillName": "alibabacloud-ecs-batch-command",
"displayName": "ECS 批量命令执行",
"description": "批量在多台 ECS 实例上执行命令",
"categoryCode": "computing",
"categoryName": "计算",
"subCategoryCode": "ecs",
"subCategoryName": "云服务器 ECS",
"installCount": 245,
"likeCount": 18
}
],
"totalCount": 100,
"nextToken": "eyJwYWdlIjoyfQ=="
}
```
---
## 3. aliyun agentexplorer get-skill-content
**Description**: Retrieve the complete markdown content of a specific skill.
**Syntax**:
```bash
aliyun agentexplorer get-skill-content --skill-name <name> [flags]
```
**Parameters**:
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `--skill-name` | string | **Yes** | Unique skill identifier (from search results) |
**Common Flags**:
- `--user-agent AlibabaCloud-Agent-Skills/alibabacloud-find-skills` — **Required**: Identify requests from this skill
- `--cli-query <jmespath>` — Filter output using JMESPath expression
- `-q, --quiet` — Suppress output
**Example Usage**:
```bash
# Get skill content
aliyun agentexplorer get-skill-content \
--skill-name "alibabacloud-ecs-batch-command" \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-find-skills
# Get only the description field
aliyun agentexplorer get-skill-content \
--skill-name "alibabacloud-ecs-batch-command" \
--cli-query "description" \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-find-skills
```
**Output Structure**:
```json
{
"skillName": "alibabacloud-ecs-batch-command",
"displayName": "ECS 批量命令执行",
"description": "批量在多台 ECS 实例上执行命令",
"content": "---\nname: alibabacloud-ecs-batch-command\n...",
"categoryCode": "computing",
"categoryName": "计算",
"subCategoryCode": "ecs",
"subCategoryName": "云服务器 ECS",
"installCount": 245,
"likeCount": 18,
"createTime": "2024-01-15T10:30:00Z",
"updateTime": "2024-03-20T14:45:00Z"
}
```
---
## 4. aliyun plugin install
**Description**: Install Aliyun CLI plugins.
**Syntax**:
```bash
aliyun plugin install --names <plugin-name> [flags]
```
**Parameters**:
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `--names` | string | **Yes** | Plugin name to install |
**Example Usage**:
```bash
# Install agentexplorer plugin
aliyun plugin install --names aliyun-cli-agentexplorer
# Install multiple plugins (comma-separated)
aliyun plugin install --names aliyun-cli-agentexplorer,aliyun-cli-another-plugin
```
---
## 5. aliyun configure list
**Description**: List all configured credentials and profiles.
**Syntax**:
```bash
aliyun configure list [flags]
```
**Parameters**: None required.
**Common Flags**:
- `--user-agent AlibabaCloud-Agent-Skills/alibabacloud-find-skills` — **Required**: Identify requests from this skill
**Example Usage**:
```bash
# List all profiles
aliyun configure list --user-agent AlibabaCloud-Agent-Skills/alibabacloud-find-skills
```
**Output Example**:
```
Profile | Credential | Valid | Region | Language
--------- | ------------------ | ------- | ---------------- | --------
default * | AK:***abc | Valid | cn-hangzhou | en
profile1 | STS:***def | Valid | cn-beijing | zh
```
---
## 6. aliyun version
**Description**: Display Aliyun CLI version.
**Syntax**:
```bash
aliyun version
```
**Parameters**: None.
**Example Usage**:
```bash
aliyun version
```
**Output Example**:
```
3.3.2
```
---
## 7. aliyun configure set
**Description**: Configure CLI settings (used for enabling auto plugin install).
**Syntax**:
```bash
aliyun configure set [flags]
```
**Common Flags**:
- `--auto-plugin-install <bool>` — Enable/disable automatic plugin installation
**Example Usage**:
```bash
# Enable automatic plugin installation
aliyun configure set --auto-plugin-install true
```
---
## Advanced Usage Patterns
### Pattern 1: Search with Auto-pagination
```bash
# Automatically fetch all pages
aliyun agentexplorer search-skills \
--keyword "monitoring" \
--pager \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-find-skills
```
### Pattern 2: Filter Output with JMESPath
```bash
# Get only skill names from search results
aliyun agentexplorer search-skills \
--keyword "ECS" \
--cli-query "skills[].skillName" \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-find-skills
# Get skills with install count > 100
aliyun agentexplorer search-skills \
--keyword "ECS" \
--cli-query "skills[?installCount > \`100\`]" \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-find-skills
```
### Pattern 3: Hierarchical Category Search
```bash
# Search all computing skills
aliyun agentexplorer search-skills \
--category-code "computing" \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-find-skills
# Search only ECS skills (computing.ecs)
aliyun agentexplorer search-skills \
--category-code "computing.ecs" \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-find-skills
```
### Pattern 4: Multi-category Search
```bash
# Search across multiple top-level categories
aliyun agentexplorer search-skills \
--category-code "computing,database,storage" \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-find-skills
# Search across multiple subcategories
aliyun agentexplorer search-skills \
--category-code "computing.ecs,database.rds,storage.oss" \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-find-skills
```
---
## Troubleshooting Commands
### Check Plugin Installation
```bash
# List installed plugins
aliyun plugin list
# Check if agentexplorer is installed
aliyun plugin list | grep agentexplorer
```
### Verify Credentials
```bash
# Check if credentials are configured
aliyun configure list --user-agent AlibabaCloud-Agent-Skills/alibabacloud-find-skills
# Test API access
aliyun agentexplorer list-categories --user-agent AlibabaCloud-Agent-Skills/alibabacloud-find-skills
```
### Debug Mode
```bash
# Enable debug logging
aliyun agentexplorer search-skills \
--keyword "ECS" \
--log-level DEBUG \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-find-skills
```
### Dry Run Mode
```bash
# Preview request without sending
aliyun agentexplorer search-skills \
--keyword "ECS" \
--cli-dry-run \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-find-skills
```
---
## Command Comparison Table
| Task | Command | Key Parameters |
|------|---------|----------------|
| Browse all categories | `list-categories` | None |
| Search by keyword | `search-skills` | `--keyword` |
| Search by category | `search-skills` | `--category-code` |
| Combined search | `search-skills` | `--keyword`, `--category-code` |
| Get skill details | `get-skill-content` | `--skill-name` |
| Paginate results | `search-skills` | `--max-results`, `--next-token` |
| Install plugin | `plugin install` | `--names` |
| Check credentials | `configure list` | None |
---
## Notes
- **User-Agent Required**: All `aliyun agentexplorer` commands MUST include `--user-agent AlibabaCloud-Agent-Skills/alibabacloud-find-skills`
- **Plugin Mode**: Commands use plugin mode format (lowercase with hyphens)
- **Pagination**: Use `--next-token` from response for subsequent pages
- **Category Codes**: Use dot notation for subcategories (e.g., `computing.ecs`)
- **Multiple Values**: Comma-separate for multiple category codes
- **JMESPath**: Use `--cli-query` for client-side filtering
FILE:references/verification-method.md
# Verification Methods
This document provides detailed verification steps for each workflow in the `alibabacloud-find-skills` skill.
## Overview
After executing each workflow, verify success by checking:
1. Command exit code (0 = success)
2. Response structure matches expected format
3. Data content is valid and non-empty
4. Appropriate error handling for edge cases
---
## Workflow 1: Search Skills by Keyword
### Success Criteria
✅ **Command executes successfully**
```bash
aliyun agentexplorer search-skills \
--keyword "ECS" \
--max-results 20 \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-find-skills
echo "Exit code: $?" # Should be 0
```
✅ **Response contains expected fields**
```bash
aliyun agentexplorer search-skills \
--keyword "ECS" \
--cli-query "skills[0].skillName" \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-find-skills
# Should return a valid skill name, not null
```
✅ **Skills array is not empty** (when results exist)
```bash
aliyun agentexplorer search-skills \
--keyword "ECS" \
--cli-query "length(skills)" \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-find-skills
# Should return a number > 0
```
✅ **Each skill has required fields**
- `skillName` — Non-empty string
- `displayName` — Non-empty string
- `description` — Non-empty string
- `categoryName` — Non-empty string
- `installCount` — Non-negative integer
- `likeCount` — Non-negative integer
### Verification Script
```bash
#!/bin/bash
KEYWORD="ECS"
echo "=== Verifying Search Skills by Keyword ==="
# Execute search
RESULT=$(aliyun agentexplorer search-skills \
--keyword "$KEYWORD" \
--max-results 5 \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-find-skills 2>&1)
EXIT_CODE=$?
# Check exit code
if [ $EXIT_CODE -eq 0 ]; then
echo "✅ Command executed successfully (exit code: $EXIT_CODE)"
else
echo "❌ Command failed (exit code: $EXIT_CODE)"
echo "$RESULT"
exit 1
fi
# Check if result contains skills array
if echo "$RESULT" | grep -q '"skills"'; then
echo "✅ Response contains 'skills' array"
else
echo "❌ Response missing 'skills' array"
exit 1
fi
# Check skill count
SKILL_COUNT=$(echo "$RESULT" | grep -o '"skillName"' | wc -l)
if [ $SKILL_COUNT -gt 0 ]; then
echo "✅ Found $SKILL_COUNT skills"
else
echo "⚠️ No skills found for keyword '$KEYWORD'"
fi
echo "=== Verification Complete ==="
```
---
## Workflow 2: Browse Skills by Category
### Success Criteria
✅ **List categories succeeds**
```bash
aliyun agentexplorer list-categories \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-find-skills
echo "Exit code: $?" # Should be 0
```
✅ **Categories structure is valid**
```bash
aliyun agentexplorer list-categories \
--cli-query "categories[0].categoryCode" \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-find-skills
# Should return a valid category code
```
✅ **Search by category returns filtered results**
```bash
aliyun agentexplorer search-skills \
--category-code "computing" \
--cli-query "skills[0].categoryCode" \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-find-skills
# Should return "computing"
```
### Verification Script
```bash
#!/bin/bash
echo "=== Verifying Browse Skills by Category ==="
# Step 1: List categories
echo "Step 1: Listing categories..."
CATEGORIES=$(aliyun agentexplorer list-categories \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-find-skills 2>&1)
if [ $? -eq 0 ]; then
echo "✅ list-categories succeeded"
else
echo "❌ list-categories failed"
echo "$CATEGORIES"
exit 1
fi
# Extract first category code
CATEGORY_CODE=$(echo "$CATEGORIES" | grep -o '"categoryCode":"[^"]*"' | head -1 | cut -d'"' -f4)
if [ -n "$CATEGORY_CODE" ]; then
echo "✅ Found category code: $CATEGORY_CODE"
else
echo "❌ No category codes found"
exit 1
fi
# Step 2: Search by category
echo "Step 2: Searching skills in category '$CATEGORY_CODE'..."
SKILLS=$(aliyun agentexplorer search-skills \
--category-code "$CATEGORY_CODE" \
--max-results 5 \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-find-skills 2>&1)
if [ $? -eq 0 ]; then
echo "✅ search-skills by category succeeded"
else
echo "❌ search-skills by category failed"
echo "$SKILLS"
exit 1
fi
# Verify results belong to the category
if echo "$SKILLS" | grep -q "\"categoryCode\":\"$CATEGORY_CODE\""; then
echo "✅ Results correctly filtered by category"
else
echo "⚠️ Results may not be filtered correctly"
fi
echo "=== Verification Complete ==="
```
---
## Workflow 3: Get Skill Details
### Success Criteria
✅ **Command succeeds with valid skill name**
```bash
aliyun agentexplorer get-skill-content \
--skill-name "alibabacloud-ecs-batch-command" \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-find-skills
echo "Exit code: $?" # Should be 0
```
✅ **Response contains content field**
```bash
aliyun agentexplorer get-skill-content \
--skill-name "alibabacloud-ecs-batch-command" \
--cli-query "content" \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-find-skills
# Should return non-empty markdown content
```
✅ **Content is valid markdown**
- Starts with `---` (YAML frontmatter)
- Contains `name:` field
- Contains `description:` field
### Verification Script
```bash
#!/bin/bash
echo "=== Verifying Get Skill Details ==="
# First, search for a skill to get a valid skill name
echo "Step 1: Finding a valid skill name..."
SEARCH_RESULT=$(aliyun agentexplorer search-skills \
--keyword "ECS" \
--max-results 1 \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-find-skills 2>&1)
SKILL_NAME=$(echo "$SEARCH_RESULT" | grep -o '"skillName":"[^"]*"' | head -1 | cut -d'"' -f4)
if [ -z "$SKILL_NAME" ]; then
echo "❌ Could not find a valid skill name"
exit 1
fi
echo "✅ Found skill name: $SKILL_NAME"
# Step 2: Get skill content
echo "Step 2: Retrieving skill content..."
CONTENT=$(aliyun agentexplorer get-skill-content \
--skill-name "$SKILL_NAME" \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-find-skills 2>&1)
if [ $? -eq 0 ]; then
echo "✅ get-skill-content succeeded"
else
echo "❌ get-skill-content failed"
echo "$CONTENT"
exit 1
fi
# Verify content field exists and is not empty
if echo "$CONTENT" | grep -q '"content"'; then
echo "✅ Response contains 'content' field"
else
echo "❌ Response missing 'content' field"
exit 1
fi
# Extract content and check for markdown frontmatter
MARKDOWN_CONTENT=$(echo "$CONTENT" | grep -o '"content":"[^"]*"' | cut -d'"' -f4)
if echo "$MARKDOWN_CONTENT" | grep -q '---'; then
echo "✅ Content appears to be valid markdown"
else
echo "⚠️ Content may not be valid markdown"
fi
echo "=== Verification Complete ==="
```
---
## Workflow 4: Install a Skill
### Success Criteria
✅ **Installation command succeeds**
```bash
npx skills add https://github.com/aliyun/alibabacloud-aiops-skills --skill <skill-name>
echo "Exit code: $?" # Should be 0
```
✅ **Skill appears in Claude Code skills list**
```bash
# Verify skill is installed (implementation-specific)
# Check in Claude Code UI or skills directory
```
### Verification Steps
1. **Before Installation**: Check that skill is not already installed
2. **During Installation**: Monitor output for errors
3. **After Installation**: Verify skill is available
4. **Test Skill**: Trigger the skill to ensure it works
### Manual Verification Checklist
- [ ] Installation command completed without errors
- [ ] Skill appears in Claude Code skills list
- [ ] Skill can be triggered with appropriate keywords
- [ ] Skill loads successfully when triggered
- [ ] Skill's functions work as expected
---
## Workflow 5: Combined Search (Keyword + Category)
### Success Criteria
✅ **Combined search executes successfully**
```bash
aliyun agentexplorer search-skills \
--keyword "backup" \
--category-code "database.rds" \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-find-skills
echo "Exit code: $?" # Should be 0
```
✅ **Results match both filters**
- Each result's `categoryCode` or `subCategoryCode` matches the filter
- Each result's `displayName` or `description` contains keyword (case-insensitive)
### Verification Script
```bash
#!/bin/bash
KEYWORD="backup"
CATEGORY="database"
echo "=== Verifying Combined Search ==="
# Execute combined search
RESULT=$(aliyun agentexplorer search-skills \
--keyword "$KEYWORD" \
--category-code "$CATEGORY" \
--max-results 10 \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-find-skills 2>&1)
if [ $? -eq 0 ]; then
echo "✅ Combined search succeeded"
else
echo "❌ Combined search failed"
echo "$RESULT"
exit 1
fi
# Check if results contain the category
if echo "$RESULT" | grep -q "\"categoryCode\":\"$CATEGORY\""; then
echo "✅ Results correctly filtered by category '$CATEGORY'"
else
echo "⚠️ No results with category '$CATEGORY' found"
fi
# Count results
SKILL_COUNT=$(echo "$RESULT" | grep -o '"skillName"' | wc -l)
echo "Found $SKILL_COUNT skills matching both filters"
echo "=== Verification Complete ==="
```
---
## Workflow 6: Paginated Search
### Success Criteria
✅ **First page returns results and nextToken**
```bash
RESULT=$(aliyun agentexplorer search-skills \
--keyword "monitoring" \
--max-results 5 \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-find-skills)
echo "$RESULT" | grep -q '"nextToken"'
# Should find nextToken if more results exist
```
✅ **Second page uses nextToken correctly**
```bash
NEXT_TOKEN=$(echo "$RESULT" | grep -o '"nextToken":"[^"]*"' | cut -d'"' -f4)
aliyun agentexplorer search-skills \
--keyword "monitoring" \
--max-results 5 \
--next-token "$NEXT_TOKEN" \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-find-skills
# Should return different results
```
✅ **No duplicate results across pages**
### Verification Script
```bash
#!/bin/bash
KEYWORD="ECS"
PAGE_SIZE=5
echo "=== Verifying Paginated Search ==="
# Page 1
echo "Fetching page 1..."
PAGE1=$(aliyun agentexplorer search-skills \
--keyword "$KEYWORD" \
--max-results $PAGE_SIZE \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-find-skills 2>&1)
if [ $? -ne 0 ]; then
echo "❌ Page 1 fetch failed"
exit 1
fi
echo "✅ Page 1 fetched successfully"
# Extract nextToken
NEXT_TOKEN=$(echo "$PAGE1" | grep -o '"nextToken":"[^"]*"' | head -1 | cut -d'"' -f4)
if [ -z "$NEXT_TOKEN" ]; then
echo "⚠️ No nextToken found (may be last page)"
echo "=== Verification Complete ==="
exit 0
fi
echo "✅ Found nextToken: 0:20..."
# Page 2
echo "Fetching page 2..."
PAGE2=$(aliyun agentexplorer search-skills \
--keyword "$KEYWORD" \
--max-results $PAGE_SIZE \
--next-token "$NEXT_TOKEN" \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-find-skills 2>&1)
if [ $? -eq 0 ]; then
echo "✅ Page 2 fetched successfully"
else
echo "❌ Page 2 fetch failed"
exit 1
fi
# Check for different skill names
SKILLS_PAGE1=$(echo "$PAGE1" | grep -o '"skillName":"[^"]*"' | cut -d'"' -f4 | sort)
SKILLS_PAGE2=$(echo "$PAGE2" | grep -o '"skillName":"[^"]*"' | cut -d'"' -f4 | sort)
if [ "$SKILLS_PAGE1" != "$SKILLS_PAGE2" ]; then
echo "✅ Page 2 contains different results from page 1"
else
echo "⚠️ Pages may contain duplicate results"
fi
echo "=== Verification Complete ==="
```
---
## General Verification Checklist
Use this checklist after implementing any workflow:
### Command Execution
- [ ] Command exits with code 0 on success
- [ ] Command exits with non-zero code on error
- [ ] Error messages are clear and actionable
### Response Format
- [ ] Response is valid JSON
- [ ] Response contains expected top-level keys
- [ ] All required fields are present
- [ ] Field types match expected types (string, int, array, etc.)
### Data Validity
- [ ] String fields are non-empty when expected
- [ ] Numeric fields are non-negative
- [ ] Array fields contain valid elements
- [ ] Nested objects have correct structure
### Edge Cases
- [ ] Empty results handled gracefully (no error)
- [ ] Invalid parameters return appropriate errors
- [ ] Missing required parameters return clear error messages
- [ ] Pagination works correctly at boundaries
### User Experience
- [ ] Results are displayed in user-friendly format
- [ ] Tables align properly
- [ ] Important information is highlighted
- [ ] Next steps are clear to the user
---
## Automated Test Suite
Create a comprehensive test script:
```bash
#!/bin/bash
# Test suite for alibabacloud-find-skills
set -e # Exit on first error
echo "========================================"
echo " alibabacloud-find-skills Test Suite"
echo "========================================"
# Test 1: List Categories
echo -e "\n[Test 1] List Categories"
aliyun agentexplorer list-categories \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-find-skills \
--cli-query "categories[0].categoryCode" > /dev/null
echo "✅ PASS"
# Test 2: Search by Keyword
echo -e "\n[Test 2] Search by Keyword"
aliyun agentexplorer search-skills \
--keyword "ECS" \
--max-results 5 \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-find-skills \
--cli-query "skills[0].skillName" > /dev/null
echo "✅ PASS"
# Test 3: Search by Category
echo -e "\n[Test 3] Search by Category"
aliyun agentexplorer search-skills \
--category-code "computing" \
--max-results 5 \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-find-skills \
--cli-query "skills[0].categoryCode" > /dev/null
echo "✅ PASS"
# Test 4: Combined Search
echo -e "\n[Test 4] Combined Search"
aliyun agentexplorer search-skills \
--keyword "backup" \
--category-code "database" \
--max-results 5 \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-find-skills > /dev/null
echo "✅ PASS"
# Test 5: Get Skill Content
echo -e "\n[Test 5] Get Skill Content"
SKILL_NAME=$(aliyun agentexplorer search-skills \
--keyword "ECS" \
--max-results 1 \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-find-skills \
--cli-query "skills[0].skillName" 2>/dev/null | tr -d '"' | tr -d '\n')
if [ -n "$SKILL_NAME" ]; then
aliyun agentexplorer get-skill-content \
--skill-name "$SKILL_NAME" \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-find-skills \
--cli-query "content" > /dev/null
echo "✅ PASS"
else
echo "⚠️ SKIP (no skills found)"
fi
# Test 6: Pagination
echo -e "\n[Test 6] Pagination"
RESULT=$(aliyun agentexplorer search-skills \
--keyword "ECS" \
--max-results 2 \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-find-skills 2>/dev/null)
if echo "$RESULT" | grep -q '"nextToken"'; then
echo "✅ PASS"
else
echo "⚠️ SKIP (no pagination needed)"
fi
echo -e "\n========================================"
echo " All Tests Completed Successfully!"
echo "========================================"
```
Save as `test-skill.sh` and run with:
```bash
chmod +x test-skill.sh
./test-skill.sh
```
---
## Troubleshooting Verification Failures
### Issue: Command returns non-zero exit code
**Check**:
1. Credentials configured: `aliyun configure list --user-agent AlibabaCloud-Agent-Skills/alibabacloud-find-skills`
2. Plugin installed: `aliyun plugin list | grep agentexplorer`
3. CLI version: `aliyun version` (should be >= 3.3.3)
4. Network connectivity: `ping api.aliyun.com`
### Issue: Response missing expected fields
**Check**:
1. CLI version is up-to-date
2. Plugin version is latest: `aliyun plugin list`
3. API version changes (check official docs)
### Issue: No results returned
**Check**:
1. Keyword spelling
2. Category code validity
3. Try broader search terms
4. Check if any skills exist in category
---
## Success Metrics
Track these metrics to assess skill effectiveness:
| Metric | Target | Measurement |
| ------------------------- | ----------- | ---------------------------------------- |
| Command success rate | > 99% | Exit code 0 / total commands |
| Average response time | < 3 seconds | Time to receive response |
| Empty results rate | < 20% | Searches with 0 results / total searches |
| Installation success rate | > 95% | Successful installs / install attempts |
| User satisfaction | > 4/5 | User feedback rating |
---
## Continuous Monitoring
Set up periodic checks:
```bash
# Cron job example (run daily at 2 AM)
0 2 * * * /path/to/test-skill.sh >> /var/log/skill-tests.log 2>&1
```
Monitor for:
- API availability
- Response time degradation
- New error patterns
- Skill catalog updates
FILE:scripts/validate-skill.sh
#!/bin/bash
# Validation script for alibabacloud-find-skills
set -e
echo "========================================"
echo " Skill Validation Script"
echo "========================================"
echo ""
# Color codes
GREEN='\033[0;32m'
RED='\033[0;31m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color
# Check 1: Aliyun CLI version
echo "Check 1: Aliyun CLI Version"
CLI_VERSION=$(aliyun version 2>/dev/null || echo "0.0.0")
REQUIRED_VERSION="3.3.3"
if [ "$(printf '%s\n' "$REQUIRED_VERSION" "$CLI_VERSION" | sort -V | head -n1)" = "$REQUIRED_VERSION" ]; then
echo -e "GREEN✅ PASSNC - Aliyun CLI version: $CLI_VERSION (>= $REQUIRED_VERSION)"
else
echo -e "RED❌ FAILNC - Aliyun CLI version: $CLI_VERSION (< $REQUIRED_VERSION required)"
exit 1
fi
echo ""
# Check 2: Plugin installation
echo "Check 2: agentexplorer Plugin"
if aliyun plugin list 2>/dev/null | grep -q "agentexplorer"; then
PLUGIN_VERSION=$(aliyun plugin list 2>/dev/null | grep agentexplorer | awk '{print $2}')
echo -e "GREEN✅ PASSNC - agentexplorer plugin installed (version: $PLUGIN_VERSION)"
else
echo -e "YELLOW⚠️ WARNNC - agentexplorer plugin not installed"
echo "Run: aliyun plugin install --names aliyun-cli-agentexplorer"
fi
echo ""
# Check 3: Skill structure
echo "Check 3: Skill File Structure"
FILES=(
"SKILL.md"
"references/ram-policies.md"
"references/related-commands.md"
"references/verification-method.md"
"references/cli-installation-guide.md"
"references/acceptance-criteria.md"
"references/category-examples.md"
)
ALL_FILES_EXIST=true
for file in "FILES[@]"; do
if [ -f "$file" ]; then
echo -e "GREEN✅NC $file"
else
echo -e "RED❌NC $file (missing)"
ALL_FILES_EXIST=false
fi
done
if [ "$ALL_FILES_EXIST" = true ]; then
echo -e "GREEN✅ PASSNC - All required files present"
else
echo -e "RED❌ FAILNC - Some files missing"
exit 1
fi
echo ""
# Check 4: SKILL.md frontmatter
echo "Check 4: SKILL.md Frontmatter"
if grep -q "^name: alibabacloud-find-skills" SKILL.md; then
echo -e "GREEN✅NC name field present"
else
echo -e "RED❌NC name field missing or incorrect"
exit 1
fi
if grep -q "^description:" SKILL.md; then
echo -e "GREEN✅NC description field present"
else
echo -e "RED❌NC description field missing"
exit 1
fi
echo -e "GREEN✅ PASSNC - SKILL.md frontmatter valid"
echo ""
# Check 5: Required sections
echo "Check 5: Required Sections in SKILL.md"
REQUIRED_SECTIONS=(
"Scenario Description"
"Installation"
"Authentication"
"RAM Policy"
"Parameter Confirmation"
"Core Workflow"
"Success Verification"
"Cleanup"
"Best Practices"
"Reference Documentation"
)
ALL_SECTIONS_PRESENT=true
for section in "REQUIRED_SECTIONS[@]"; do
if grep -q "## $section" SKILL.md; then
echo -e "GREEN✅NC $section"
else
echo -e "RED❌NC $section (missing)"
ALL_SECTIONS_PRESENT=false
fi
done
if [ "$ALL_SECTIONS_PRESENT" = true ]; then
echo -e "GREEN✅ PASSNC - All required sections present"
else
echo -e "RED❌ FAILNC - Some sections missing"
exit 1
fi
echo ""
# Check 6: CLI command validation
echo "Check 6: CLI Command Syntax"
CLI_COMMANDS=(
"list-categories"
"search-skills"
"get-skill-content"
)
ALL_COMMANDS_VALID=true
for cmd in "CLI_COMMANDS[@]"; do
if aliyun agentexplorer "$cmd" --help --user-agent AlibabaCloud-Agent-Skills/alibabacloud-find-skills >/dev/null 2>&1; then
echo -e "GREEN✅NC agentexplorer $cmd"
else
echo -e "RED❌NC agentexplorer $cmd (command not found or invalid)"
ALL_COMMANDS_VALID=false
fi
done
if [ "$ALL_COMMANDS_VALID" = true ]; then
echo -e "GREEN✅ PASSNC - All CLI commands valid"
else
echo -e "YELLOW⚠️ WARNNC - Some CLI commands may be invalid (plugin issue?)"
fi
echo ""
# Check 7: User-agent flag presence
echo "Check 7: User-Agent Flag in Commands"
USER_AGENT_COUNT=$(grep -o "user-agent AlibabaCloud-Agent-Skills/alibabacloud-find-skills" SKILL.md | wc -l)
if [ "$USER_AGENT_COUNT" -gt 20 ]; then
echo -e "GREEN✅ PASSNC - Found $USER_AGENT_COUNT instances of user-agent flag"
else
echo -e "YELLOW⚠️ WARNNC - Only found $USER_AGENT_COUNT instances of user-agent flag"
fi
echo ""
# Check 8: Permission failure handling block
echo "Check 8: Permission Failure Handling Block"
if grep -q "Permission Failure Handling" SKILL.md; then
echo -e "GREEN✅ PASSNC - Permission failure handling block present in SKILL.md"
else
echo -e "RED❌ FAILNC - Permission failure handling block missing"
exit 1
fi
if grep -q "Permission Failure Handling" references/ram-policies.md; then
echo -e "GREEN✅ PASSNC - Permission failure handling instructions in ram-policies.md"
else
echo -e "YELLOW⚠️ WARNNC - Permission failure handling may be incomplete in ram-policies.md"
fi
echo ""
# Summary
echo "========================================"
echo -e "GREEN All Validations Passed!NC"
echo "========================================"
echo ""
echo "The skill is ready for use. To test:"
echo " 1. Configure credentials: aliyun configure"
echo " 2. Test commands manually or run references/verification-method.md tests"
echo ""
Initialize and manage Alibaba Cloud SDK clients in Go. Covers sync.Once singleton, goroutine safety, endpoint vs region configuration, VPC endpoints, and deb...
---
name: alibabacloud-sdk-client-initialization-for-golang
description: >
Initialize and manage Alibaba Cloud SDK clients in Go. Covers sync.Once singleton, goroutine safety, endpoint vs region
configuration, VPC endpoints, and debug mode. Use when the user creates Go SDK clients, configures endpoints, asks about
goroutine safety, singleton patterns, or VPC endpoint setup in the Alibaba Cloud Go SDK.
version: 0.0.1-beta
---
# Client Initialization Best Practices (Go)
## Core Rules
- **Client is goroutine-safe** — safe to share across goroutines without additional synchronization.
- **Use singleton pattern** — do NOT create new client instances per request. Frequent client creation wastes resources.
- Prefer **explicit endpoint** over region-based endpoint resolution.
## Recommended Client Creation
```go
import (
"os"
"sync"
openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
ecs "github.com/alibabacloud-go/ecs-20140526/v3/client"
"github.com/alibabacloud-go/tea/tea"
)
var (
ecsClient *ecs.Client
ecsClientOnce sync.Once
)
func GetEcsClient() *ecs.Client {
ecsClientOnce.Do(func() {
config := &openapi.Config{
AccessKeyId: tea.String(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")),
AccessKeySecret: tea.String(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")),
Endpoint: tea.String("ecs.cn-hangzhou.aliyuncs.com"),
}
var err error
ecsClient, err = ecs.NewClient(config)
if err != nil {
panic(err)
}
})
return ecsClient
}
```
## Endpoint Configuration
Priority: explicit `Endpoint` > region-based resolution via `RegionId`.
```go
// Preferred: explicit endpoint
config.Endpoint = tea.String("ecs.cn-hangzhou.aliyuncs.com")
// Alternative: SDK resolves endpoint from region
config.RegionId = tea.String("cn-hangzhou")
```
### VPC Endpoints
Use VPC endpoints when running inside Alibaba Cloud VPC:
```go
config.Endpoint = tea.String("ecs-vpc.cn-hangzhou.aliyuncs.com")
```
### File Upload APIs (Advance)
Set **both** `RegionId` and `Endpoint` to the same region for file upload APIs:
```go
config.RegionId = tea.String("cn-shanghai")
config.Endpoint = tea.String("objectdet.cn-shanghai.aliyuncs.com")
// VPC file upload authorization:
client.OpenPlatformEndpoint = tea.String("openplatform-vpc.cn-shanghai.aliyuncs.com")
client.EndpointType = tea.String("internal")
```
## SDK Components
| Component | Description |
|-----------|-------------|
| Core SDK (`darabonba-openapi`) | Generic calls, no product dependency |
| Product SDK (e.g., `ecs-20140526`) | Typed client, models, convenience methods |
## Debugging
Enable debug mode via environment variable to log all requests:
```bash
export DEBUG=tea
```