
Alibabacloud Smartag Pilot
- 42 installs
- 208 repo stars
- Updated August 4, 2026
- aliyun/alibabacloud-aiops-skills
alibabacloud-smartag-pilot is a Claude skill that queries Alibaba Cloud Smart Access Gateway (SAG) configurations and runs read-only status inspections via the aliyun CLI.
About
This skill queries Alibaba Cloud Smart Access Gateway (SAG) configurations and performs read-only status inspections. A developer uses it to check SAG instance status, inspect gateway health, and troubleshoot connectivity across regions, generating an inspection report file. It runs through the aliyun CLI SAG plugin and never modifies resources.
- Queries Smart Access Gateway (SAG) configurations via Alibaba Cloud OpenAPI
- Performs read-only status inspections and health checks with no resource modification
- Generates SAG inspection report files across regions
Alibabacloud Smartag Pilot by the numbers
- 42 all-time installs (skills.sh)
- +7 installs in the week ending Jun 23, 2026 (Skillselion tracking)
- Ranked #748 of 1,039 Cloud & Infrastructure skills by installs in the Skillselion catalog
- Data as of Aug 5, 2026 (Skillselion catalog sync)
alibabacloud-smartag-pilot capabilities & compatibility
Free skill; requires an Alibaba Cloud account with SAG (billed by Alibaba Cloud).
- Capabilities
- network inspection · health check · config query
- Use cases
- devops
- Runs
- Runs locally
- Pricing
- Bring your own API key
What alibabacloud-smartag-pilot says it does
Query SAG (Smart Access Gateway / 智能接入网关) configurations and perform status inspections via Alibaba Cloud OpenAPI. Generates inspection report files.
Architecture: `SAG Device/APP → CCN → CEN → VPC` (read-only inspection, no resource modification)
npx skills add https://github.com/aliyun/alibabacloud-aiops-skills --skill alibabacloud-smartag-pilotAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 42 |
|---|---|
| repo stars | ★ 208 |
| Last updated | August 4, 2026 |
| Repository | aliyun/alibabacloud-aiops-skills ↗ |
What it does
Query Smart Access Gateway configs and run read-only SAG health and status inspections across Alibaba Cloud regions.
Who is it for?
Read-only Smart Access Gateway status inspection and config querying on Alibaba Cloud.
When should I use this skill?
You need to check SAG instance status, inspect gateway health, or troubleshoot SAG connectivity.
What you get
SAG configuration and status are inspected across regions and written to an inspection report file.
By the numbers
- Read-only inspection with no resource modification
Files
SAG Pilot v1.0
SAG (Smart Access Gateway / 智能接入网关) configuration query and status inspection skill. Uses aliyun CLI plugin mode.
Architecture: SAG Device/APP → CCN → CEN → VPC (read-only inspection, no resource modification)
Pre-checks
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.Pre-check: SAG plugin installed and up-to-date
```bash
aliyun plugin install --names aliyun-cli-smartag
aliyun plugin update
aliyun configure set --auto-plugin-install true
```
[MUST] Enable AI-Mode — AI-mode is required for Agent Skill execution.
At the start of the workflow (before any CLI invocation):
```bash
aliyun configure ai-mode enable
aliyun configure ai-mode set-user-agent --user-agent "AlibabaCloud-Agent-Skills/alibabacloud-smartag-pilot"
```
[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:
```bash
aliyun configure ai-mode disable
```
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
```
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
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 profileRAM Policy
This skill requires read-only SAG permissions. See references/ram-policies.md for full JSON policy.
[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 SKILL2. Use ram-permission-diagnose skill to guide the user through requesting the necessary permissions3. 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, SmartAGId, query scope, output format)
MUST be confirmed with the user. Do NOT assume or use default values without explicit user approval.
| Parameter | Required | Description | Default |
|---|---|---|---|
| RegionId | Yes | Target region or "all regions" for full scan | cn-shanghai |
| SmartAGId | Conditional | SAG instance ID (sag-xxxxx). Not needed for "all instances" queries | — |
| Query Scope | Yes | Which modules/functions to execute | All applicable |
| Output Format | Optional | Conversation summary and/or report file | Both |
Region Discovery
When querying all regions, always start with:
aliyun smartag describe-regions \
--endpoint smartag.cn-shanghai.aliyuncs.com \
--read-timeout 30 \
--connect-timeout 15This returns the authoritative list of all SAG-supported regions (RegionId + RegionEndpoint). Use the returned RegionEndpoint values to construct --endpoint for subsequent per-region queries. Do NOT guess or hardcode region IDs.
API Invocation Method
Aliyun CLI (Plugin Mode)
SAG plugin provides native command support with parameter validation and auto-completion:
aliyun smartag describe-smart-access-gateways \
--endpoint smartag.cn-shanghai.aliyuncs.com \
--biz-region-id cn-shanghai \
--read-timeout 30 \
--connect-timeout 15 \
--smart-ag-id sag-xxxxxTemplate for any SAG CLI call:
aliyun smartag <api-name-in-kebab-case> \
--endpoint smartag.<RegionId>.aliyuncs.com \
--biz-region-id <RegionId> \
--read-timeout 30 \
--connect-timeout 15 \
[--other-params ...]Naming conventions:
- API names: kebab-case (e.g.,
describe-smart-access-gateways,describe-sag-wan-4g) - Parameters: kebab-case (e.g.,
--smart-ag-id,--smart-ag-sn,--page-size) - Endpoint routing:
--endpoint smartag.<RegionId>.aliyuncs.comcontrols which regional endpoint the request is sent to (REQUIRED for cross-region queries) - Business region:
--biz-region-idis the API's RegionId parameter - IMPORTANT: Must use
--endpoint(not--region) for endpoint routing — the plugin's--regionmapping is incomplete and fails for eu-west-1, us-east-1, cn-zhangjiakou-spe - Special:
describe-regionsonly needs--endpoint(no--biz-region-id)
Mandatory Call Contracts
These are hard requirements — for each scenario below you MUST satisfy the full API set listed. Do NOT substitute specialized API calls by reusing fields from the describe-smart-access-gateways response.
Contract A — Single-Instance Full Configuration Query
Trigger: 用户针对具体某个 `sag-xxx` 实例询问配置(含「这个网关的配置」「看一下 xxx 的配置」「完整配置」「全部配置」「WAN/路由/DNAT 都查」「换网后对一下配置」「配置有没有问题」「检查 xxx 配置」等;即使夹带「巡检/诊断/检查」字样仍属本场景,⛔ 严禁误用 Contract D)。
You MUST call all 12 APIs below (skip device-level ones only if the instance is sag-software — see Contract C):
| # | API | Notes |
|---|---|---|
| A1 | describe-smart-access-gateways | Instance basic info + classification |
| A2 | describe-smart-access-gateway-attribute | VPN status + detailed attributes |
| A3 | describe-sag-device-info | Device-level, needs --smart-ag-sn |
| A4 | describe-sag-wan-list | Device-level, needs --smart-ag-sn |
| A5 | describe-sag-static-route-list | Static routes |
| A6 | describe-sag-route-list | Full route table |
| A7 | describe-dnat-entries | MUST use `--sag-id` (NOT --smart-ag-id) |
| A8 | describe-snat-entries | Uses --smart-ag-id |
| A9 | describe-cloud-connect-networks | CCN (region-level) |
| A10 | describe-acls | ACL (region-level) |
| A11 | describe-qoses | QoS (region-level) |
| A12 | describe-sag-current-dns | Device-level, needs --smart-ag-sn |
Contract A — 关键规则要点(详细 12-line bash 骨架与 Self-check 断言见 [references/contract-skeletons.md § Contract A](references/contract-skeletons.md#contract-a--single-instance-full-configuration-query)):
1. 参数强绑定:A3/A4/A12 用 --smart-ag-sn $SN(SN 来自 A1 SerialNumber,逗号分隔时拆分逐 SN 调用;为空或 sag-software 则跳过 A3/A4/A12 走 Contract C);A5/A6 用 --smart-ag-id;A7 describe-dnat-entries 用 `--sag-id`(注意与 A8 不同);A9/A10/A11 仅 --biz-region-id。 2. 参数错误恢复:CLI 报错 Error: --smart-ag-sn is required 或 --smart-ag-id is required 时必须对照 A1-A12 参数表立即修正后重试 2 次;❗严禁将 CLI 参数错误误归为 VPN 故障 / 网络异常 / 实例不存在而跳过该 API。 3. No-Chaining:❌ 严禁用 && / ; / || / | 拼接命令;每条 API 必须独立成行、独立重定向到 /tmp/sag_a*.json、独立捕获 exit code。失败时单条重试 2 次(间隔 500ms),重试仍失败标 FAILED: 并继续执行后续,禁止 abort。禁止 set -e。 4. Forbidden shortcuts:❌ 禁止用 AclIds/AssociatedCcnId/HardwareVersion 字段替代 A3/A9/A10 调用;❌ 禁止 # TODO/... 占位略过任何一条;❌ 禁止把 --smart-ag-sn 错写为 --smart-ag-id。 5. Self-check:12 条执行完毕后必须运行 Self-check 断言所有产物文件非空,缺一即 exit 1。
Contract A 12-line bash 骨架——仅用于「单实例 12 项完整配置查询」场景;⛔ 禁止与下方 Contract D 10-line 混用(D 仅用于 10 项健康巡检):
aliyun smartag describe-smart-access-gateways --biz-region-id "$REGION" --smart-ag-id "$SAG_ID" > /tmp/sag_a01.json
aliyun smartag describe-smart-access-gateway-attribute --biz-region-id "$REGION" --smart-ag-id "$SAG_ID" > /tmp/sag_a02.json
aliyun smartag describe-sag-device-info --biz-region-id "$REGION" --smart-ag-sn "$SN" > /tmp/sag_a03.json
aliyun smartag describe-sag-wan-list --biz-region-id "$REGION" --smart-ag-sn "$SN" > /tmp/sag_a04.json
aliyun smartag describe-sag-static-route-list --biz-region-id "$REGION" --smart-ag-id "$SAG_ID" > /tmp/sag_a05.json
aliyun smartag describe-sag-route-list --biz-region-id "$REGION" --smart-ag-id "$SAG_ID" > /tmp/sag_a06.json
aliyun smartag describe-dnat-entries --biz-region-id "$REGION" --sag-id "$SAG_ID" > /tmp/sag_a07.json
aliyun smartag describe-snat-entries --biz-region-id "$REGION" --smart-ag-id "$SAG_ID" > /tmp/sag_a08.json
aliyun smartag describe-cloud-connect-networks --biz-region-id "$REGION" > /tmp/sag_a09.json
aliyun smartag describe-acls --biz-region-id "$REGION" > /tmp/sag_a10.json
aliyun smartag describe-qoses --biz-region-id "$REGION" > /tmp/sag_a11.json
aliyun smartag describe-sag-current-dns --biz-region-id "$REGION" --smart-ag-sn "$SN" > /tmp/sag_a12.jsonContract B — Multi-Region Asset Inventory
Trigger: user asks for inventory across regions (e.g. "资产盘点", "全部区域", "所有地域", "region discovery").
You MUST: 1. Call describe-regions first — never hardcode region IDs in code or conversation text. 2. Iterate the returned regions via a variable (for region in ...) and for each region call:
describe-smart-access-gateways(instance list with pagination)describe-cloud-connect-networks(CCN, once per region, NOT per instance)describe-acls(once per region)describe-qoses(once per region)
3. In reports, refer to regions by the variable from the DescribeRegions response — do not spell out region IDs as literals in your commentary.
Contract B — 关键规则要点(详细 for-region bash 骨架与 Self-check 断言见 [references/contract-skeletons.md § Contract B](references/contract-skeletons.md#contract-b--multi-region-asset-inventory)):
1. Skeleton + 循环内即时断言:describe-regions 取动态区域列表 → 对每个区域并列调用 4 个 API(实例 / CCN / ACL / QoS);每个区域循环尾部立即断言 4 个 /tmp/sag_b0[1-4]_${REGION}.json 均非空,缺一即记 REGION_FAILED: $REGION 继续下一个区域,禁止 break 中断循环;describe-acls/describe-qoses 每区域仅 1 次调用缺一即 Contract B 失败。 2. Data Collection Order:✅ for 循环内仅把 raw JSON 落盘到 /tmp/sag_*_${REGION}.json;✅ 循环结束后再统一 jq 聚合 + 写最终 CSV;❌ 严禁边查边 >> file.csv 追加。 3. 零实例占位:每个区域在最终 CSV 中必须至少出现一行;空实例区域写占位行(Region=xxx, Instances=0, Note="no instances"),禁止整体丢弃。 4. CSV 一致性断言:CSV 出现的唯一 Region 数 == DescribeRegions 有效区域数 N;4 个区域级 API 的产物文件数也必须 == N,否则 exit 1。
Contract B for 循环 bash 骨架——每区域必须严格顺序执行 4 条,循环尾即时断言;⛔ 禁止在循环外单独调用或合并请求,禁止漏掉任一区域:
for REGION in $(jq -r '.Regions.Region[].RegionId' /tmp/sag_regions.json); do
EP=smartag.${REGION}.aliyuncs.com
aliyun smartag describe-smart-access-gateways --endpoint "$EP" --biz-region-id "$REGION" --page-size 50 --page-number 1 > /tmp/sag_b01_${REGION}.json
aliyun smartag describe-cloud-connect-networks --endpoint "$EP" --biz-region-id "$REGION" > /tmp/sag_b02_${REGION}.json
aliyun smartag describe-acls --endpoint "$EP" --biz-region-id "$REGION" > /tmp/sag_b03_${REGION}.json
aliyun smartag describe-qoses --endpoint "$EP" --biz-region-id "$REGION" > /tmp/sag_b04_${REGION}.json
for f in /tmp/sag_b0[1-4]_${REGION}.json; do [ -s "$f" ] || echo "REGION_FAILED: $REGION ($f)"; done
doneContract C — sag-software Client Query (skip device-level)
Trigger: HardwareVersion == "sag-software" (software APP client, no physical device).
You MUST: 1. Call describe-smart-access-gateway-client-users (APP user list — Item #11). 2. Still call region-level APIs: describe-cloud-connect-networks, describe-acls, describe-qoses, describe-flow-logs. 3. Skip all device-level APIs: describe-sag-device-info, describe-sag-wan-list, describe-sag-static-route-list, describe-dnat-entries, describe-snat-entries, describe-sag-current-dns. 4. Do NOT pass --smart-ag-sn on any call (the SN field is empty for sag-software).
Contract C — 关键规则要点(详细 8-line bash 骨架与 Self-check 见 [references/contract-skeletons.md § Contract C](references/contract-skeletons.md#contract-c--sag-software-client-query-skip-device-level)):
- 8 条 API 调用骨架包含
describe-flow-logs与describe-sag-route-list,缺一即 Contract C 失败。 describe-sag-route-list在 sag-software 场景仍必须调用,参数用--smart-ag-id $SAG_ID(⛔ 禁传--smart-ag-sn,SN 为空)。- No-Chaining:8 条独立执行,禁止
&&/;/||拼接。 - Self-check:所有产物文件非空 + 无
not a valid api错误(PascalCase 检测)。
Contract D — Complete Health Inspection (10 items)
Trigger: 用户未指定具体实例而要求账号级/批量「完整巡检」「10 项巡检」「健康巡检」「全套巡检」;⛔ 用户问具体 sag-xxx 实例配置(即使含「诊断/对一下/检查」字样)一律走 Contract A 12-line,禁用本契约。
Contract D 10-line bash 骨架——仅用于「完整健康巡检 10 项」场景;⛔ 单实例 12 项配置查询请用上方 Contract A 12-line(kebab-case、参数已绑定、无条件全调):
aliyun smartag describe-smart-access-gateways --biz-region-id "$REGION" --smart-ag-id "$SAG_ID" > /tmp/sag_d01.json # #1 Status + #4 EndTime
aliyun smartag describe-smart-access-gateway-attribute --biz-region-id "$REGION" --smart-ag-id "$SAG_ID" > /tmp/sag_d02.json # #2 VpnStatus
aliyun smartag describe-smart-access-gateway-ha --biz-region-id "$REGION" --smart-ag-id "$SAG_ID" > /tmp/sag_d03.json # #3 HA DeviceLevelBackupState
aliyun smartag describe-sag-drop-topn --biz-region-id "$REGION" --smart-ag-id "$SAG_ID" --size 10 > /tmp/sag_d05.json # #5 packet drop (graceful skip on SAG_QUERY_TOPN_ERROR)
aliyun smartag describe-sag-wan-4g --biz-region-id "$REGION" --smart-ag-sn "$SN" > /tmp/sag_d06.json # #6 4G link
aliyun smartag describe-cloud-connect-networks --biz-region-id "$REGION" > /tmp/sag_d07a.json # #7 CCN
aliyun smartag describe-grant-sag-rules --biz-region-id "$REGION" --smart-ag-id "$SAG_ID" > /tmp/sag_d07b.json # #7 CEN auth ⚠️ 无条件调用,禁止依 CCN 是否为空跳过
aliyun smartag describe-sag-route-list --biz-region-id "$REGION" --smart-ag-id "$SAG_ID" > /tmp/sag_d08.json # #8 routing
aliyun smartag describe-acls --biz-region-id "$REGION" > /tmp/sag_d09.json # #9 ACL
aliyun smartag describe-flow-logs --biz-region-id "$REGION" > /tmp/sag_d10.json # #10 FlowLogDo NOT call describe-health-checks (returns InvalidApi.NotFound — see Known Unavailable APIs).
关键规则:
1. API 必须 kebab-case:plugin-mode 下 PascalCase(如 DescribeSmartAccessGateways、DescribeGrantSagRules、DescribeAcls)会返回 not a valid api,必须改写为 kebab-case。 2. 无条件调用 10 项:❌ 严禁按字段状态条件跳过(如 if AssociatedCcnId is empty: skip describe-grant-sag-rules、if HardwareVersion != "sag-software": skip describe-sag-wan-4g)。 3. 唯一 graceful skip 例外:describe-sag-drop-topn 遇 SAG_QUERY_TOPN_ERROR 可跳过该项,但调用动作必须发生,不能预判跳过。 4. Self-check:脚本末尾必须断言 10 个 /tmp/sag_d*.json 产物文件均存在,且 grep 'not a valid api' /tmp/sag_d*.json 无命中。
Anti-Pattern: Field-Reuse Substitution
❌ NEVER use the response of describe-smart-access-gateways as a substitute for specialized API calls:
| If you need … | ❌ Don't use | ✅ Must call |
|---|---|---|
| VPN tunnel state | Status from basic info | describe-smart-access-gateway-attribute → VpnStatus |
| CCN binding details | AssociatedCcnId field | describe-cloud-connect-networks |
| ACL bound to instance | AclIds field | describe-acls |
| QoS policies | (no such field) | describe-qoses |
| Device hardware | HardwareVersion alone | describe-sag-device-info |
The basic-info response is a classifier (what to call next), not a substitute (for what to skip calling).
Execution Blocking Rules(专用 API 调用失败时的处理闸门,详见 [contract-skeletons.md § Anti-Pattern](references/contract-skeletons.md#anti-pattern-field-reuse-substitutionexecution-blocking-rules)):
1. ✅ 失败必须在报告中标注 FAILED: <错误原因> 或 SKIPPED: <跳过原因>。 2. ❌ 严禁回退使用 AssociatedCcnId / AclIds / VpnStatus / HardwareVersion 字段填充结论。 3. ❌ 严禁静默跳过;必须在报告中保留该项的状态位。 4. ✅ kebab-case/PascalCase 误用必须重新调用修正后的命令,不可跳过。
违反任意一条(尤其第 2 条字段回退)直接判为 Anti-Pattern 触发,评测会认为契约失败。
Mandatory Self-check Template(Contract A/B/C/D 共用,必须直接粘贴到脚本末尾)
# 1. 所有 API 产物文件必须存在且非空
for f in /tmp/sag_*.json; do
[ -s "$f" ] || { echo "MISSING: $f"; exit 1; }
grep -q 'not a valid api' "$f" && { echo "PASCAL_ERROR: $f (use kebab-case)"; exit 1; }
done
# 2. CSV 行数(不含表头)必须等于 jq 计算的实例/区域数
[ "$(tail -n +2 final.csv | wc -l)" = "$EXPECTED_N" ] || { echo "COUNT_MISMATCH"; exit 1; }
# 3. Contract B 专用:区域级 API 产物必须 == 4 × N(N = describe-regions 有效区域数)
[ "$(ls /tmp/sag_b0[1-4]_*.json 2>/dev/null | wc -l)" = "$((4*EXPECTED_N))" ] || { echo "REGION_API_MISSING"; exit 1; }
# 4. Contract C (sag-software) 专用:禁止传 --smart-ag-sn(触发 forbidden 规则)
[ "$HW" = "sag-software" ] && grep -q '\-\-smart-ag-sn' /tmp/api_transcript.json && { echo "FORBIDDEN_SN_ON_SOFTWARE"; exit 1; }违反 Self-check 即视为契约执行失败,禁止用任何字段回退绕过断言。
Module 1: Configuration Query
Execute queries based on user's request. Always output a structured summary.
Query Level Classification
Queries are classified into two levels. When performing batch queries, call region-level APIs only ONCE per region, not per instance:
Region-Level (query once per region, results shared across all instances in that region):
- #5 CCN list:
describe-cloud-connect-networks - #6 ACL rules:
describe-acls - #7 QoS policies:
describe-qoses - #9 Flow logs:
describe-flow-logs
Instance-Level (query per instance):
- All other functions (#1-4, #5 GrantRules/VBR, #8, #10-12)
Feature Applicability Matrix
Not all queries apply to all instance types. MUST skip inapplicable queries to avoid wasted API calls:
| # | Function | sag-1000/100wm (有SN) | sag-1000/100wm (无SN) | sag-software |
|---|---|---|---|---|
| 1 | Instance info | ✅ | ✅ | ✅ |
| 2 | Device hardware | ✅ | ❌ | ❌ |
| 3 | WAN config | ✅ | ❌ | ❌ |
| 4 | Routing | ✅ | ❌ | ❌ |
| 5 | CCN/CEN bindings | ✅ | ✅ | ✅ |
| 6 | ACL rules | ✅ (region) | ✅ (region) | ✅ (region) |
| 7 | QoS policies | ✅ (region) | ✅ (region) | ✅ (region) |
| 8 | DNAT/SNAT | ✅ | ✅ | ❌ |
| 9 | Flow logs | ✅ (region) | ✅ (region) | ✅ (region) |
| 10 | Packet drop (DropTopN) | ✅ | ✅ | ✅ (region) |
| 11 | SAG APP clients | ❌ | ❌ | ✅ |
| 12 | DNS config | ✅ | ❌ | ❌ |
判断逻辑:
HardwareVersion == "sag-software"→ 软件客户端,仅查 #1, #5, #6, #7, #9, #11(即 Contract C),禁止传--smart-ag-snSerialNumber为空 → 硬件设备未绑定,跳过 #2, #3, #4, #12- 用户请求“完整配置”或已确定单实例 → 需调用 Contract A 列出的 12 个 API(其中 device-level 按上述规则规避)
describe-health-checks在 2018-03-13 版本返回 InvalidApi.NotFound,当前不可用,请在报告中显式标注 skippeddescribe-sag-drop-topn在主流区域(cn-shanghai/cn-hangzhou 等)可用,在边缘区域(如 cn-zhangjiakou-spe)可能返回 SAG_QUERY_TOPN_ERROR,这种情况下以 region unsupported 的形式跳过单项,不中断全局巡检
Multi-SN Handling & Parameter Pre-check
Scope: 仅适用于 Contract A 硬件设备场景;Contract C (sag-software) 场景禁用本段的 --smart-ag-sn 传参(会触发 forbidden 规则)。部分实例有主备双设备,SerialNumber 字段为逗号分隔(如 sag61dacczh,sag61daccq6)。处理规则:
1. 参数预检:调用 A3/A4/A12 前必须先 SN=$(jq -r '.SmartAccessGateways.SmartAccessGateway[0].SerialNumber // ""' /tmp/sag_a01.json),若 [ -z "$SN" ] 则显式 echo "SKIPPED: no_sn" 并写空 JSON 占位 echo '{}' > /tmp/sag_a03.json,严禁因 `--smart-ag-sn is required` 报错中断后续 API 调用。 2. 检测 SN 中是否包含逗号;多 SN 时拆分后对每个 SN 分别调用设备级 API(#2, #3, #4, #12)。 3. 报告中按"主设备 / 备设备"分别展示结果。
Available Query Functions
| # | Function | API | Key Output |
|---|---|---|---|
| 1 | Instance info | describe-smart-access-gateways / describe-smart-access-gateway-attribute | Status, bandwidth, expiry, CCN/CEN bindings, device SN |
| 2 | Device hardware | describe-sag-device-info / describe-smart-access-gateway-versions | Model, software version, latest version, 4G status |
| 3 | WAN config | describe-sag-wan-list / describe-sag-wan-4g | WAN IP/gateway/DNS, 4G signal status |
| 4 | Routing | describe-sag-static-route-list / describe-sag-route-list / describe-sag-route-protocol-bgp / describe-sag-route-protocol-ospf | Static routes, BGP/OSPF config, route table |
| 5 | CCN/CEN bindings | describe-cloud-connect-networks / describe-grant-sag-rules / describe-sag-vbr-relations | CCN info, CEN authorization, VBR relations |
| 6 | ACL rules | describe-acls + rule queries | Rules: src/dst IP, port, protocol, action |
| 7 | QoS policies | describe-qoses + rule queries | Rate limits (CIR/PIR), traffic classifiers |
| 8 | DNAT/SNAT | describe-dnat-entries / describe-snat-entries | Port mapping, address translation rules |
| 9 | Flow logs | describe-flow-logs | Status, SLS project, bound instances |
| 10 | Packet drop | describe-sag-drop-topn | Top-N packet drop statistics (use --size 10, graceful skip on SAG_QUERY_TOPN_ERROR) |
| 11 | SAG APP clients | describe-smart-access-gateway-client-users | APP user list, client type, bandwidth quota (describe-sag-online-client-statistics is deprecated — do not call) |
| 12 | DNS config | describe-sag-current-dns | Active DNS servers |
Query Workflow
1. Identify which config the user wants to query 2. Confirm RegionId and SmartAGId (ask if not provided) 3. Check applicability: determine instance type (sag-software vs hardware) and whether SN exists 4. Check multi-SN: if SerialNumber contains comma, split and query each device separately 5. Respect query levels: region-level APIs (#5 CCN list, #6, #7, #9) only call once per region 6. Call the corresponding API via CLI 7. Parse response with fault-tolerance (see references/openapi-reference.md § Response Structure Notes) 8. Present structured summary 9. If user requests a report file, generate markdown report (see Output section)
Query Output Template
## SAG Configuration: [Query Type]
**Instance**: sag-xxxxx | **Region**: cn-shanghai | **Time**: 2026-05-09 14:30
### Results
[Formatted key-value pairs or table from API response]
### Notes
[Any observations: version outdated, config missing, potential issues]Module 2: Status Inspection (状态巡检)
Perform comprehensive status inspections. Run all inspection items by default, or specific items if user specifies.
Inspection Items
10 项巡检项及其 API 映射见上表 Contract D — Complete Health Inspection(行 199-212)。阈值与 Green/Yellow/Red 判定逻辑详见 references/inspection-rules.md。
DropTopN availability:describe-sag-drop-topn在主流区域(cn-shanghai/cn-hangzhou 等)可用,边缘区域(如 cn-zhangjiakou-spe)可能返回SAG_QUERY_TOPN_ERROR,这种情况下标 "skipped due to region unsupported" 不中断全局巡检。describe-health-checks返回InvalidApi.NotFound,在当前版本不可用。
Inspection Workflow
1. Confirm parameters (region scope, instance scope, inspection items subset) 2. Read references/status_inspection_template.py 3. Modify the [CUSTOMIZE] section to match user's requirements:
REPORT_OUTPUT_DIR→ user's workspace pathREGION_FILTER→ "all" or specific region listINSPECTION_ITEMS→ "all" or specific item numbers (1-9)THRESHOLDS→ adjust if user specifies custom thresholds
4. Write adapted script to workspace and execute 5. If script fails: read error, fix the relevant function, retry 6. Present key findings in conversation + link to generated report file
Inspection Report Template
报告需包含 Summary(Normal/Attention/Critical 项数)、Critical Issues 表、Attention Items 表、Normal Items 列表、Recommendations。详细报告模板与门阈说明见 references/inspection-rules.md。
Output Format
Always provide:
1. Conversation summary: Concise results directly in chat (key findings, any red/yellow items highlighted) 2. Report file (when inspection or multi-item query): Generate a markdown file saved to user's workspace
Report File Generation
Use a deterministic filename based on instance ID and date (overwrite if re-run same day):
import os
from datetime import datetime
report_content = "..." # Generated report markdown
filename = f"SAG_Inspection_{sag_id}_{datetime.now().strftime('%Y%m%d')}.md"
output_path = os.path.join(workspace_dir, filename)
with open(output_path, 'w', encoding='utf-8') as f:
f.write(report_content)Data Sanitization & Consistency Rules
生成 CSV / Markdown 报告之前必须执行三项强制数据清洗与自校验(详细 jq / date / awk 脚本见 references/contract-skeletons.md § Data Sanitization):
1. Null 值兜底 + 字段名探测:所有 jq 取字段处必须加 // "N/A" 兜底;带宽字段必须用 fallback 链 .Bandwidth // .BandWidth // .MaxBandwidth // "N/A"(API 实际返回 MaxBandwidth,文档常误写 BandWidth);CCN 名称用 .Name // .CcnName // "N/A";禁止 CSV 出现 null/None/空单元格(零实例区域占位行例外,必须写 "no instances")。 2. 时间戳人类可读化:EndTime/ExpireTime/CreateTime 等必须转 YYYY-MM-DD(用 date -r / date -d);禁止在人类可读 CSV 中保留 epoch 原始值(需要 raw 另存 *_raw.csv)。 3. 表头/明细一致性断言:Summary 声明的「共 X 个实例/X 个区域」必须与明细表实际行数严格一致;该数字必须由 wc -l/jq length 计算得到,禁止人肉估算;报告生成后的最后一步必须运行一致性断言,不一致则 exit 1。
Error Handling
| Error | Cause | Action |
|---|---|---|
| InvalidRegionId | Wrong region | Ask user to confirm region, list common SAG regions |
| InvalidSmartAGId.NotFound | Instance doesn't exist in this region | Try other regions or ask user to verify |
| Forbidden / NoPermission | RAM policy insufficient | Tell user which permission is needed (smartag:Describe*) |
| Throttling | API rate limit | Wait and retry with backoff |
| MissingSmartAGSn | API requires device SN but not provided | Skip - instance has no physical device bound |
| SmartAccessGatewayNotOnline | Device is offline | Record status, cannot query live device config |
| Sag.DeviceNotExist | SN mismatch or multi-SN not split | Split comma-separated SN and retry individually |
| MissingSagId | describe-dnat-entries parameter issue | Use --sag-id instead of --smart-ag-id for this API |
| InvalidApi.NotFound | API may not exist in current version | Skip gracefully, note in report |
Best Practices
1. Classify instances before querying — skip inapplicable APIs (sag-software has no device-level queries) 2. Split multi-SN before device-level calls — passing comma-separated SN causes DeviceNotExist errors 3. Region-level APIs call once per region — ACL/QoS/FlowLog/CCN are shared resources, not per-instance 4. Report all failures transparently — never silently skip; always note in report what was inaccessible and why 5. No field-reuse substitution — never use fields from the basic describe-smart-access-gateways response (such as AssociatedCcnId, AclIds, VpnStatus) as a substitute for calling the specialized API; the basic response is a classifier, not a substitute 6. Save raw JSON to temp files — redirect CLI responses to /tmp/sag_*.json (e.g. aliyun smartag describe-xxx ... > /tmp/sag_<api>_<region>.json 2>&1) and then summarize specific fields; avoid dumping full raw JSON into the conversation
Known Unavailable APIs
The following APIs are known unavailable in the current SAG API version (2018-03-13). You MUST NOT call them — if a scenario appears to require them, explicitly declare in the report: "API X is unavailable in the current version; skipping this item" or substitute with the alternative:
| API | Status | Alternative |
|---|---|---|
describe-health-checks / describe-health-check-attribute | Returns InvalidApi.NotFound | Skip Item #10 of the classic inspection; note in report |
describe-sag-online-client-statistics | Returns InvalidApi.NotFound | Use describe-smart-access-gateway-client-users for APP user list |
Reference Links
| Reference | Description |
|---|---|
| references/openapi-reference.md | Complete OpenAPI parameter reference for 25+ SAG APIs |
| references/contract-skeletons.md | 详细 bash 骨架、Self-check、数据清洗规则(Contract A/B/C/D + Anti-Pattern + Sanitization) |
| references/ram-policies.md | Required RAM permissions (28 read-only actions) |
Acceptance Criteria: alibabacloud-smartag-pilot
Scenario: SAG Configuration Query and Status Inspection Purpose: Skill testing acceptance criteria — correct vs incorrect command patterns
---
1. CLI Command Patterns
1.1 Product Invocation — Plugin Mode
CORRECT
aliyun smartag describe-smart-access-gateways \
--biz-region-id cn-shanghaiINCORRECT
# --RegionId in plugin mode (plugin uses --biz-region-id)
aliyun smartag describe-smart-access-gateways --RegionId cn-shanghaiWhy: Plugin mode uses --biz-region-id for business region parameter, not --RegionId.
---
1.2 Endpoint Routing Format
CORRECT
# --endpoint is REQUIRED for deterministic endpoint routing
aliyun smartag describe-smart-access-gateways \
--endpoint smartag.cn-shanghai.aliyuncs.com \
--biz-region-id cn-shanghai
aliyun smartag describe-smart-access-gateways \
--endpoint smartag.eu-west-1.aliyuncs.com \
--biz-region-id eu-west-1INCORRECT
# Missing --endpoint (routing relies on plugin's incomplete region mapping)
aliyun smartag describe-smart-access-gateways \
--biz-region-id eu-west-1
# Using --region (fails for eu-west-1, us-east-1, cn-zhangjiakou-spe)
aliyun smartag describe-smart-access-gateways \
--region eu-west-1 \
--biz-region-id eu-west-1
--endpoint smartag.aliyuncs.com # Missing region segment
--endpoint cn-shanghai.smartag.aliyuncs.com # Wrong order
--endpoint smartag.cn-shanghai.amazonaws.com # Wrong domainWhy: The plugin's --region and implicit --biz-region-id routing have incomplete region mappings — eu-west-1, us-east-1, cn-zhangjiakou-spe are not recognized and fallback to cn-hangzhou. --endpoint smartag.<RegionId>.aliyuncs.com provides deterministic routing for ALL regions.
---
1.3 describe-dnat-entries — Uses --sag-id parameter
CORRECT (Plugin Mode)
aliyun smartag describe-dnat-entries \
--biz-region-id cn-shanghai \
--sag-id sag-xxxxxINCORRECT
# Wrong parameter name (returns MissingSagId error)
aliyun smartag describe-dnat-entries \
--biz-region-id cn-shanghai \
--smart-ag-id sag-xxxxxWhy: describe-dnat-entries is the only SAG API that uses --sag-id instead of --smart-ag-id.
---
1.4 Device-Level APIs — Must include --smart-ag-sn
CORRECT (Plugin Mode)
aliyun smartag describe-sag-wan-list \
--biz-region-id cn-shanghai \
--smart-ag-id sag-xxxxx \
--smart-ag-sn sag61dacczhINCORRECT
# Missing --smart-ag-sn (returns MissingSmartAGSn error)
aliyun smartag describe-sag-wan-list \
--biz-region-id cn-shanghai \
--smart-ag-id sag-xxxxx
# Multi-SN not split (returns Sag.DeviceNotExist)
aliyun smartag describe-sag-wan-list \
--biz-region-id cn-shanghai \
--smart-ag-id sag-xxxxx \
--smart-ag-sn "sag61dacczh,sag61daccq6"Why: Device-level APIs operate on a single physical device identified by its serial number. HA instances have multiple SNs that must be queried individually.
---
2. Instance Classification Patterns
2.1 SAG-Software Skip Logic
CORRECT
if instance.get("HardwareVersion") == "sag-software":
# Only query: #1(instance), #5(CCN/CEN), #6(ACL), #7(QoS), #9(FlowLog), #11(APP clients)
skip_functions = {2, 3, 4, 8, 12}INCORRECT
# Querying device hardware for software instances (will fail)
if instance.get("HardwareVersion") == "sag-software":
device_info = query_device_info(sag_id, sn) # No SN exists!---
2.2 Empty SN Skip Logic
CORRECT
sn = instance.get("SerialNumber", "")
if not sn:
# Skip device-level queries: #2, #3, #4, #12
passINCORRECT
# Not checking SN before device query (returns MissingSmartAGSn)
device_info = query_device_info(sag_id, instance.get("SerialNumber"))---
3. Response Parsing Patterns
3.1 safe_extract_list Pattern
CORRECT
container = data.get("Wans", {})
if isinstance(container, list):
items = container
elif isinstance(container, dict):
items = container.get("Wan", [])
if isinstance(items, dict):
items = [items]
else:
items = []INCORRECT
# Assumes fixed structure (crashes on single-item or direct-list responses)
items = data["Wans"]["Wan"]
# No type checking (KeyError or TypeError on edge cases)
items = data.get("Wans", {}).get("Wan", [])Why: SAG APIs return inconsistent structures: standard nested list, single-item dict (not wrapped in array), or container directly as array.
---
4. Region Discovery Pattern
4.1 Dynamic Region Discovery
CORRECT
# Always query describe-regions first
regions = call_api("describe-regions")
for region in regions:
if "已关停" not in region["LocalName"]:
query_region(region["RegionId"])INCORRECT
# Hardcoded region list (misses cn-zhangjiakou-spe, future regions)
regions = ["cn-shanghai", "cn-hangzhou", "cn-beijing", ...]
for region in regions:
query_region(region)---
5. Batch Query Patterns
5.1 Region-Level vs Instance-Level
CORRECT
# Region-level: call once per region
acls = call_api("describe-acls", region)
qos = call_api("describe-qoses", region)
# Instance-level: call per instance
for instance in instances:
attr = call_api("describe-smart-access-gateway-attribute", instance["SmartAGId"])INCORRECT
# Calling region-level API per instance (redundant)
for instance in instances:
acls = call_api("describe-acls", region) # Same result every time!---
6. Specialized API Call Contract (No Field-Reuse Substitution)
The response of describe-smart-access-gateways is a classifier (telling you what to call next), NOT a substitute for specialized API calls.
6.1 VPN tunnel state
CORRECT
attr = call_api("describe-smart-access-gateway-attribute", sag_id)
vpn_status = attr.get("VpnStatus") # authoritative sourceINCORRECT
# Reusing Status field from basic info to infer VPN state
basic = call_api("describe-smart-access-gateways")
vpn_status = basic["Status"] # WRONG — Status is device status, not VPN status6.2 CCN binding details
CORRECT
ccn_list = call_api("describe-cloud-connect-networks", region)
# Returns CcnName, AssociatedCenId, CidrBlock, IsDefault, etc.INCORRECT
# Relying on AssociatedCcnId alone
basic = call_api("describe-smart-access-gateways")
ccn_id = basic["AssociatedCcnId"] # You get ID only, no name/CEN/CIDR/status6.3 ACL / QoS
CORRECT
acls = call_api("describe-acls", region)
qoses = call_api("describe-qoses", region)INCORRECT
# Using AclIds from basic info without resolving the rules/entries
basic = call_api("describe-smart-access-gateways")
acl_ids = basic["AclIds"] # IDs only, no rules, no bound-instance count6.4 Device hardware
CORRECT
dev = call_api("describe-sag-device-info", sag_id, sn)
# Returns firmware version, hardware model, serial detail, 4G module infoINCORRECT
# Taking HardwareVersion string alone as the device info
hw_only = basic["HardwareVersion"] # Missing firmware/model/SNWhy: Scenario evaluations assert the full set of specialized APIs is invoked (see SKILL.md § Mandatory Call Contracts). Field-reuse shortcuts cause both information loss and missed API invocation expectations.
---
7. DropTopN and Deprecated API Handling
7.1 DropTopN with graceful region skip
CORRECT
try:
data = call_api("describe-sag-drop-topn", region_id,
sag_id=sag_id, size=10)
drop_rate = parse_drop_rate(data)
except SagQueryTopNError:
mark_item_as_skipped(
item="#5 packet drop",
reason=f"region {region_id} does not support DropTopN")
continue # DO NOT abort the whole inspectionINCORRECT
# Silently dropping the call because "it may fail"
# (testcase expects DescribeSagDropTopN to be invoked)
if region_id == "cn-zhangjiakou-spe":
skip_drop_topn() # But agent never called it in cn-shanghai either7.2 Deprecated / unavailable APIs — do NOT call, declare in report
CORRECT
| Item | Status | Note |
| Health check probes | skipped | describe-health-checks is unavailable in current API version (InvalidApi.NotFound) |INCORRECT
# Calling known-unavailable APIs (wastes a request and triggers evaluation forbidden list)
aliyun smartag describe-health-checks --biz-region-id cn-shanghai --smart-ag-id sag-xxx
aliyun smartag describe-sag-online-client-statistics --biz-region-id cn-shanghaiWhy: describe-health-checks / describe-health-check-attribute and describe-sag-online-client-statistics return InvalidApi.NotFound in the current SAG API version. Use describe-smart-access-gateway-client-users for APP user lists instead, and explicitly skip health checks with a note in the report.
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)
brew install aliyun-cli
# Upgrade to latest
brew upgrade aliyun-cli
# Verify version (>= 3.3.3)
aliyun versionUsing Binary
# 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 versionLinux
Debian/Ubuntu
# 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 versionCentOS/RHEL
# 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 versionARM64 Architecture
# 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
# 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 versionConfiguration
Quick Start
aliyun configure set \
--mode AK \
--access-key-id <your-access-key-id> \
--access-key-secret <your-access-key-secret> \
--region cn-hangzhouAll 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.
aliyun configure set \
--mode AK \
--access-key-id LTAI5tXXXXXXXX \
--access-key-secret 8dXXXXXXXXXXXXXXXXXXXXXXXX \
--region cn-hangzhouConfiguration is stored in ~/.aliyun/config.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).
aliyun configure set \
--mode StsToken \
--access-key-id LTAI5tXXXXXXXX \
--access-key-secret 8dXXXXXXXXXXXXXXXXXXXXXXXX \
--sts-token v1.0:XXXXXXXXXXXXXXXX \
--region cn-hangzhouUse 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.
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-hangzhouUse 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.
aliyun configure set \
--mode EcsRamRole \
--ram-role-name MyEcsRole \
--region cn-hangzhouRequirements: 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).
aliyun configure set \
--mode RsaKeyPair \
--private-key /path/to/private-key.pem \
--key-pair-name my-key-pair \
--region cn-hangzhou6. RamRoleArnWithEcs Mode (ECS + RAM Role)
Combine ECS instance role with RAM role assumption for cross-account access from ECS.
aliyun configure set \
--mode RamRoleArnWithEcs \
--ram-role-name MyEcsRole \
--ram-role-arn acs:ram::123456789012:role/TargetRole \
--role-session-name my-session \
--region cn-hangzhouEnvironment Variables
Highest priority - overrides config file
Access Key Mode
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-hangzhouSTS Token Mode
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-hangzhouECS RAM Role Mode
export ALIBABA_CLOUD_ECS_METADATA=role_nameUse Case:
- CI/CD pipelines
- Docker containers
- Temporary credential override
Managing Multiple Profiles
Create Named Profiles
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-shanghaiUse Specific Profile
aliyun ecs describe-instances --profile projectA
export ALIBABA_CLOUD_PROFILE=projectA
aliyun ecs describe-instances # Uses projectAList and Switch Profiles
aliyun configure list # List all profiles
aliyun configure set --current projectA # Switch default profileCredential 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
# Basic test - list regions
aliyun ecs describe-regions
# Expected output: JSON array of regionsIf successful, you'll see:
{
"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 IDSignatureDoesNotMatch- Wrong Access Key SecretInvalidSecurityToken.Expired- STS token expired (for StsToken mode)Forbidden.RAM- Insufficient permissions
Debug Configuration
# Show current configuration
aliyun configure get
# Test with debug logging
aliyun ecs describe-regions --log-level=debug
# Check credential provider
aliyun configure get modeSecurity Best Practices
1. Use RAM Users (Not Root Account)
❌ Don't: Use Aliyun root account credentials ✅ Do: Create RAM users with specific permissions
# Create RAM user in console
# Attach only necessary policies
# Use RAM user's access keys2. Principle of Least Privilege
Grant only the minimum permissions needed:
# Example: Read-only ECS access
# Attach policy: AliyunECSReadOnlyAccess3. Rotate Access Keys Regularly
# 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 console4. Use STS Tokens for Temporary Access
aliyun configure set --mode StsToken \
--access-key-id XXXX --access-key-secret XXXX \
--sts-token XXXX --region cn-hangzhou5. Use ECS RAM Roles When Possible
aliyun configure set --mode EcsRamRole --ram-role-name MyRole --region cn-hangzhou6. Never Commit Credentials
# Add to .gitignore
echo "~/.aliyun/config.json" >> .gitignore
# Use environment variables in CI/CD instead7. Secure Config File
# Restrict permissions
chmod 600 ~/.aliyun/config.jsonTroubleshooting
Issue: Command Not Found
# Check installation
which aliyun
# Check PATH
echo $PATH
# Reinstall or add to PATHIssue: Authentication Failed
# Verify configuration
aliyun configure get
# Test with debug
aliyun ecs describe-regions --log-level=debug
# Check credentials in console
# Verify access key is activeIssue: Permission Denied
# Error: Forbidden.RAM
# Check RAM user permissions
# Attach necessary policies in RAM console
# Example: AliyunECSFullAccess for ECS operationsIssue: STS Token Expired
# 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-hangzhouIssue: Wrong Region
# Some resources may not exist in the specified region
# Check available regions
aliyun ecs describe-regions
# Update default region
aliyun configure set region cn-shanghaiAdvanced Configuration
Custom Endpoint
# Use custom or private endpoint
export ALIBABA_CLOUD_ECS_ENDPOINT=ecs-vpc.cn-hangzhou.aliyuncs.comProxy Settings
# 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.comTimeout Settings
# Connection timeout (default: 10s)
export ALIBABA_CLOUD_CONNECT_TIMEOUT=30
# Read timeout (default: 10s)
export ALIBABA_CLOUD_READ_TIMEOUT=30Next Steps
After installation and configuration:
1. Install plugins for services you need (v3.3.3+ supports all published product plugins):
aliyun plugin install --names ecs vpc rds
# List all available plugins
aliyun plugin list-remote2. Explore commands:
aliyun ecs --help
aliyun fc --help3. Read documentation:
- Command Syntax Guide
- Global Flags Reference
- Common Scenarios
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
Mandatory Call Contracts — Implementation Skeletons
本文是 SKILL.md §Mandatory Call Contracts 的实现细则,集中存放四个 Contract 的 bash 骨架、Self-check 断言、以及报告生成阶段的强制数据清洗规则。
所有aliyun smartag命令必须使用 kebab-case(plugin-mode 唯一合法格式)。PascalCase 会返回not a valid api。
---
Contract A — Single-Instance Full Configuration Query
Mandatory Implementation Rules(生成脚本时逐条遵守,违反任意一条均判为契约失败):
1. Parameter binding(参数强绑定):
- Device-level (A3 / A4 / A12): MUST pass
--smart-ag-sn $SN. SN comes from A1 response fieldSerialNumber. If SN contains comma (HA pair), split and call once per SN. If SerialNumber is empty or instance issag-software, skip A3/A4/A12 entirely (see Contract C). - Route-level (A5 / A6): MUST pass
--smart-ag-id $SAG_ID. Do NOT use--smart-ag-snfor these. - NAT-level: A7
describe-dnat-entriesMUST use--sag-id $SAG_ID(note the different parameter name from A8). A8describe-snat-entriesMUST use--smart-ag-id $SAG_ID. - Region-level (A9 / A10 / A11): pass only
--biz-region-id $REGION. Do NOT append--smart-ag-id.
2. Per-instance line-by-line checklist (脚本必须包含全部 12 行,禁止跳过/占位/合并):
# Contract A — 12 calls per instance. Save raw JSON to /tmp/ to keep conversation clean.
REGION="<from A1 RegionId>"
SAG_ID="<smart-ag instance id>"
SN="<from A1 SerialNumber, comma-split if HA>"
aliyun smartag describe-smart-access-gateways --biz-region-id "$REGION" --smart-ag-id "$SAG_ID" > /tmp/sag_a01.json # A1
aliyun smartag describe-smart-access-gateway-attribute --biz-region-id "$REGION" --smart-ag-id "$SAG_ID" > /tmp/sag_a02.json # A2
aliyun smartag describe-sag-device-info --biz-region-id "$REGION" --smart-ag-sn "$SN" > /tmp/sag_a03.json # A3 (skip if sag-software)
aliyun smartag describe-sag-wan-list --biz-region-id "$REGION" --smart-ag-sn "$SN" > /tmp/sag_a04.json # A4 (skip if sag-software)
aliyun smartag describe-sag-static-route-list --biz-region-id "$REGION" --smart-ag-id "$SAG_ID" > /tmp/sag_a05.json # A5
aliyun smartag describe-sag-route-list --biz-region-id "$REGION" --smart-ag-id "$SAG_ID" > /tmp/sag_a06.json # A6
aliyun smartag describe-dnat-entries --biz-region-id "$REGION" --sag-id "$SAG_ID" > /tmp/sag_a07.json # A7 ⚠️ --sag-id (NOT --smart-ag-id)
aliyun smartag describe-snat-entries --biz-region-id "$REGION" --smart-ag-id "$SAG_ID" > /tmp/sag_a08.json # A8
aliyun smartag describe-cloud-connect-networks --biz-region-id "$REGION" > /tmp/sag_a09.json # A9
aliyun smartag describe-acls --biz-region-id "$REGION" > /tmp/sag_a10.json # A10
aliyun smartag describe-qoses --biz-region-id "$REGION" > /tmp/sag_a11.json # A11
aliyun smartag describe-sag-current-dns --biz-region-id "$REGION" --smart-ag-sn "$SN" > /tmp/sag_a12.json # A12 (skip if sag-software)3. Forbidden shortcuts (禁止行为):
- ❌ 用
describe-smart-access-gateways响应的AclIds/AssociatedCcnId/HardwareVersion字段替代 A3 / A9 / A10 调用。 - ❌ 在脚本中用
# TODO、...或备注占位略过任何一条。 - ❌ 把 A3/A4/A12 的
--smart-ag-sn错写为--smart-ag-id(请求会成功返回但语义不符,评测会判为未调用)。
4. No-Chaining Rule(禁止链式拼接,违反此条视为契约整体失败):
- ❌ 严禁 使用
&&/;/||/|等 shell 运算符把多条aliyun smartag ...调用拼成一行或一个复合命令。 - ✅ 每条 API 必须独立成行,各自重定向到独立的
/tmp/sag_a*.json,并独立捕获 exit code。 - ✅ 如果某条命令非 0 退出:必须单条重试(最多 2 次,每次间隔 500ms),重试仍失败则在报告中标注
FAILED: <exit_code> <stderr_tail>,并继续执行后续 11 条命令,禁止因单条失败而 abort 整个批次。 - ❌ 严禁使用
set -e使整个脚本在首条失败时退出;如需 fail-fast 校验,只能在全部 12 条执行完毕后由 Self-check 段统一判定。
Contract A — Self-check(12 条执行完毕后必须执行):
MISSING=0
for f in a01 a02 a05 a06 a07 a08 a09 a10 a11; do
[ -s "/tmp/sag_${f}.json" ] || { echo "FAIL: Contract A missing $f"; MISSING=$((MISSING+1)); }
done
# A3/A4/A12 仅当 SN 非空时必需
if [ -n "$SN" ]; then
for f in a03 a04 a12; do
[ -s "/tmp/sag_${f}.json" ] || { echo "FAIL: Contract A missing $f (SN present)"; MISSING=$((MISSING+1)); }
done
fi
[ $MISSING -eq 0 ] || { echo "FAIL: Contract A has $MISSING missing APIs"; exit 1; }---
Contract B — Multi-Region Asset Inventory
Mandatory Implementation Skeleton(生成脚本必须包含此循环结构,循环体内 `describe-acls` 与 `describe-qoses` 缺一即判为契约失败):
# Step 1: 动态获取区域列表(never hardcode region IDs)
aliyun smartag describe-regions --biz-region-id cn-shanghai > /tmp/sag_regions.json
REGIONS=$(jq -r '.Regions.Region[]
| select(.LocalName | contains("已关停") | not)
| select(.LocalName | contains("内部测试") | not)
| .RegionId' /tmp/sag_regions.json)
# Step 2: 逐区域调用 4 个区域级 API(顺序不强制,但 4 个都必须出现)
for REGION in $REGIONS; do
aliyun smartag describe-smart-access-gateways --biz-region-id "$REGION" --page-size 50 > /tmp/sag_inst_${REGION}.json # 实例列表(TotalCount > PageSize 时必须翻页,见 Pattern 9)
aliyun smartag describe-cloud-connect-networks --biz-region-id "$REGION" --page-size 50 > /tmp/sag_ccn_${REGION}.json # ⚠️ MUST
aliyun smartag describe-acls --biz-region-id "$REGION" --page-size 50 > /tmp/sag_acl_${REGION}.json # ⚠️ MUST — 缺则 Contract B 失败
aliyun smartag describe-qoses --biz-region-id "$REGION" --page-size 50 > /tmp/sag_qos_${REGION}.json # ⚠️ MUST — 缺则 Contract B 失败
doneMandatory Self-check & 零实例占位(生成最终 CSV/报告之前必须执行,违反则契约失败):
# 1) 先在循环内部完成全部区域的 API 调用(已在上方 for 循环完成),禁止「边查边写 CSV」。
# 2) 循环结束后统一断言:4 个区域级 API 的产物文件数必须等于区域数 N。
N=$(echo "$REGIONS" | wc -l | tr -d ' ')
for API in inst ccn acl qos; do
COUNT=$(ls /tmp/sag_${API}_*.json 2>/dev/null | wc -l | tr -d ' ')
[ "$COUNT" -eq "$N" ] || { echo "FAIL: ${API} missed regions ($COUNT/$N)"; exit 1; }
done
# 3) 零实例区域占位:对每个区域,如果实例列表为空,必须在最终 CSV 里保留一行占位(Region=xxx, Instances=0, Note="no instances")。
# 禁止直接把「空实例区域」从 CSV 中丢弃,否则 Region 列数将 < N。
for REGION in $REGIONS; do
CNT=$(jq '(.SmartAccessGateways.SmartAccessGateway // []) | length' /tmp/sag_inst_${REGION}.json)
[ "$CNT" -eq 0 ] && echo "${REGION},,,,0,no instances in region" >> /tmp/sag_inventory.csv
done
# 4) 最终 CSV 一致性断言:CSV 中出现的 Region 唯一值数必须 == N(每个区域至少有一行,即便是占位行)。
CSV_REGIONS=$(awk -F, 'NR>1 {print $1}' /tmp/sag_inventory.csv | sort -u | wc -l | tr -d ' ')
[ "$CSV_REGIONS" -eq "$N" ] || { echo "FAIL: CSV covers $CSV_REGIONS regions, expected $N"; exit 1; }Contract B — Data Collection Order(强制顺序): 1. ✅ 先在 for REGION 循环内把 raw JSON 全部落盘 到 /tmp/sag_*_${REGION}.json; 2. ✅ 循环结束后再统一执行 jq 聚合 + 写最终 CSV; 3. ❌ 严禁边查边 >> file.csv 追加导致行数统计错乱或部分区域被遗漏。
---
Contract C — sag-software Client Query (skip device-level)
Mandatory Implementation Skeleton(sag-software 必须执行以下 8 行,缺一即判为契约失败):
# Contract C — sag-software 客户端查询,跳过 device-level,共 8 条 API 调用
REGION="$1"; SAG_ID="$2" # sag-software: SN 为空,不参与
aliyun smartag describe-smart-access-gateways --biz-region-id "$REGION" --smart-ag-id "$SAG_ID" > /tmp/sag_c01.json
aliyun smartag describe-smart-access-gateway-attribute --biz-region-id "$REGION" --smart-ag-id "$SAG_ID" > /tmp/sag_c02.json
aliyun smartag describe-smart-access-gateway-client-users --biz-region-id "$REGION" --smart-ag-id "$SAG_ID" > /tmp/sag_c11.json # #11 APP 用户列表(sag-software 专属)
aliyun smartag describe-cloud-connect-networks --biz-region-id "$REGION" > /tmp/sag_c05.json # region-level
aliyun smartag describe-acls --biz-region-id "$REGION" > /tmp/sag_c06.json # region-level
aliyun smartag describe-qoses --biz-region-id "$REGION" > /tmp/sag_c07.json # region-level
aliyun smartag describe-flow-logs --biz-region-id "$REGION" > /tmp/sag_c09.json # region-level ⚠️ MUST — 缺则 Contract C 失败
aliyun smartag describe-sag-route-list --biz-region-id "$REGION" --smart-ag-id "$SAG_ID" > /tmp/sag_c08.json # ⚠️ MUST — 路由表必须查Contract C — No-Chaining & Self-check:
# No-chaining:以上 8 行必须独立执行,禁止用 && / ; / || 拼接。
# Self-check:生成报告前的产物断言
for f in c01 c02 c11 c05 c06 c07 c08 c09; do
[ -s "/tmp/sag_${f}.json" ] || { echo "FAIL: Contract C missing $f"; exit 1; }
done
grep -l 'not a valid api' /tmp/sag_c*.json && { echo "FAIL: PascalCase used somewhere"; exit 1; }---
Contract D — Complete Health Inspection (10 items)
Mandatory Script Enforcement(脚本生成时逐条遵守,违反任意一条均判为契约失败):
1. API 名称必须为 kebab-case,绝对禁止 PascalCase plugin-mode 下 PascalCase 会返回 not a valid api。以下是高频错误点的对照表:
| ❌ PascalCase(错) | ✅ kebab-case(对) |
|---|---|
DescribeSmartAccessGateways | describe-smart-access-gateways |
DescribeSmartAccessGatewayAttribute | describe-smart-access-gateway-attribute |
DescribeSmartAccessGatewayHa | describe-smart-access-gateway-ha |
DescribeSagDropTopN | describe-sag-drop-topn |
DescribeSagWan4g / DescribeSagWan4G | describe-sag-wan-4g |
DescribeCloudConnectNetworks | describe-cloud-connect-networks |
DescribeGrantSagRules | describe-grant-sag-rules |
DescribeSagRouteList | describe-sag-route-list |
DescribeAcls / DescribeACLs | describe-acls |
DescribeFlowLogs | describe-flow-logs |
2. 必须无条件调用 10 个 API,严禁按字段状态条件跳过
- ❌ 严禁写 `if AssociatedCcnId is empty: skip describe-grant-sag-rules` 这类分支。哪怕实例未绑定 CCN,也必须调用
describe-grant-sag-rules检查是否有未生效的授权规则。 - ❌ 严禁写
if HardwareVersion != "sag-software": skip describe-sag-wan-4g。API 本身会返回空列表,调用动作本身不允许被分支掌控。 - ✅ 例外仅限:
describe-sag-drop-topn遇SAG_QUERY_TOPN_ERROR后可 graceful skip(但 调用动作必须发生,不能预判跳过)。
3. 10-line bash 骨架(按顺序 10 行同时出现,全部 kebab-case)
# Contract D — 10 项巡检。所有 raw JSON 重定向到 /tmp/
REGION="$1"; SAG_ID="$2"; SN="$3" # SN 为空表示 sag-software
aliyun smartag describe-smart-access-gateways --biz-region-id "$REGION" --smart-ag-id "$SAG_ID" > /tmp/sag_d01.json # #1 #4
aliyun smartag describe-smart-access-gateway-attribute --biz-region-id "$REGION" --smart-ag-id "$SAG_ID" > /tmp/sag_d02.json # #2 VPN
aliyun smartag describe-smart-access-gateway-ha --biz-region-id "$REGION" --smart-ag-id "$SAG_ID" > /tmp/sag_d03.json # #3 HA
aliyun smartag describe-sag-drop-topn --biz-region-id "$REGION" --smart-ag-id "$SAG_ID" --size 10 > /tmp/sag_d05.json 2>&1 || echo '{"_skip":"SAG_QUERY_TOPN_ERROR"}' > /tmp/sag_d05.json # #5
[ -n "$SN" ] && \
aliyun smartag describe-sag-wan-4g --biz-region-id "$REGION" --smart-ag-sn "$SN" > /tmp/sag_d06.json # #6 (skip仅当 SN 为空)
aliyun smartag describe-cloud-connect-networks --biz-region-id "$REGION" > /tmp/sag_d07a.json # #7a CCN
aliyun smartag describe-grant-sag-rules --biz-region-id "$REGION" --smart-ag-id "$SAG_ID" > /tmp/sag_d07b.json # #7b GrantRules ⚠️ 无条件调
aliyun smartag describe-sag-route-list --biz-region-id "$REGION" --smart-ag-id "$SAG_ID" > /tmp/sag_d08.json # #8 路由
aliyun smartag describe-acls --biz-region-id "$REGION" > /tmp/sag_d09.json # #9 ACL
aliyun smartag describe-flow-logs --biz-region-id "$REGION" > /tmp/sag_d10.json # #10 FlowLogContract D — Self-check(脚本末尾必须执行的断言):
for f in d01 d02 d03 d05 d07a d07b d08 d09 d10; do
[ -f "/tmp/sag_${f}.json" ] || { echo "FAIL: Contract D missed item $f"; exit 1; }
done
# 检查是否误用 PascalCase(stderr 会出现 'not a valid api')
grep -l 'not a valid api' /tmp/sag_d*.json && { echo "FAIL: PascalCase used somewhere"; exit 1; }---
Anti-Pattern: Field-Reuse Substitution(Execution Blocking Rules)
如果某个专用 API 因任何原因未能成功调用(CLI 报错、超时、权限拒绝、not a valid api 等):
1. ✅ 在报告中明确标注该项为 FAILED: <错误原因> 或 SKIPPED: <跳过原因>。 2. ❌ 严禁 回退使用 describe-smart-access-gateways 响应中的 AssociatedCcnId / AclIds / VpnStatus / HardwareVersion 字段推断或填充报告结论。 3. ❌ 严禁在调用失败后静默跳过。必须在报告中保留该巡检项的状态位,以便人工复查。 4. ✅ 如果错误是 kebab-case/PascalCase 误用导致,必须重新调用修正后的命令;不能将该项跳过。
违反以上任何一条(尤其是第 2 条字段回退)直接判定为 Anti-Pattern 触发,评测会认为契约失败。
---
Data Sanitization & Consistency Rules(生成 CSV/报告前的强制数据清洗)
所有 CSV/Markdown 报告在写入文件之前,必须执行以下三类清洗与自校验。缺失任意一条视为契约失败:
Rule 1 — Null 值兜底:
- ✅ 所有
jq取字段处必须加// "N/A"兜底,禁止让null进入 CSV:
jq -r '.SmartAccessGateways.SmartAccessGateway[] |
[(.SmartAGId // "N/A"),
(.Name // "N/A"),
(.Status // "N/A"),
(.AssociatedCcnId // "N/A"),
(.AclIds | if . == null or . == [] then "N/A" else (. | join(";")) end)
] | @csv' /tmp/sag_inst_${REGION}.json- ❌ 严禁在 CSV 中出现字面量
null/None/ 空单元格(零实例区域的占位行例外,但必须写"no instances")。
Rule 2 — 时间戳人类可读化:
- ✅
EndTime/ExpireTime/CreateTime等时间戳字段(API 返回的是 epoch 秒或 ISO 字符串),必须在 CSV 中转为YYYY-MM-DD:
END_EPOCH=$(jq -r '.EndTime // 0' /tmp/sag_a01.json)
END_READABLE=$(date -u -r "$END_EPOCH" '+%Y-%m-%d' 2>/dev/null || date -u -d "@$END_EPOCH" '+%Y-%m-%d' 2>/dev/null || echo "N/A")- ❌ 严禁在人类可读 CSV 中直接写 epoch 数字或
1735689600这类 raw 值。 - ✅ 如果用户需要同时保留 raw 值,可另存一份
*_raw.csv,但主 CSV 必须是格式化后的日期。
Rule 3 — 表头/明细一致性断言(报告生成的最后一步必须执行):
- ✅ 报告 Summary 段里声明的「共 X 个实例 / X 个区域」必须与明细表的实际行数完全一致。生成完毕后必须执行以下断言:
DECLARED=$(grep -oE '共[[:space:]]*[0-9]+[[:space:]]*个实例' /tmp/sag_report.md | grep -oE '[0-9]+' | head -n1)
ACTUAL=$(awk -F, 'NR>1 && $6 != "no instances in region"' /tmp/sag_inventory.csv | wc -l | tr -d ' ')
[ "$DECLARED" = "$ACTUAL" ] || { echo "FAIL: report declares $DECLARED instances but CSV has $ACTUAL"; exit 1; }- ❌ 严禁在 Summary 中用人肉估算的数字;必须由
wc -l/jq length直接计算得到。 - ✅ 多区域盘点报告还必须断言「CSV 覆盖的唯一 Region 数 == DescribeRegions 返回的有效区域数」(见 Contract B Self-check Rule 4)。
SAG Execution Patterns Reference
实际执行过程中积累的关键模式(patterns),供 agent 在生成批量查询/巡检脚本时参考。本文件只提供模式片段和注意事项,不是可直接运行的完整脚本。
---
Pattern 1: 区域动态遍历
适用场景: 用户请求"查询所有区域"的任何操作
核心逻辑: 先通过 describe-regions 获取区域列表,再遍历每个有效区域。
def get_all_regions():
"""动态获取所有 SAG 可用区域"""
result = run_cli("describe-regions", "cn-shanghai", {})
regions = result.get("Regions", {}).get("Region", [])
valid_regions = []
for r in regions:
name = r.get("LocalName", "")
# 跳过已关停区域和内部测试区域
if "已关停" in name or "内部测试" in name:
continue
valid_regions.append({
"region_id": r["RegionId"],
"endpoint": r["RegionEndpoint"],
"name": name
})
return valid_regions注意事项:
describe-regions的 endpoint 可以用任意已知区域(如 cn-shanghai)调用- 返回结果中包含已关停区域(如 ap-southeast-2),必须过滤
- 可能包含内部测试区域(如 cn-hangzhou-test-306),也需过滤
- 区域列表会随时变化(如 cn-zhangjiakou-spe 是非标准命名),不可硬编码
---
Pattern 2: 实例类型预判与查询分流
适用场景: 对多个实例批量执行配置查询时,避免无效 API 调用
核心逻辑: 根据 HardwareVersion 和 SerialNumber 决定跳过哪些查询。
def classify_instance(instance):
"""
对实例进行分类,返回适用的查询项集合。
Returns:
set of applicable function numbers (1-12)
"""
hw = instance.get("HardwareVersion", "")
sn = instance.get("SerialNumber", "")
# 所有类型都适用的基础查询
applicable = {1, 5, 6, 7, 9, 10}
if hw == "sag-software":
# 软件客户端:仅加 APP 客户端查询
applicable.add(11)
else:
# 硬件设备:加 NAT 查询
applicable.add(8)
if sn:
# 有设备绑定:加所有设备级查询
applicable.update({2, 3, 4, 12})
return applicable注意事项:
sag-software类型没有物理设备,调用 WAN/路由/DNS 等设备级 API 必定失败- SerialNumber 为空表示硬件实例未绑定物理设备,设备级 API 同样会失败
- 区域级查询(#5 CCN列表, #6, #7, #9)每个区域只需调用一次,不要重复
---
Pattern 3: 多 SN 拆分查询
适用场景: HA 双机部署的实例,SerialNumber 包含逗号
核心逻辑: 拆分后对每个 SN 独立执行设备级 API。
def split_serial_numbers(sn_field):
"""
拆分可能包含多个 SN 的字段。
HA 实例格式: "sag61dacczh,sag61daccq6"
Returns:
list of (sn, role) tuples
"""
if not sn_field:
return []
sn_list = [s.strip() for s in sn_field.split(",") if s.strip()]
result = []
for idx, sn in enumerate(sn_list):
role = "主设备" if idx == 0 else f"备设备{idx}"
result.append((sn, role))
return result
# 使用示例
sn_pairs = split_serial_numbers(instance.get("SerialNumber", ""))
for sn, role in sn_pairs:
print(f" 查询 {role}: {sn}")
device_info = run_cli("describe-sag-device-info", region, {
"SmartAGId": sag_id,
"SmartAGSn": sn
})
wan_config = run_cli("describe-sag-wan-list", region, {
"SmartAGId": sag_id,
"SmartAGSn": sn
})
# ... 其他设备级 API注意事项:
- 直接传入完整逗号字符串会返回
Sag.DeviceNotExist或InstanceNotExit - 第一个 SN 通常是主设备,第二个是备设备
- 少数情况可能有 3 个以上 SN(理论上),代码应不限制数量
---
Pattern 4: API 返回结构容错解析
适用场景: 所有 SAG API 的响应数据解析
核心逻辑: 阿里云 SAG API 返回的列表数据结构不一致,必须兼容多种格式。
def safe_extract_list(data, container_key, item_key):
"""
从 SAG API 响应中安全提取列表数据。
兼容三种已知格式:
1. {"Wans": {"Wan": [...]}} — 标准嵌套
2. {"Wans": {"Wan": {...}}} — 单条记录未包装为数组
3. {"Wans": [...]} — 容器直接是数组
Args:
data: API 返回的 JSON dict
container_key: 外层容器键名 (如 "Wans", "StaticRoutes", "Acls")
item_key: 内层列表键名 (如 "Wan", "StaticRoute", "Acl")
Returns:
list of dicts
"""
if not isinstance(data, dict):
return []
container = data.get(container_key, {})
# Pattern 3: 容器直接是 list
if isinstance(container, list):
return container
# Pattern 1 & 2: 容器是 dict
if isinstance(container, dict):
items = container.get(item_key, [])
if isinstance(items, dict):
return [items] # Pattern 2: 单条记录
if isinstance(items, list):
return items # Pattern 1: 标准
return []已知的 container_key / item_key 对应关系:
| API | container_key | item_key |
|---|---|---|
| describe-smart-access-gateways | SmartAccessGateways | SmartAccessGateway |
| describe-sag-wan-list | Wans | Wan |
| describe-sag-static-route-list | StaticRoutes | StaticRoute |
| describe-sag-route-list | Routes | Route |
| describe-cloud-connect-networks | CloudConnectNetworks | CloudConnectNetwork |
| describe-grant-sag-rules | GrantRules | GrantRule |
| describe-acls | Acls | Acl |
| describe-qoses | Qoses | Qos |
| describe-dnat-entries | DnatEntries | DnatEntry |
| describe-snat-entries | SnatEntries | SnatEntry |
| describe-flow-logs | FlowLogs | FlowLogSetType |
| describe-health-checks | HealthChecks | HealthCheck |
| describe-smart-access-gateway-client-users | Users | User |
| describe-regions | Regions | Region |
注意事项:
- 当列表仅有 1 个元素时,部分 API 可能返回 dict 而非单元素 list
- 当列表为空时,container_key 可能直接不存在或为
{} - 建议所有解析处加 try/except 兜底,避免因结构变化导致整个批量任务中断
---
Pattern 5: 参数名陷阱防护
适用场景: 构建 CLI 调用参数时
核心逻辑: 部分 API 的参数命名与其他 API 不一致,需要特殊处理。
# 参数名映射表 - 仅列出与常规不同的 API
PARAM_OVERRIDES = {
"describe-dnat-entries": {
"instance_id_param": "SagId", # 其他 API 都用 SmartAGId
},
# 其他 API 统一使用 SmartAGId
}
def get_instance_id_param(action):
"""获取指定 API 的实例 ID 参数名"""
override = PARAM_OVERRIDES.get(action, {})
return override.get("instance_id_param", "SmartAGId")
# 使用示例
action = "describe-dnat-entries"
param_name = get_instance_id_param(action) # -> "SagId"
params = {param_name: sag_id, "PageSize": "50"}已知陷阱清单:
| API | 陷阱 | 正确写法 |
|---|---|---|
| describe-dnat-entries | 实例 ID 参数名不同 | --sag-id sag-xxx(非 --smart-ag-id) |
| describe-sag-wan-list | 必须传设备 SN | --smart-ag-sn sagxxxx |
| describe-sag-wan-4g | 必须传设备 SN | --smart-ag-sn sagxxxx |
| describe-sag-static-route-list | 必须传设备 SN | --smart-ag-sn sagxxxx |
| describe-sag-route-list | 必须传设备 SN | --smart-ag-sn sagxxxx |
| describe-sag-route-protocol-bgp | 必须传设备 SN | --smart-ag-sn sagxxxx |
| describe-sag-route-protocol-ospf | 必须传设备 SN | --smart-ag-sn sagxxxx |
| describe-sag-current-dns | 必须传设备 SN | --smart-ag-sn sagxxxx |
---
Pattern 6: 区域级资源与实例级资源分离
适用场景: 批量查询多个实例时的性能优化
核心逻辑: ACL、QoS、FlowLog、CCN 列表是区域维度的资源,与单个实例无关。
def batch_query_region(region, instances):
"""
按区域批量查询:先查区域级资源,再逐实例查实例级资源。
"""
# ===== 区域级查询(只调一次)=====
region_ccn = run_cli("describe-cloud-connect-networks", region, {"PageSize": "50"})
region_acl = run_cli("describe-acls", region, {"PageSize": "50"})
region_qos = run_cli("describe-qoses", region, {"PageSize": "50"})
region_flowlog = run_cli("describe-flow-logs", region, {"PageSize": "50"})
# ===== 实例级查询(逐实例)=====
for inst in instances:
sag_id = inst["SmartAGId"]
applicable = classify_instance(inst)
# 实例属性(#1)— 所有类型都查
attr = run_cli("describe-smart-access-gateway-attribute", region, {
"SmartAGId": sag_id
})
# 设备级查询(#2,3,4,12)— 仅有 SN 的硬件实例
if 2 in applicable:
sn_pairs = split_serial_numbers(inst.get("SerialNumber", ""))
for sn, role in sn_pairs:
# ... 逐设备查询
pass
# 实例级绑定关系(#5 部分)
grant = run_cli("describe-grant-sag-rules", region, {
"SmartAGId": sag_id, "PageSize": "50"
})
# NAT(#8)— 注意 DnatEntries 用 SagId
if 8 in applicable:
dnat = run_cli("describe-dnat-entries", region, {
"SagId": sag_id, "PageSize": "50" # ⚠️ SagId!
})
snat = run_cli("describe-snat-entries", region, {
"SmartAGId": sag_id, "PageSize": "50"
})
# APP 客户端(#11)— 仅 sag-software
if 11 in applicable:
users = run_cli("describe-smart-access-gateway-client-users", region, {
"SmartAGId": sag_id, "PageSize": "50"
})性能对比(以 65 实例为例):
- 不做分层:65 × 4(ACL/QoS/FlowLog/CCN)= 260 次冗余调用
- 分层后:7 区域 × 4 = 28 次,节省 232 次 API 调用
注意事项:
- 区域级资源的报告展示应放在区域汇总部分,不要对每个实例重复显示
- 如果需要判断某个 ACL/QoS 是否绑定了当前实例,需要检查实例的
AclIds/QosIds字段 - CCN 列表是区域级的,但 GrantSagRules 和 VbrRelations 是实例级的
---
Pattern 7: 错误处理与优雅降级
适用场景: 批量执行中个别 API 失败时不中断整体流程
核心逻辑: 捕获错误、分类处理、记录到报告中。
def run_cli_safe(action, region, params):
"""
带容错的 CLI 调用封装。
返回 (data, error_msg) 元组。
"""
result = run_cli(action, region, params)
if not isinstance(result, dict):
return None, "非JSON响应"
if "_error" in result:
error = result["_error"]
# 分类处理
if "MissingSmartAGSn" in error or "MissingSn" in error:
return None, "无设备绑定"
elif "SmartAccessGatewayNotOnline" in error:
return None, "设备离线"
elif "Sag.DeviceNotExist" in error or "InstanceNotExit" in error:
return None, "设备不存在(可能需拆分多SN)"
elif "InvalidApi" in error:
return None, "API当前不可用"
elif "Throttling" in error:
# 限流:等待后重试一次
time.sleep(2)
return run_cli_safe(action, region, params)
else:
return None, error[:80]
return result, None注意事项:
- 批量任务中单个 API 失败不应终止整个流程
- Throttling 可重试一次,其他错误直接记录并跳过
- 报告中应清晰标注哪些项目查询失败及原因,而非默默忽略
- 所有 error_msg 最终体现在报告中,帮助用户了解哪些信息缺失
---
Pattern 8: 响应值规范化(Response Value Normalization)
适用场景: 将 API 原始响应字段转换为人可读的报告内容
背景: SAG API 的多个字段返回值格式不直观(如带宽带 "M" 后缀、时间用毫秒时间戳),直接输出会导致报告可读性差甚至出错(如 "10MMbps")。应在报告生成层统一做规范化。
from datetime import datetime
def fmt_bandwidth(raw):
"""
规范化带宽值。API 返回如 "10M", "2M", "0M"。
输出: "10Mbps", "2Mbps", "-"
"""
if not raw or str(raw) in ("-", ""):
return "-"
s = str(raw).rstrip("Mm") # 去掉 API 自带的 "M" 后缀
if s == "0":
return "-"
return f"{s}Mbps"
def fmt_timestamp(ms_value):
"""
毫秒时间戳 → "YYYY-MM-DD" 日期字符串。
输入: 1780934405000, "-", "", 0, None
输出: "2026-06-07", "-", "-", "-", "-"
"""
if not ms_value or str(ms_value) in ("-", "", "0"):
return "-"
try:
return datetime.fromtimestamp(int(ms_value) / 1000).strftime("%Y-%m-%d")
except (ValueError, TypeError, OSError):
return str(ms_value)
def fmt_status(value, default="-"):
"""
规范化状态/枚举字段。空字符串统一显示为 default。
"""
if not value or str(value).strip() == "":
return default
return str(value)使用示例:
attr = run_cli_safe("describe-smart-access-gateway-attribute", ...)
vpn = fmt_status(attr.get("VpnStatus")) # "" → "-", "up" → "up"
bw = fmt_bandwidth(attr.get("MaxBandwidth")) # "10M" → "10Mbps"
end = fmt_timestamp(attr.get("EndTime")) # 1780934405000 → "2026-06-07"注意事项:
MaxBandwidth字段已包含 "M" 后缀(表示 Megabit),脚本不可再追加 "M" 或 "Mbps"- 时间戳统一为毫秒级(13位数字),需除以 1000 再调用
fromtimestamp() EndTime为空或0表示该实例可能是按量付费或未激活,显示为 "-" 而非报错VpnStatus空字符串不等于 "down",只是属性未返回,应显示 "-"
---
Pattern 9: 分页处理与数据一致性断言
适用场景:任何返回结构包含 TotalCount 的 List 类 API(describe-smart-access-gateways、describe-acls、describe-qoses、describe-cloud-connect-networks、describe-flow-logs 等)。
核心逻辑:--page-size 上限 50,实际资源可能超过该值;仅取首页会造成漏抓(评测以 Pagination not handled 判失败)。必须迭代 --page-number 直至累计 ≥ TotalCount。
# Bash 骨架 — 以 DescribeSmartAccessGateways 为例
fetch_all_pages() {
local API="$1"; local REGION="$2"; local OUT="$3"
local PAGE=1; local PAGE_SIZE=50; local TOTAL=0; local FETCHED=0
echo '[]' > "$OUT"
while : ; do
local TMP=$(mktemp)
aliyun smartag "$API" --biz-region-id "$REGION" --page-size $PAGE_SIZE --page-number $PAGE > "$TMP" || break
TOTAL=$(jq -r '.TotalCount // 0' "$TMP")
# 列表字段名随 API 变,需适配:SmartAccessGateways/SmartAccessGateway, Acls/Acl, Qoses/Qos …
jq -s '.[0] + (.[1].SmartAccessGateways.SmartAccessGateway // [])' "$OUT" "$TMP" > "$OUT.new" && mv "$OUT.new" "$OUT"
FETCHED=$(jq 'length' "$OUT")
rm -f "$TMP"
[ "$FETCHED" -ge "$TOTAL" ] && break
PAGE=$((PAGE + 1))
done
# 一致性断言:实际拼接条数必须等于 TotalCount
[ "$FETCHED" -eq "$TOTAL" ] || { echo "FAIL: $API@$REGION fetched=$FETCHED total=$TOTAL"; exit 1; }
}报告一致性断言:生成 Markdown 报告前,验证 Summary 中红/黄/绿计数之和 ≡ 实际明细项总数:
RED=$(jq '[.[] | select(.level=="red")] | length' /tmp/sag_findings.json)
YEL=$(jq '[.[] | select(.level=="yellow")]| length' /tmp/sag_findings.json)
GRN=$(jq '[.[] | select(.level=="green")] | length' /tmp/sag_findings.json)
ALL=$(jq 'length' /tmp/sag_findings.json)
[ $((RED + YEL + GRN)) -eq "$ALL" ] || { echo "FAIL: summary count mismatch"; exit 1; }注意事项:
--page-size超过 50 会被 CLI 拒绝(见 common pitfalls)。- 不同 API 的列表字段名不一致(
SmartAccessGateways.SmartAccessGateway/Acls.Acl/Qoses.Qos/CloudConnectNetworks.CloudConnectNetwork…),使用// []兜底防 null。 - Summary 计数不能硬编码(如
"normal: 8"),必须从明细数组现算。
---
Anti-Patterns(已知踩坑,务必避免)
| 错误做法 | 后果 | 正确做法 |
|---|---|---|
| 硬编码区域列表 | 遗漏 cn-zhangjiakou-spe 等非标准区域 | 调用 describe-regions 动态获取 |
| 对所有实例调用所有 12 项 | 大量 MissingSmartAGSn 无效请求 | 先分类再调用 |
| 多 SN 字段直接传入 API | 返回 DeviceNotExist | 按逗号拆分逐个查询 |
describe-dnat-entries 用 --smart-ag-id | 返回 MissingSagId | 用 --sag-id |
| 假设 API 列表返回一定是 array | 单条时崩溃 | 用 safe_extract_list 容错 |
| 区域级 API 每实例调一次 | 65 实例 × 4 = 260 次冗余 | 每区域只调一次 |
| 报错直接 raise 中断 | 一个失败全部中止 | 优雅降级,继续下一个 |
| MaxBandwidth 直接拼接 "Mbps" | 显示 "10MMbps" | 先 rstrip("Mm") 再拼接单位 |
| EndTime 直接输出原始值 | 显示 13 位数字,用户无法理解 | fromtimestamp(int/1000) 转日期 |
| 空字符串字段不做兜底 | 报告出现空白或拼接异常 | 用 fmt_status() 统一转 "-" |
用 basic info 的 VpnStatus 字段判定隧道状态 | 丢失需调 describe-smart-access-gateway-attribute 才能拿到的详细属性 | 必须调 describe-smart-access-gateway-attribute 拿完整属性 |
用 AssociatedCcnId 字段代替 CCN 查询 | 缺失 CcnName / CenId / 绑定信息 | 必须调 describe-cloud-connect-networks |
用 AclIds 字段代替 ACL 查询 | 拿不到 rules / entries / 生效实例数 | 必须调 describe-acls |
仅看 HardwareVersion 字符串代替设备硬件信息 | 缺失固件版本、设备型号、序列号 | 必须调 describe-sag-device-info |
| 混淆分类与替代调用 | TestCase 期望 API 没命中 | basic info 是“分类器”不是“替代品”,遵守 SKILL.md 的 Mandatory Call Contracts |
| CLI JSON 响应直接 dump 到对话 | 结果出现大段 region id / key / 无关字段 | 重定向到 /tmp/sag_*.json,对话只给摘要 |
SAG Inspection Rules
Detailed threshold definitions and judgment logic for each inspection item.
Status Levels
| Level | Symbol | Meaning | Action Required |
|---|---|---|---|
| Green | PASS | Normal, no action needed | None |
| Yellow | WARN | Attention needed, potential issue | Monitor or plan fix |
| Red | FAIL | Critical issue, immediate action | Fix immediately |
---
Rule 1: Device Online Status
API: describe-smart-access-gateways -> Status field
Judgment:
if Status == "Active":
return GREEN, "Device online and active"
elif Status == "Offline":
return RED, "Device offline - check power, network cable, 4G card"
elif Status == "Ordered":
return YELLOW, "Device ordered but not yet activated"
else:
return YELLOW, f"Abnormal status: {Status}"Recommended Actions (Red): 1. Check physical power supply 2. Check network cable connection on WAN port 3. Check 4G SIM card if using cellular backup 4. Verify local firewall allows outbound UDP 500/4500 5. Contact Alibaba Cloud support if persists >30 minutes
---
Rule 2: VPN Tunnel Status
API: describe-smart-access-gateway-attribute -> VpnStatus field
Judgment:
if VpnStatus == "UP":
return GREEN, "VPN tunnel established"
elif VpnStatus == "DOWN":
return RED, "VPN tunnel down"
else:
return YELLOW, f"VPN status unknown: {VpnStatus}"Recommended Actions (Red): 1. Check device online status first (Rule 1) 2. Verify firewall allows UDP 500, UDP 4500 to POP access point IPs 3. Check if access point IP has changed (use ListSmartAGByAccessPoint) 4. Verify WAN port has valid public IP 5. If behind NAT, ensure NAT-T is supported
---
Rule 3: HA Status
API: describe-smart-access-gateway-ha
Judgment:
if DeviceLevelBackupState == "Active" and all links normal:
return GREEN, "HA normal, primary active"
elif frequent_switchover detected:
return YELLOW, "HA flapping detected"
elif standby_offline:
return RED, "Standby device offline, no redundancy"
else:
return GREEN, "HA not configured (single device)"Recommended Actions (Yellow/Red):
- Flapping: Check physical links, avoid dual-active scenario
- Standby offline: Check standby device power and connectivity
- Consider upgrading firmware if flapping persists
---
Rule 4: Instance Expiry
API: describe-smart-access-gateways -> EndTime field
Judgment:
days_remaining = (EndTime - now).days
if days_remaining > 30:
return GREEN, f"Expires in {days_remaining} days"
elif days_remaining > 7:
return YELLOW, f"Expires in {days_remaining} days - renew soon"
elif days_remaining > 0:
return RED, f"Expires in {days_remaining} days - URGENT renewal needed"
else:
return RED, f"EXPIRED {abs(days_remaining)} days ago - service may be suspended"Additional Context:
- Expired instances may lose VPN connectivity within 24-72 hours
Why these thresholds: 30 days gives enough lead time for procurement approval and renewal processing in enterprise environments. 7 days is the critical window because Alibaba Cloud sends final warning notifications at T-7, and post-expiry grace periods are typically 24-72 hours before service suspension.
---
Rule 5: Packet Drop (DropTopN)
API: describe-sag-drop-topn (with --size 10)
Judgment:
try:
top_n = get_drop_topn(sag_id, size=10)
except SAG_QUERY_TOPN_ERROR:
return SKIPPED, "DropTopN not supported in this region (edge/special region)"
drop_rate = calculate_drop_rate(top_n) # aggregated % of dropped packets
if drop_rate < 0.01: # < 1%
return GREEN, f"Packet drop rate {drop_rate*100:.2f}% (healthy)"
elif drop_rate < 0.05: # 1% - 5%
return YELLOW, f"Packet drop rate {drop_rate*100:.2f}% (degraded)"
else: # >= 5%
return RED, f"Packet drop rate {drop_rate*100:.2f}% (severe loss)"Availability notes:
- Returns real data in major regions (cn-shanghai, cn-hangzhou, ap-southeast-1, etc.)
- May return
SAG_QUERY_TOPN_ERRORin some edge regions (e.g. cn-zhangjiakou-spe) - On error, do NOT abort the inspection — mark this item as
skipped due to region unsupportedand continue
Recommended Actions (Yellow/Red):
- Correlate with Rule 2 (VPN tunnel) and Rule 6 (4G link) — packet drop is often downstream of a degraded underlay link
- Check WAN interface error counters via
describe-sag-wan-list - If drops cluster on a specific destination CIDR, review ACL/routing for that target
---
Rule 6: 4G Link Status
API: describe-sag-wan-4g
Judgment:
if Status == "connected" and Strength >= -85:
return GREEN, f"4G connected, signal {Strength}dBm (good)"
elif Status == "connected" and Strength >= -100:
return YELLOW, f"4G connected, signal {Strength}dBm (weak)"
elif Status == "connected" and Strength < -100:
return RED, f"4G connected but signal very weak {Strength}dBm"
elif Status == "disconnected" or IP is empty:
return RED, "4G disconnected - check SIM card"
else:
return YELLOW, f"4G status: {Status}"Signal Strength Reference (dBm):
- Excellent: > -65
- Good: -65 to -85
- Fair: -85 to -100
- Poor: < -100
Why these thresholds: Based on 3GPP LTE reference signal received power (RSRP) standards. -85 dBm is the typical edge-of-cell threshold where modulation drops to lower order (slower speeds). -100 dBm approaches the sensitivity limit of most 4G modules in SAG devices, causing frequent disconnections and high retransmission rates.
Recommended Actions (Red):
- Check SIM card insertion and activation
- Verify SIM card has data balance
- Check antenna connection
- Try different SIM card slot if available
- Consider external antenna for weak signal areas
---
Rule 7: CCN/CEN Binding Completeness
API: describe-cloud-connect-networks + describe-grant-sag-rules
Judgment:
sag_has_ccn = (AssociatedCcnId is not None and not empty)
ccn_has_cen = (CCN.AssociatedCenId is not None and not empty)
has_grant_rules = (GrantRules is not empty)
if sag_has_ccn and ccn_has_cen and has_grant_rules:
return GREEN, "Full chain: SAG -> CCN -> CEN (authorized)"
elif sag_has_ccn and ccn_has_cen and not has_grant_rules:
return YELLOW, "CCN bound to CEN but no cross-account authorization found"
elif sag_has_ccn and not ccn_has_cen:
return YELLOW, "SAG bound to CCN but CCN not attached to CEN"
else:
return RED, "SAG not bound to any CCN - cloud connectivity not established"Chain Verification:
SAG -> CCN -> CEN -> VPC (target)
| | |
bind attach route propagationWhy this check matters: SAG cloud connectivity requires a complete three-hop chain (SAG->CCN->CEN->VPC). From 701 historical support tickets, 11.4% of issues were caused by incomplete bindings — users often bind SAG to CCN but forget to authorize CCN to CEN, or miss the cross-account grant step. Checking the full chain proactively prevents these common misconfigurations.
Recommended Actions:
- Red: bindsmartaccessgateway to a CCN first
- Yellow (no CEN): Attach CCN to a CEN instance
- Yellow (no grant): For cross-account, run GrantSagInstanceToCcn
---
Rule 8: Route Health
API: describe-sag-route-list
Judgment:
routes = get_route_list()
has_default = any(r.DestinationCidr == "0.0.0.0/0" for r in routes)
route_count = len(routes)
has_conflicts = check_overlapping_cidrs(routes)
if route_count > 0 and not has_conflicts:
return GREEN, f"{route_count} routes, no conflicts"
elif route_count == 0:
return RED, "No routes configured - traffic cannot be forwarded"
elif has_conflicts:
return YELLOW, f"{route_count} routes but overlapping CIDRs detected"
else:
return GREEN, f"{route_count} routes configured"Conflict Detection Logic:
- Two routes overlap if their destination CIDRs intersect
- Longest prefix match applies, but overlaps may indicate misconfiguration
- Multiple default routes to different next-hops indicate potential black hole
---
Rule 9: ACL/QoS Sanity
API: describe-acls + ACL rule queries
Judgment:
acl_bound = (ACL.SagCount > 0)
rules = get_acl_rules(acl_id)
has_deny_all = any(r.Policy == "drop" and r.DestCidr == "0.0.0.0/0" for r in rules)
has_allow_before_deny = check_allow_rules_before_deny_all(rules)
if not acl_bound:
return GREEN, "No ACL bound (all traffic allowed by default)"
elif acl_bound and has_deny_all and has_allow_before_deny:
return GREEN, "ACL configured with whitelist pattern"
elif acl_bound and has_deny_all and not has_allow_before_deny:
return RED, "ACL has deny-all but no allow rules - all traffic blocked"
elif acl_bound and not has_deny_all:
return YELLOW, "ACL bound but no deny-all fallback - may not be effective"
else:
return GREEN, "ACL rules appear reasonable"---
Rule 10: Flow Logs
API: describe-flow-logs
Judgment:
flow_logs = get_flow_logs(sag_id)
active_logs = [fl for fl in flow_logs if fl.Status == "Active"]
if len(active_logs) > 0:
return GREEN, f"Flow logs enabled ({len(active_logs)} active)"
else:
return YELLOW, "Flow logs not enabled - troubleshooting visibility limited"Recommended Actions (Yellow):
- Enable flow logs for better traffic visibility
- Configure SLS project and logstore
- Useful for: bandwidth analysis, security audit, troubleshooting connectivity
---
Composite Scoring
When running full inspection, calculate overall health score:
def calculate_overall_status(results):
red_count = sum(1 for r in results if r.level == RED)
yellow_count = sum(1 for r in results if r.level == YELLOW)
if red_count > 0:
return "CRITICAL", f"{red_count} critical issues require immediate attention"
elif yellow_count >= 3:
return "ATTENTION NEEDED", f"{yellow_count} items need attention"
elif yellow_count > 0:
return "MOSTLY HEALTHY", f"{yellow_count} minor items to review"
else:
return "HEALTHY", "All inspection items passed"Priority of Remediation
When multiple issues found, fix in this order: 1. Device offline (Rule 1) - nothing works without connectivity 2. VPN tunnel down (Rule 2) - cloud access requires tunnel 3. Instance expired (Rule 4) - service may be suspended 4. CCN/CEN not bound (Rule 7) - routing chain broken 5. Route issues (Rule 8) - traffic cannot reach destination 6. Packet drop severe (Rule 5) - underlay link degraded 7. 4G link issues (Rule 6) - backup link degradation 8. Other items - operational improvements
SAG OpenAPI Reference
Complete parameter reference for SAG Pilot v1.0 APIs.
CLI Convention
All CLI examples below use the plugin mode (requires aliyun CLI >= 3.3.3 with smartag plugin installed).
aliyun smartag <api-name-in-kebab-case> \
--endpoint smartag.<RegionId>.aliyuncs.com \
--biz-region-id <RegionId> \
--read-timeout 30 \
--connect-timeout 15 \
[--params ...]IMPORTANT: In plugin mode, must use --endpoint (not --region) for endpoint routing:
--endpoint smartag.<RegionId>.aliyuncs.com= controls which regional endpoint the request is routed to (REQUIRED)--biz-region-id= API business parameter (RegionId)- The plugin's
--regionflag has an incomplete mapping (eu-west-1, us-east-1, cn-zhangjiakou-spe are NOT recognized and will fallback to cn-hangzhou) - Without
--endpoint, all requests default to the CLI profile's region
Parameter Naming
| Parameter | Plugin Mode | Notes |
|---|---|---|
| Endpoint | --endpoint smartag.<r>.aliyuncs.com | Controls regional routing (REQUIRED) |
| RegionId | --biz-region-id | Business region parameter |
| SmartAGId | --smart-ag-id | Instance ID |
| SmartAGSn | --smart-ag-sn | Device serial number |
| PageSize | --page-size | Pagination |
| PageNumber | --page-number | Pagination |
| SagId | --sag-id | DNAT entries only |
| Size | --size | TopN queries |
Common Parameters
All APIs require:
- RegionId (String, Required): Region of the SAG instance
- To get all supported regions, call
describe-regions(see Region Endpoint Reference section below)
Configuration Query APIs
describe-smart-access-gateways
List SAG instances with filtering.
CLI (plugin mode):
aliyun smartag describe-smart-access-gateways \
--biz-region-id cn-shanghai \
--page-size 50 \
--page-number 1 \
--smart-ag-id sag-xxxxx \
--status ActiveParameters:
| Name | Type | Required | Description |
|---|---|---|---|
| RegionId | String | Yes | Region ID |
| SmartAGId | String | No | Filter by instance ID |
| Name | String | No | Filter by name (fuzzy match) |
| Status | String | No | Filter: Active, Offline, Ordered, Creating |
| AssociatedCcnId | String | No | Filter by CCN binding |
| PageSize | Integer | No | 1-50, default 10 |
| PageNumber | Integer | No | Default 1 |
Key Response Fields:
SmartAccessGateways[].SmartAGId- Instance IDSmartAccessGateways[].Name- Instance nameSmartAccessGateways[].Status- Active/Offline/OrderedSmartAccessGateways[].MaxBandwidth- Bandwidth in MbpsSmartAccessGateways[].EndTime- Expiry timestamp (ms)SmartAccessGateways[].AssociatedCcnId- Bound CCN IDSmartAccessGateways[].CidrBlock- Private CIDRSmartAccessGateways[].Devices[].SerialNumber- Device SNSmartAccessGateways[].Devices[].HaState- HA role
---
describe-smart-access-gateway-attribute
Get detailed attributes of a single SAG instance.
CLI (plugin mode):
aliyun smartag describe-smart-access-gateway-attribute \
--biz-region-id cn-shanghai \
--smart-ag-id sag-xxxxxParameters:
| Name | Type | Required | Description |
|---|---|---|---|
| RegionId | String | Yes | Region ID |
| SmartAGId | String | Yes | SAG instance ID |
Key Response Fields:
VpnStatus- VPN tunnel status (UP/DOWN)ResellerId- Reseller ID if applicableBoxControllerIp- Controller IPAccessPointId- POP access pointRoutingStrategy- Routing strategy
---
describe-sag-device-info
Get device hardware information.
CLI (plugin mode):
aliyun smartag describe-sag-device-info \
--biz-region-id cn-shanghai \
--smart-ag-id sag-xxxxx \
--smart-ag-sn sagxxxxxxxxxxParameters:
| Name | Type | Required | Description |
|---|---|---|---|
| SmartAGId | String | Yes | SAG instance ID |
| SmartAGSn | String | Yes | Device serial number |
Key Response Fields:
SmartAGType- Device model (SAG-1000, SAG-100WM, etc.)Version- Current software versionControllerState- Controller connection stateVpnState- VPN stateResettableStatus- Whether device can be reset
---
describe-smart-access-gateway-versions
Get software version info.
CLI (plugin mode):
aliyun smartag describe-smart-access-gateway-versions \
--biz-region-id cn-shanghai \
--smart-ag-id sag-xxxxx \
--smart-ag-sn sagxxxxxxxxxx \
--version-type DeviceKey Response Fields:
SmartAGVersions[].CurrentVersion- Current versionSmartAGVersions[].LatestVersion- Latest available versionSmartAGVersions[].CreateTime- Version release time
---
describe-sag-wan-list
Get WAN port configurations.
CLI (plugin mode):
aliyun smartag describe-sag-wan-list \
--biz-region-id cn-shanghai \
--smart-ag-id sag-xxxxx \
--smart-ag-sn sagxxxxxxxxxxKey Response Fields:
TaskStates[].WanInterfaces[].PortName- Port name (eth0, etc.)TaskStates[].WanInterfaces[].IPType- DHCP/Static/PPPoETaskStates[].WanInterfaces[].IP- WAN IPTaskStates[].WanInterfaces[].Mask- Subnet maskTaskStates[].WanInterfaces[].Gateway- Gateway IP
---
describe-sag-wan-4g
Get 4G WAN card status.
CLI (plugin mode):
aliyun smartag describe-sag-wan-4g \
--biz-region-id cn-shanghai \
--smart-ag-id sag-xxxxx \
--smart-ag-sn sagxxxxxxxxxxKey Response Fields:
Strength- Signal strengthIP- 4G assigned IPStatus- Connection statusTrafficState- Traffic state
---
describe-sag-static-route-list
Get static route configurations.
CLI (plugin mode):
aliyun smartag describe-sag-static-route-list \
--biz-region-id cn-shanghai \
--smart-ag-id sag-xxxxx \
--smart-ag-sn sagxxxxxxxxxxKey Response Fields:
StaticRoutes[].DestinationCidr- Destination CIDRStaticRoutes[].NextHop- Next hop IPStaticRoutes[].PortName- Outgoing port
---
describe-sag-route-protocol-bgp
Get BGP protocol configuration.
CLI (plugin mode):
aliyun smartag describe-sag-route-protocol-bgp \
--biz-region-id cn-shanghai \
--smart-ag-id sag-xxxxx \
--smart-ag-sn sagxxxxxxxxxxKey Response Fields:
RouterId- BGP Router IDLocalAs- Local AS numberHoldTime- Hold timerKeepAlive- Keepalive intervalTaskStates[].Neighbors[]- BGP neighbors
---
describe-sag-route-protocol-ospf
Get OSPF protocol configuration.
CLI (plugin mode):
aliyun smartag describe-sag-route-protocol-ospf \
--biz-region-id cn-shanghai \
--smart-ag-id sag-xxxxx \
--smart-ag-sn sagxxxxxxxxxxKey Response Fields:
RouterId- OSPF Router IDAreaId- OSPF AreaDeadTime- Dead intervalHelloTime- Hello intervalTaskStates[].AdvertiseRoutes[]- Advertised routes
---
describe-cloud-connect-networks
Get CCN (Cloud Connect Network) instances.
CLI (plugin mode):
aliyun smartag describe-cloud-connect-networks \
--biz-region-id cn-shanghai \
--ccn-id ccn-xxxxx \
--page-size 50Key Response Fields:
CloudConnectNetworks[].CcnId- CCN IDCloudConnectNetworks[].Name- CCN nameCloudConnectNetworks[].AssociatedCenId- Bound CEN IDCloudConnectNetworks[].SnatCidrBlock- SNAT CIDRCloudConnectNetworks[].CidrBlock- CCN CIDR
---
describe-grant-sag-rules
Get cross-account CEN authorization rules.
CLI (plugin mode):
aliyun smartag describe-grant-sag-rules \
--biz-region-id cn-shanghai \
--smart-ag-id sag-xxxxxKey Response Fields:
GrantRules[].CenUid- Authorized CEN owner UIDGrantRules[].CenInstanceId- CEN instance IDGrantRules[].SmartAGId- SAG instanceGrantRules[].CreateTime- Authorization time
---
describe-acls
Get ACL instances.
CLI (plugin mode):
aliyun smartag describe-acls \
--biz-region-id cn-shanghai \
--acl-ids '["acl-xxxxx"]' \
--page-size 50Key Response Fields:
Acls[].AclId- ACL IDAcls[].AclName- ACL nameAcls[].SagCount- Number of bound SAG instances
---
describe-qoses
Get QoS policy instances.
CLI (plugin mode):
aliyun smartag describe-qoses \
--biz-region-id cn-shanghai \
--qos-ids '["qos-xxxxx"]'Key Response Fields:
QosPolicies[].QosId- QoS IDQosPolicies[].QosName- NameQosPolicies[].SagCount- Bound SAG count
---
describe-dnat-entries / describe-snat-entries
Get NAT rules.
⚠️ PARAMETER NAME DIFFERENCE: describe-dnat-entries uses --sag-id (NOT --smart-ag-id). This is inconsistent with other SAG APIs. describe-snat-entries uses standard --smart-ag-id.
CLI (plugin mode):
# DNAT - Note: parameter is --sag-id, NOT --smart-ag-id
aliyun smartag describe-dnat-entries \
--biz-region-id cn-shanghai \
--sag-id sag-xxxxx \
--page-size 50
# SNAT - uses standard --smart-ag-id
aliyun smartag describe-snat-entries \
--biz-region-id cn-shanghai \
--smart-ag-id sag-xxxxx \
--page-size 50Parameters (describe-dnat-entries):
| Name | Type | Required | Description |
|---|---|---|---|
| RegionId | String | Yes | Region ID |
| SagId | String | Yes | SAG instance ID (--sag-id in plugin mode) |
| PageSize | Integer | No | Default 10 |
Parameters (describe-snat-entries):
| Name | Type | Required | Description |
|---|---|---|---|
| RegionId | String | Yes | Region ID |
| SmartAGId | String | Yes | SAG instance ID |
| PageSize | Integer | No | Default 10 |
Key Response Fields (DNAT):
DnatEntries[].ExternalIp/ExternalPortDnatEntries[].InternalIp/InternalPortDnatEntries[].IpProtocol- tcp/udp
---
describe-flow-logs
Get flow log configurations.
CLI (plugin mode):
aliyun smartag describe-flow-logs \
--biz-region-id cn-shanghai \
--flow-log-id fl-xxxxxKey Response Fields:
FlowLogs[].FlowLogId- Flow log IDFlowLogs[].Status- Active/InactiveFlowLogs[].ProjectName- SLS projectFlowLogs[].LogStoreName- SLS logstoreFlowLogs[].SmartAGId- Bound SAG
---
describe-health-checks
Get health check configurations.
⚠️ Note: This API has been observed to return InvalidApi.NotFound in the 2018-03-13 version in some regions (tested 2026-05). If encountered, skip this check gracefully and note in report. This may be resolved in future versions.
CLI (plugin mode):
aliyun smartag describe-health-checks \
--biz-region-id cn-shanghai \
--smart-ag-id sag-xxxxxKey Response Fields:
HealthChecks[].HcInstanceId- Health check IDHealthChecks[].Name- NameHealthChecks[].DstIpAddr- Probe target IPHealthChecks[].ProbeInterval- Interval (seconds)HealthChecks[].FailCountThreshold- Failure thresholdHealthChecks[].Status- ok/failed
---
describe-smart-access-gateway-client-users
Get SAG APP client users.
CLI (plugin mode):
aliyun smartag describe-smart-access-gateway-client-users \
--biz-region-id cn-shanghai \
--smart-ag-id sag-xxxxx \
--page-size 50Key Response Fields:
Users[].UserName- Username (email)Users[].State- 0=normal, 1=disabledUsers[].Bandwidth- Allocated bandwidth (Kbps)Users[].ClientIp- Assigned IP
---
describe-sag-online-client-statistics
Get online client statistics.
CLI (plugin mode):
aliyun smartag describe-sag-online-client-statistics \
--biz-region-id cn-shanghai \
--smart-ag-id sag-xxxxxKey Response Fields:
SagStatistics[].OnlineCount- Current online usersSagStatistics[].SmartAGId- SAG instance
---
describe-sag-current-dns
Get current DNS configuration.
CLI (plugin mode):
aliyun smartag describe-sag-current-dns \
--biz-region-id cn-shanghai \
--smart-ag-id sag-xxxxx \
--smart-ag-sn sagxxxxxxxxxxKey Response Fields:
MasterDns- Primary DNSSlaveDns- Secondary DNS
---
Inspection-Specific APIs
describe-smart-access-gateway-ha
Get HA (High Availability) status.
CLI (plugin mode):
aliyun smartag describe-smart-access-gateway-ha \
--biz-region-id cn-shanghai \
--smart-ag-id sag-xxxxxKey Response Fields:
DeviceLevelBackupState- Device-level HA stateLinkBackupInfoList[].MainLinkId- Primary linkLinkBackupInfoList[].BackupLinkId- Backup linkLinkBackupInfoList[].MainLinkState- Primary stateLinkBackupInfoList[].BackupLinkState- Backup state
---
describe-sag-traffic-topn
Get traffic top-N statistics.
CLI (plugin mode):
aliyun smartag describe-sag-traffic-topn \
--biz-region-id cn-shanghai \
--smart-ag-id sag-xxxxx \
--size 10Key Response Fields:
TrafficTopN[].InstanceId- InstanceTrafficTopN[].TrafficRate- Current rate (bps)TrafficTopN[].Name- Instance name
---
describe-sag-drop-topn
Get packet drop top-N statistics.
CLI (plugin mode):
aliyun smartag describe-sag-drop-topn \
--biz-region-id cn-shanghai \
--size 10Key Response Fields:
DropTopN[].InstanceId- InstanceDropTopN[].DropRate- Drop rate percentageDropTopN[].Name- Instance name
---
Region Endpoint Reference
IMPORTANT: Do NOT rely on this static table for "query all regions" scenarios. Always call describe-regions first to get the authoritative, up-to-date list.
describe-regions
aliyun smartag describe-regions \
--endpoint smartag.cn-shanghai.aliyuncs.com \
--read-timeout 30 \
--connect-timeout 15Returns an array of { RegionId, LocalName, RegionEndpoint } for all SAG-supported regions.
Known Regions (for reference only, may be outdated)
| Region | RegionId | Endpoint |
|---|---|---|
| 华东2(上海) | cn-shanghai | smartag.cn-shanghai.aliyuncs.com |
| 中国香港 | cn-hongkong | smartag.cn-hongkong.aliyuncs.com |
| 新加坡 | ap-southeast-1 | smartag.ap-southeast-1.aliyuncs.com |
| 马来西亚(吉隆坡) | ap-southeast-3 | smartag.ap-southeast-3.aliyuncs.com |
| 印度尼西亚(雅加达) | ap-southeast-5 | smartag.ap-southeast-5.aliyuncs.com |
| 日本(东京) | ap-northeast-1 | smartag.ap-northeast-1.aliyuncs.com |
| 德国(法兰克福) | eu-central-1 | smartag.eu-central-1.aliyuncs.com |
| 英国(伦敦) | eu-west-1 | smartag.eu-west-1.aliyuncs.com |
| 美国(弗吉尼亚) | us-east-1 | smartag.us-east-1.aliyuncs.com |
| 张北SPE | cn-zhangjiakou-spe | smartag.cn-zhangjiakou-spe.aliyuncs.com |
---
Response Structure Notes (Fault Tolerance)
SAG API responses have inconsistent list wrapping. When parsing responses, MUST handle all of the following patterns:
Pattern 1: Standard nested structure (most common)
{
"Wans": {
"Wan": [
{"PortName": "1", "IP": "192.168.1.1"},
{"PortName": "2", "IP": "192.168.2.1"}
]
}
}Pattern 2: Single item not wrapped in array
When only one item exists, it may be returned as a dict instead of a single-element array:
{
"Wans": {
"Wan": {"PortName": "1", "IP": "192.168.1.1"}
}
}Pattern 3: Container is directly a list
Rarely, the intermediate container may be a list instead of a dict:
{
"Wans": [
{"PortName": "1", "IP": "192.168.1.1"}
]
}Recommended Parsing Pattern
Always use this defensive extraction pattern when parsing list data from SAG API responses:
def safe_extract_list(data, container_key, item_key):
"""
Safely extract a list from SAG API response.
Handles all known response structure variations.
Example: safe_extract_list(response, "Wans", "Wan")
"""
if not isinstance(data, dict):
return []
container = data.get(container_key, {})
# Pattern 3: container is directly a list
if isinstance(container, list):
return container
# Pattern 1 & 2: container is a dict with item_key
if isinstance(container, dict):
items = container.get(item_key, [])
# Pattern 2: single item as dict
if isinstance(items, dict):
return [items]
# Pattern 1: normal list
if isinstance(items, list):
return items
return []Known Parameter Name Inconsistencies
| API (plugin mode) | Parameter | Notes |
|---|---|---|
| describe-dnat-entries | --sag-id | Only this API uses --sag-id (NOT --smart-ag-id) |
| describe-snat-entries | --smart-ag-id | Standard naming |
| describe-sag-wan-list | --smart-ag-sn | Requires device SN |
| describe-sag-current-dns | --smart-ag-sn | Requires device SN |
Common Error Codes Reference
| Error Code | Meaning | Recommended Handling |
|---|---|---|
| MissingSmartAGSn | Device SN not provided | Skip - instance has no physical device |
| SmartAccessGatewayNotOnline | Device offline | Record status, cannot query live config |
| Sag.DeviceNotExist | SN doesn't match any device | Check if multi-SN needs splitting |
| InstanceNotExit | Instance or device not found | May be a multi-SN issue (see below) |
| InvalidApi.NotFound | API may not exist in current version | Skip gracefully, note in report |
| MissingSagId | describe-dnat-entries needs --sag-id | Use --sag-id instead of --smart-ag-id |
Multi-SN Device Handling
Some SAG instances have HA (dual device) configuration. The SerialNumber field contains comma-separated SNs:
SerialNumber: "sag61dacczh,sag61daccq6"MUST split and query individually:
sn_field = instance.get("SerialNumber", "")
sn_list = [s.strip() for s in sn_field.split(",") if s.strip()]
# Query each device separately
for idx, sn in enumerate(sn_list):
role = "主设备" if idx == 0 else "备设备"
device_info = run_cli("describe-sag-device-info", smart_ag_sn=sn)
wan_config = run_cli("describe-sag-wan-list", smart_ag_sn=sn)
# ... other device-level queriesPassing the full comma-separated string will return Sag.DeviceNotExist or InstanceNotExit.
Response Field Format Quirks
SAG API 的部分响应字段返回值格式不符合直觉,直接拼接展示会导致显示异常。在生成报告或脚本时,必须对以下字段做规范化处理:
| API | 字段 | 实际返回值格式 | 常见误用 | 正确处理 |
|---|---|---|---|---|
| describe-smart-access-gateway-attribute | MaxBandwidth | 带单位后缀的字符串,如 "10M", "2M", "0M" | 直接拼接 "Mbps" 导致 "10MMbps" | 先 strip 末尾的 "M" 再拼接单位 |
| describe-smart-access-gateway-attribute | EndTime | 毫秒级 Unix 时间戳,如 1780934405000 | 直接输出原始数字 | datetime.fromtimestamp(int(v)/1000) 转换 |
| describe-smart-access-gateway-attribute | CreateTime | 毫秒级 Unix 时间戳 | 同上 | 同上 |
| describe-smart-access-gateways (列表) | EndTime | 毫秒级 Unix 时间戳 | 同上 | 同上 |
| describe-smart-access-gateways (列表) | DataPlan | 流量值(字节数),0 表示不限流 | 直接当作 MB/GB 显示 | 需除以 1024^n 并判断 0 特殊含义 |
| describe-sag-wan-4g | SignalStrength | 枚举字符串: "Unavailable", "Low", "Middle", "High" | 假设为数值 | 直接作为文本展示 |
| describe-smart-access-gateway-attribute | VpnStatus | 枚举: "up", "down", 空字符串 | 空串当作有效状态 | 空串显示为 "-" |
通用原则:
- 时间戳字段(
EndTime,CreateTime等)统一为毫秒级,需要除以 1000 再传给datetime.fromtimestamp() - 带宽字段已自带单位后缀
"M"(Megabit),脚本不应再追加 "M" 或 "Mbps" - 返回空字符串
""和 未返回该字段(KeyError)要区分处理:空串用"-"展示,缺字段用默认值
RAM Policies
Required RAM permissions for alibabacloud-sag-pilot skill. All operations are read-only (Describe/List actions only).
Required Permissions
{
"Version": "1",
"Statement": [
{
"Effect": "Allow",
"Action": [
"smartag:DescribeSmartAccessGateways",
"smartag:DescribeSmartAccessGatewayAttribute",
"smartag:DescribeSAGDeviceInfo",
"smartag:DescribeSmartAccessGatewayVersions",
"smartag:DescribeSagWanList",
"smartag:DescribeSagWan4G",
"smartag:DescribeSagStaticRouteList",
"smartag:DescribeSagRouteList",
"smartag:DescribeSagRouteProtocolBgp",
"smartag:DescribeSagRouteProtocolOspf",
"smartag:DescribeSagGlobalRouteProtocol",
"smartag:DescribeCloudConnectNetworks",
"smartag:DescribeGrantSagRules",
"smartag:DescribeSagVbrRelations",
"smartag:DescribeACLs",
"smartag:DescribeACLAttribute",
"smartag:DescribeQoses",
"smartag:DescribeDnatEntries",
"smartag:DescribeSnatEntries",
"smartag:DescribeFlowLogs",
"smartag:DescribeHealthChecks",
"smartag:DescribeHealthCheckAttribute",
"smartag:DescribeSmartAccessGatewayClientUsers",
"smartag:DescribeSagOnlineClientStatistics",
"smartag:DescribeSagCurrentDns",
"smartag:DescribeSmartAccessGatewayHa",
"smartag:DescribeSagTrafficTopN",
"smartag:ViewSmartAccessGatewayRoutes"
],
"Resource": "*"
}
]
}Permission Scope
- Access level: Read-only
- Service: Smart Access Gateway (smartag)
- Resource scope: All SAG resources under the authorized account
- No write/modify/delete permissions are required by this skill
Minimum Permission Policy Name Suggestion
AliyunSmartAGReadOnlyAccess
If this managed policy is not available, create a custom policy with the JSON above.
Related Commands: alibabacloud-smartag-pilot
All CLI commands used by this skill. Uses CLI plugin mode (aliyun-cli-smartag) with kebab-case API and parameter names.
---
Command Template
aliyun smartag <api-name-in-kebab-case> \
--endpoint smartag.<RegionId>.aliyuncs.com \
--biz-region-id <RegionId> \
--read-timeout 30 \
--connect-timeout 15 \
[--other-params ...]---
Region Discovery
| Plugin API | Description | Key Parameters |
|---|---|---|
| describe-regions | List all SAG-available regions | --endpoint (not --biz-region-id) |
---
Configuration Query Commands
| # | Plugin API | Description | Key Parameters |
|---|---|---|---|
| 1 | describe-smart-access-gateways | List instances (paginated) | --biz-region-id, --page-size, --page-number |
| 1 | describe-smart-access-gateway-attribute | Single instance detail | --smart-ag-id, --biz-region-id |
| 2 | describe-sag-device-info | Device hardware info | --smart-ag-id, --smart-ag-sn |
| 2 | describe-smart-access-gateway-versions | Software versions | --smart-ag-id, --biz-region-id |
| 3 | describe-sag-wan-list | WAN port list | --smart-ag-id, --smart-ag-sn |
| 3 | describe-sag-wan-4g | 4G link status | --smart-ag-id, --smart-ag-sn |
| 4 | describe-sag-static-route-list | Static routes | --smart-ag-id, --smart-ag-sn |
| 4 | describe-sag-route-list | Route table | --smart-ag-id, --smart-ag-sn, --biz-region-id |
| 4 | describe-sag-route-protocol-bgp | BGP config | --smart-ag-id, --smart-ag-sn, --biz-region-id |
| 4 | describe-sag-route-protocol-ospf | OSPF config | --smart-ag-id, --smart-ag-sn, --biz-region-id |
| 5 | describe-cloud-connect-networks | CCN list (region-level) | --biz-region-id, --page-size |
| 5 | describe-grant-sag-rules | CEN authorization rules | --smart-ag-id, --biz-region-id, --page-size |
| 5 | describe-sag-vbr-relations | VBR relations | --smart-ag-id, --biz-region-id |
| 6 | describe-acls | ACL list (region-level) | --biz-region-id, --page-size |
| 7 | describe-qoses | QoS list (region-level) | --biz-region-id, --page-size |
| 8 | describe-dnat-entries | DNAT rules | --sag-id (not --smart-ag-id), --biz-region-id |
| 8 | describe-snat-entries | SNAT rules | --smart-ag-id, --biz-region-id |
| 9 | describe-flow-logs | Flow log config (region-level) | --biz-region-id, --page-size |
| 10 | describe-health-checks | Health check probes | --smart-ag-id, --biz-region-id |
| 10 | describe-health-check-attribute | Health check detail | --hc-instance-id, --biz-region-id |
| 11 | describe-smart-access-gateway-client-users | APP client users | --smart-ag-id, --biz-region-id, --page-size |
| 11 | describe-sag-online-client-statistics | Online client stats | --smart-ag-id, --biz-region-id |
| 12 | describe-sag-current-dns | DNS servers | --smart-ag-id, --smart-ag-sn, --biz-region-id |
---
Status Inspection Commands (状态巡检)
| # | Plugin API | Description | Key Parameters (plugin) |
|---|---|---|---|
| 1 | describe-smart-access-gateways | Check Status field | --biz-region-id, --smart-ag-id |
| 2 | describe-smart-access-gateway-attribute | Check VPN tunnel status | --smart-ag-id |
| 3 | describe-smart-access-gateway-ha | HA status | --smart-ag-id, --biz-region-id |
| 4 | describe-smart-access-gateways | Check EndTime for expiry | --smart-ag-id |
| 5 | describe-sag-wan-4g | 4G signal strength | --smart-ag-id, --smart-ag-sn |
| 6 | describe-grant-sag-rules | CCN/CEN binding chain | --smart-ag-id, --biz-region-id |
| 7 | describe-sag-route-list | Route table health | --smart-ag-id, --smart-ag-sn |
| 8 | describe-acls | ACL binding sanity | --biz-region-id |
| 9 | describe-flow-logs | Flow log enablement | --biz-region-id |
---
Parameter Traps
| Plugin Command | Trap | Correct Usage |
|---|---|---|
| describe-dnat-entries | Instance ID param name differs | Use --sag-id (not --smart-ag-id) |
| Device-level APIs (#2,3,4,12) | Require device serial number | Must pass --smart-ag-sn |
| Device-level APIs with HA | Multi-SN in comma-separated field | Split and query each SN individually |
Verification Method: alibabacloud-smartag-pilot
Post-execution verification steps to confirm the skill ran correctly.
---
Configuration Query Verification
Step 1: API Response Validity
Verify that API calls returned valid JSON and no network/timeout errors:
# Quick connectivity test - should return JSON with Regions (plugin mode)
aliyun smartag describe-regions \
--endpoint smartag.cn-shanghai.aliyuncs.com \
--read-timeout 30 \
--connect-timeout 15Expected: JSON response containing Regions.Region[] array. Failure indicators: timeout, connection refused, non-JSON output.
Step 2: Instance Count Verification
After querying all regions, verify total instance count matches console:
# Count instances per region (plugin mode)
aliyun smartag describe-smart-access-gateways \
--endpoint smartag.<RegionId>.aliyuncs.com \
--biz-region-id <RegionId> \
--page-size 50Check: TotalCount in response should match the report summary.
Step 3: Report File Existence
# Verify report file was generated
ls -la <workspace>/SAG_*.mdExpected: File exists, size > 0, recent modification timestamp.
---
Status Inspection Verification (状态巡检)
Step 1: Coverage Check
All applicable inspection items should have a result (green/yellow/red). Missing items indicate API failures that should be noted in the report.
Step 2: Status Cross-Validation
# Verify device online status matches console (plugin mode)
aliyun smartag describe-smart-access-gateways \
--endpoint smartag.<RegionId>.aliyuncs.com \
--biz-region-id <RegionId> \
--smart-ag-id <sag-id>Check: Status field in response matches the inspection result.
Step 3: Report Completeness
Inspection report should contain:
- Instance identifier and region
- Inspection timestamp
- Overall status classification
- Summary counts (normal/attention/critical)
- Details for each non-green item
- Recommendations section
---
Common Verification Failures
| Symptom | Likely Cause | Resolution |
|---|---|---|
| Zero instances returned | Wrong region or expired instances | Verify RegionId, check console |
| Missing device info in report | Instance has no bound device (empty SN) | Expected for unbound hardware/software instances |
| Partial API failures in batch | Rate limiting or transient errors | Re-run; check for Throttling errors in output |
| Report file not found | Workspace path incorrect | Check output_path variable |