---
name: alicloud-ecs-cpu-inventory
description: List Alibaba Cloud International ECS instances (AliCloud equivalent of EC2) for a specified aliyun CLI profile and region. Outputs creation time, instance type/spec, last-7-day CPU utilization, unused-instance screening, and a sorted report under reports/. Use when user asks for 阿里云 ECS 清单, AliCloud EC2 list, ECS CPU usage, instance inventory with CPU metrics, or FinOps for Alibaba Cloud compute.
---

# Alibaba Cloud ECS CPU Inventory (International)

Collect ECS instance metadata and **last 7 days** CPU utilization for one **profile (account)** and one **region** on Alibaba Cloud International, using `aliyun` CLI. **Always write a Markdown report to `reports/` when the run completes.**

> User may say "EC2"; on Alibaba Cloud the product is **ECS** (Elastic Compute Service).

---

## When to Use

- 列出指定阿里云国际站账号、指定 region 下所有 ECS
- 需要实例 **创建时间**、**规格**、**最近一周 CPU 使用率**
- FinOps / 容量评估 / 低利用率实例筛查 / 疑似闲置实例

---

## Scope Parameters

| Parameter | How to specify | Example |
|-----------|----------------|---------|
| Account | `aliyun --profile <name>` | `--profile dbaas-prod-controlplane-v` |
| Region | `--region <RegionId>` on every call | `ap-southeast-1` |
| Time window | Fixed: **last 7 days** (UTC) | not configurable unless user asks |
| Report dir | `--report-dir <path>` | default `reports` |

If profile or region is missing, ask the user before querying.

---

## Prerequisites

- `aliyun` CLI v3+ installed and authenticated (`aliyun configure list` shows Valid profile)
- `jq` installed
- RAM permissions: `ecs:DescribeInstances`, `sts:GetCallerIdentity`, `cms:DescribeMetricList`, `bssopenapi:DescribeInstanceBill`
- CloudMonitor **basic monitoring** enabled on instances (agent not required for `CPUUtilization` in `acs_ecs_dashboard`, but stopped instances may have no metrics)

**Token expired (Cloud SSO):**

```bash
aliyun configure --profile <profileName>
```

**Do not pass `--output json` to `aliyun` CLI v3** when profile `output_format` is already `json`; it conflicts with table output flags.

---

## Preferred Workflow

### 1. Verify identity

```bash
aliyun sts GetCallerIdentity --profile <profile> --region <region>
```

Record `AccountId` as `account_id`.

### 2. Run inventory script (recommended)

```bash
scripts/ecs-cpu-inventory.sh \
  --profile <profile> \
  --region <region>
```

Default `--output report`: collects data, writes Markdown to `reports/`, prints report path to stdout.

Other formats: `--output json|csv|markdown` (stdout only; `report` also writes file).

The script:

1. Lists all ECS instances in the region (`DescribeInstances` with `--pager`)
2. Queries CloudMonitor `CPUUtilization` (`acs_ecs_dashboard`, period **3600s**, last 7 days)
3. Aggregates per instance: `cpu_avg_7d`, `cpu_max_7d`, `cpu_min_7d` (%)
4. Writes report to `reports/ecs-cpu-inventory-<profile>-<region>-<YYYY-MM-DD>.md`

### 3. Manual CLI (if script unavailable)

See [reference.md](reference.md).

---

## Report Contract (STRICT)

After every successful run, **must** save a report under `reports/`:

```
reports/ecs-cpu-inventory-<profile>-<region>-<YYYY-MM-DD>.md
```

### Header (required)

Report header must include:

- **account_id** — STS `AccountId`
- **region** — RegionId
- **profile** — aliyun profile name
- **total instances** — ECS count
- **cpu window** — last 7 days UTC range

### Instance Type 汇总 (required, after total instances)

Before the unused-instance section, include a summary table:

- Group by `instance_type`, count instances per type
- Sort **largest spec first**: `cpu_cores` desc, then `memory_gb` desc
- `memory_gb` = `Memory` / 1024 (1 decimal)
- Query monthly price per type via `ecs DescribePrice` in the target region:
  - `ResourceType=instance`, `PriceUnit=Month`, `Period=1`
  - System disk category auto-selected (`cloud_essd` → `cloud_efficiency` → `cloud`) for API only; price shown is **ECS compute only**
- Columns: `instance_type | cpu_cores | memory_gb | count | monthly_price`
  - **monthly_price**: `instanceType` line item `TradePrice` (1 ECS/month, compute only)

### Section 1 — 疑似无人使用 (required, list first)

Instances matching **either**:

1. `status` is `Stopped`, **or**
2. `cpu_max_7d` (last 7 days CPU **peak**) is numeric and **< 5%**

Sort within this section: `cpu_avg_7d` ascending (blank/no metrics last).

Add a `reason` column: `stopped` | `cpu_max_7d<5%` | both if applicable.

### Section 2 — 全部 ECS（required, list second)

**All** instances in the region, sorted by **`cpu_avg_7d` ascending** (low → high). Instances with blank `cpu_avg_7d` sort last.

Include `rank` column in both tables.

### Table columns (both sections)

```
rank | instance_id | instance_name | created_time | instance_type | cpu_cores | memory_mb | status | cpu_avg_7d | cpu_max_7d | cpu_min_7d
```

`account_id` and `region` appear **only in the report header**, not in table rows.

Section 1 adds: `reason`, `cost_since_launch`

**cost_since_launch** (unused section only): cumulative `PretaxAmount` from `bssopenapi DescribeInstanceBill` for the instance, from creation billing month through the current billing month (statistics time). **Leave blank for `Stopped` instances** (do not query billing). Blank if billing API unavailable.

After the unused table, output **cost_since_launch 合计**: sum of `cost_since_launch` for rows with a non-blank cost (excludes Stopped).

**Empty value rule:** blank cells, not `N/A`, `-`, or `unknown`.

---

## Output Template

```markdown
# ECS CPU Inventory — <profile> / <region> (<date>)

**account_id**: `<AccountId>`
**region**: `<region>`
**profile**: `<profile>`
**total instances**: <N>

## Instance Type 汇总

| instance_type | cpu_cores | memory_gb | count | monthly_price |
|---------------|-----------|-----------|-------|---------------|
| ecs.u1-c1m8.8xlarge | 32 | 256 | 2 | 308.94 USD |

**cpu window**: <start> → <end> (UTC)

## 疑似无人使用

判定：`cpu_max_7d < 5%` 或 `status = Stopped`

| rank | reason | instance_id | instance_name | created_time | instance_type | ... | cpu_avg_7d | cpu_max_7d | cpu_min_7d |
|------|--------|-------------|---------------|--------------|---------------|-----|------------|------------|------------|
| 1 | stopped | i-xxx | pricing-tiup | 2025-10-28T07:24Z | ecs.g8i.4xlarge | ... | | | |

## 全部 ECS（按 CPU 使用率从低到高）

排序字段：`cpu_avg_7d` 升序

| rank | instance_id | instance_name | created_time | instance_type | ... | cpu_avg_7d | cpu_max_7d | cpu_min_7d |
|------|-------------|---------------|--------------|---------------|-----|------------|------------|------------|
| 1 | i-yyy | worker-... | 2026-05-19T07:21Z | ecs.g7.4xlarge | ... | 0.4 | 2.4 | 0.3 |
```

Tell the user the saved report path after the run.

---

## Multi-Account

Iterate profiles when the user gives a list; write one report file per profile × region.

---

## Example Prompts

- 用 profile `dbaas-staging-dev-serverless-v` 查 `ap-southeast-1` 所有 ECS，输出报告到 reports。
- List AliCloud ECS in `us-east-1`, flag unused instances (CPU peak < 5% or stopped).
- 阿里云国际站 ECS 清单 + CPU 利用率，按 CPU 从低到高排序。

---

## References

- CLI details: [reference.md](reference.md)
- ECS metrics: `acs_ecs_dashboard` / `CPUUtilization`
