# ecs-storage

Part of **ECS**

<!-- intent-backlink:auto -->

> 💡 **Path Selection**: This skill is one implementation path for [Manage data protection and recovery for ECS](../../intent/ecs-manage-recovery/SKILL.md). If you're unsure which path to take, check the routing skill first.

# ECS Storage

## Capabilities Overview

| Sub-capability | Calling Mode | Description |
|--------|----------|------|
| Manage Dedicated Block Storage Clusters | Synchronous | Create, modify, and query dedicated block storage clusters and their disks. |
| Get Disk Usage Report | Synchronous | Retrieve user disk usage reports. |
| Manage Data Insight Service | Synchronous | Apply, cancel, and check status of the data insight service for storage. |
| Query Disk Events | Synchronous | Retrieve events related to block storage disks. |
| Start Disk Replica Group | Synchronous | Initiate asynchronous replication for a disk replica group. |
| Manage Default Disk Encryption | Synchronous | Enable, disable, and modify the default KMS key used for disk encryption at the account level. |
| Manage Disks | Synchronous | Initialize, reset, resize, and manage encryption keys for block storage disks. |
| Manage Storage Capacity Units | Synchronous | Purchase, modify attributes, and query details of Storage Capacity Units (SCUs). |
| Query OSS Storage Packages | Synchronous | Check purchased Object Storage Service (OSS) storage packages used for snapshots. |
| Manage Disk Replica Pairs | Synchronous | Create, delete, start, stop, failover, reprotect, and manage disaster recovery drills for disk replica pairs. |
| Manage Disk Replica Groups | Synchronous | Create, delete, start, stop, failover, reprotect, and manage disaster recovery drills for disk replica groups. |
| Manage Enterprise Snapshot Policies | Synchronous | Create, delete, modify, bind, unbind, and describe enterprise snapshot policies. |
| Export Snapshot | Synchronous | Export a snapshot to external storage. |
| Manage Snapshots | Synchronous | Create, delete, copy, lock, unlock, and modify attributes of individual disk snapshots. |
| Manage Snapshot Consistency Groups | Synchronous | Create, delete, and modify snapshot consistency groups for coordinated multi-disk backups. |
| Manage Auto Snapshot Policies | Synchronous | Create, delete, modify, and apply automatic snapshot policies to disks. |
| Query Snapshot Information | Synchronous | Retrieve details about snapshots, consistency groups, usage statistics, and policy associations. |
| Activate Snapshot Service | Synchronous | Enable the snapshot service for your account in a specific region. |
| Snapshot Monitoring | Synchronous | Query snapshot capacity change monitoring data for the last 30 days. |

## API Calling Patterns

### Authentication
The primary authentication method is bearer token authentication using an API key.

- Header format: `Authorization: Bearer <your_api_key>`
- Environment variable: `DASHSCOPE_API_KEY`

### Service Endpoint
The APIs use region-specific endpoints following this pattern:

- Base URL pattern: `https://api.aliyun.com/api/{service}/{version}`
- Common regions: cn-hangzhou, cn-shanghai, cn-beijing

For international regions, use: `https://api.alibabacloud.com/api/{service}/{version}`

### Synchronous API Pattern
All ECS Storage APIs follow a synchronous calling pattern where requests are sent via HTTP POST or GET methods and responses are returned immediately in JSON format. The typical flow is:

1. Construct the request with required parameters
2. Set the Authorization header with your API key
3. Send the request to the appropriate regional endpoint
4. Parse the JSON response for success/failure status
5. Handle any errors based on HTTP status codes and error messages

For POST requests, parameters are typically sent in the request body as JSON. For GET requests, parameters are sent as query string parameters.

## Parameter Reference

### Manage Dedicated Block Storage Clusters

| Parameter | Type | Required | Default | Constraints | Description |
|------|------|------|--------|------|------|
| RegionId | string | true | null | null | Dedicated block storage cluster region ID. |
| Azone | string | true | null | null | Dedicated block storage cluster availability zone ID. |
| DbscName | string | true | null | null | Dedicated block storage cluster name. |
| Capacity | integer | true | null | 61440~2334720GiB, min increment 12288 GiB | Dedicated block storage cluster capacity. |
| Type | string | true | Premium | one of: Standard, Premium | Dedicated block storage cluster performance type. |
| ResourceGroupId | string | false | null | null | Enterprise resource group ID. |
| Tag | array<object> | false | null | max 20 items | Tag list. |
| Period | integer | false | null | one of: 6,7,8,9,10,11,12,24,36 | Instance purchase duration. |
| PeriodUnit | string | false | null | only: Month | Time unit for Period parameter. |

### Manage Disks

| Parameter | Type | Required | Default | Constraints | Description |
|------|------|------|--------|------|------|
| DiskId | string | true | null | null | Disk ID to be initialized. |
| Password | string | false | null | length 8-30 chars, must include uppercase, lowercase, digit, special char | Password for system disk reinitialization. |
| KeyPairName | string | false | null | null | SSH key pair name for Linux instances. |
| AutoStartInstance | boolean | false | false | true/false | Whether to automatically start instance after disk reinitialization. |
| SecurityEnhancementStrategy | string | false | Deactive | Active, Deactive | Whether to use Cloud Security Center service after reinitialization. |

### Manage Snapshots

| Parameter | Type | Required | Default | Constraints | Description |
|------|------|------|--------|------|------|
| DiskId | string | true | null | null | Disk ID for snapshot creation. |
| SnapshotName | string | false | null | length 2-128 chars, cannot start with http:// or https:// | Snapshot name. |
| Description | string | false | "" | length 2-256 chars | Snapshot description. |
| RetentionDays | integer | false | null | range 1-65536 | Snapshot retention period in days. |
| InstantAccess | boolean | false | false | true, false | Whether to enable snapshot instant access feature. |
| InstantAccessRetentionDays | integer | false | matches RetentionDays | range 1-65535 | Retention period for instant access feature. |

### Manage Auto Snapshot Policies

| Parameter | Type | Required | Default | Constraints | Description |
|------|------|------|--------|------|------|
| regionId | string | true | null | null | Region ID for the auto snapshot policy. |
| timePoints | string | true | null | JSON array of integers 0-23, max 24 values | Snapshot creation time points (UTC+8). |
| repeatWeekdays | string | true | null | JSON array of integers 1-7, max 7 values | Days of week for snapshot repetition. |
| retentionDays | integer | true | -1 | -1 or 1-65535 | Snapshot retention period (-1 for permanent). |
| EnableCrossRegionCopy | boolean | false | false | true or false | Whether to enable cross-region copy. |
| TargetCopyRegions | string | false | null | JSON array with one region ID | Target region for cross-region copy. |

## Code Examples

### Create Snapshot - Python - All Regions

```python
import requests
import json

url = "https://api.aliyun.com/api/Ecs/2014-05-26/CreateSnapshot"
headers = {
    "Authorization": "Bearer $DASHSCOPE_API_KEY",
    "Content-Type": "application/json"
}
data = {
    "DiskId": "d-bp17441ohwka0yuh****",
    "SnapshotName": "my-snapshot",
    "Description": "My snapshot description",
    "RetentionDays": 30
}

response = requests.post(url, headers=headers, data=json.dumps(data))
print(response.json())
```

### Query Disk Usage Report - Python - All Regions

```python
import requests

url = "https://api.aliyun.com/api/ebs/2021-07-30/GetReport"
headers = {
    "Authorization": "Bearer $DASHSCOPE_API_KEY",
    "Content-Type": "application/json"
}
params = {
    "RegionId": "cn-hangzhou",
    "ReportType": "present"
}

response = requests.get(url, headers=headers, params=params)
print(response.json())
```

### Describe Dedicated Block Storage Cluster Disks - Python - All Regions

```python
import requests

url = "https://api.aliyun.com/api/ebs/2021-07-30/DescribeDedicatedBlockStorageClusterDisks"
headers = {
    "Authorization": "Bearer $DASHSCOPE_API_KEY",
    "Content-Type": "application/json"
}
params = {
    "RegionId": "cn-heyuan",
    "DbscId": "dbsc-cn-od43bf****",
    "MaxResults": 10
}

response = requests.get(url, headers=headers, params=params)
print(response.json())
```

### Replace System Disk - Python - All Regions

```python
import requests
import json

# Set request parameters
url = "https://ecs.aliyuncs.com/api/v1/ReplaceSystemDisk"
headers = {
    "Authorization": "Bearer YOUR_API_KEY",
    "Content-Type": "application/json"
}
params = {
    "InstanceId": "i-bp67acfmxazb4ph****",
    "ImageId": "m-bp67acfmxazb4ph****",
    "SystemDisk.Size": 80,
    "ClientToken": "123e4567-e89b-12d3-a456-426655440000"
}

# Send request
response = requests.post(url, headers=headers, data=json.dumps(params))

# Handle response
if response.status_code == 200:
    result = response.json()
    print("New system disk ID:", result["DiskId"])
    print("Request ID:", result["RequestId"])
else:
    print("Request failed:", response.status_code, response.text)
```

### Query OSS Snapshot Package - Python - All Regions

```python
from aliyunsdkcore.client import AcsClient
from aliyunsdkcore.request import CommonRequest

client = AcsClient('<your-access-key-id>', '<your-access-key-secret>', 'cn-hangzhou')

request = CommonRequest()
request.set_domain('ecs.aliyuncs.com')
request.set_method('GET')
request.set_version('2014-05-26')
request.set_action_name('DescribeSnapshotPackage')
request.add_query_param('RegionId', 'cn-hangzhou')
request.add_query_param('PageNumber', '1')
request.add_query_param('PageSize', '10')

response = client.do_action_with_exception(request)
print(response)
```

### Query OSS Snapshot Package - Bash - All Regions

```bash
curl -X GET 'https://ecs.aliyuncs.com/?Action=DescribeSnapshotPackage&RegionId=cn-hangzhou&PageNumber=1&PageSize=10&Format=JSON&Version=2014-05-26&SignatureMethod=HMAC-SHA1&SignatureNonce=1234567890&Timestamp=2024-01-01T00:00:00Z&AccessKeyId=your-access-key-id&Signature=your-signature'
```

### Describe Auto Snapshot Policy - Python - All Regions

```python
import requests

url = "https://ecs.aliyuncs.com/"
params = {
    "Action": "DescribeAutoSnapshotPolicyEx",
    "Version": "2014-05-26",
    "RegionId": "cn-hangzhou",
    "PageSize": 10,
    "PageNumber": 1,
    "AccessKeyId": "your-access-key-id",
    "SignatureMethod": "HMAC-SHA1",
    "SignatureVersion": "1.0",
    "Timestamp": "2024-01-01T00:00:00Z",
    "SignatureNonce": "1234567890",
    "Format": "JSON"
}

# Signature logic omitted
response = requests.get(url, params=params)
print(response.json())
```

### Describe Auto Snapshot Policy - Bash - All Regions

```bash
curl -G 'https://ecs.aliyuncs.com/' \
  -d 'Action=DescribeAutoSnapshotPolicyEx' \
  -d 'Version=2014-05-26' \
  -d 'RegionId=cn-hangzhou' \
  -d 'PageSize=10' \
  -d 'PageNumber=1' \
  -d 'AccessKeyId=your-access-key-id' \
  -d 'SignatureMethod=HMAC-SHA1' \
  -d 'SignatureVersion=1.0' \
  -d 'Timestamp=2024-01-01T00:00:00Z' \
  -d 'SignatureNonce=1234567890' \
  -d 'Format=JSON'
```

## Response Format

```json
{
  "RequestId": "20758A-585D-4A41-A9B2-28DA8F4F****",
  "OrderId": "50155660025****",
  "DbscId": "dbsc-f8z4d3k4nsgg9okb****"
}
```

**Key Fields**:
- `RequestId` — Unique identifier for the API request
- `OrderId` — Order ID for purchase operations
- `DbscId` — Dedicated Block Storage Cluster ID

## Error Handling

| Error Code (Code) | Description (Description) | Recommended Action (Recommended Action) |
|---------------|--------------------|-----------------------------|
| 400 | MissingParameter: Request missing required input parameters. | Check that all required parameters are included in your request. |
| 400 | InvalidParameter: Invalid parameter value. | Verify parameter formats and constraints match the API requirements. |
| 403 | Forbidden: User not authorized to perform this operation. | Check your account permissions or consult your main account administrator. |
| 403 | OperationDenied: Current operation is not allowed. | Verify the resource state allows this operation (e.g., disk status, instance status). |
| 404 | NoSuchResource: Specified resource does not exist. | Verify the resource ID (disk ID, snapshot ID, etc.) is correct. |
| 500 | InternalError: Request processing failed due to unknown error. | Retry the request after a short delay. If persistent, contact support. |
| 504 | RequestTimeout: Request timed out, please retry later. | Retry the request with exponential backoff. |

### Rate Limits & Retry
- Many APIs have rate limits of 100 QPS per account
- Single requests may have data point limits (e.g., 1440 data points for monitoring queries)
- Implement exponential backoff with jitter for retry logic
- Respect the Retry-After header when present in 429 responses

## Environment Requirements

- Set the environment variable: `export DASHSCOPE_API_KEY=your_api_key`
- For Python examples using aliyun-sdk: `pip install aliyun-python-sdk-core>=2.0.0`

## FAQ

Q: How do I enable disk encryption by default for my account?
A: Use the EnableDiskEncryptionByDefault API with your region ID. You must have KMS service enabled and proper permissions before calling this API.

Q: What's the difference between standard snapshots and snapshot consistency groups?
A: Standard snapshots capture a single disk at a point in time, while snapshot consistency groups coordinate snapshots across multiple disks (up to 16) to ensure application-consistent backups for multi-disk workloads.

Q: How can I monitor my snapshot storage usage and costs?
A: Use DescribeSnapshotsUsage to get total snapshot count and size, and DescribeSnapshotMonitorData to track capacity changes over the last 30 days. You can also query disk usage reports with GetReport API.

Q: What are the requirements for creating disk replica pairs for disaster recovery?
A: You need to create source and destination disks in different regions first, then use CreateDiskReplicaPair API. Both disks must be in compatible states and you need proper permissions for cross-region operations.

Q: How do I handle snapshot retention and automatic cleanup?
A: Set RetentionDays when creating snapshots, or use auto-snapshot policies with built-in retention settings. Snapshots will be automatically deleted after their retention period expires.

## Pricing & Billing

### Billing Model
Most ECS Storage APIs follow a per-request billing model, while the underlying resources (disks, snapshots, SCUs) have separate pricing based on capacity and duration.

### Price Reference

| Model/Specification | Input Price | Output Price | Other Fees |
|-----------|---------|---------|---------|
| Dedicated Block Storage Cluster | Not explicitly listed | Not explicitly listed | Billed by capacity and usage duration |
| SCU | According to capacity size | | |
| Standard Snapshot | Per region billing | | |
| Archive Snapshot | Billed by archive storage volume | | Early deletion within 60 days incurs 60-day fees |

### Free Tier
- DescribeDedicatedBlockStorageClusters: Free
- DescribeSnapshotPackage: 1000 free requests per month
- ModifyDiskDefaultKMSKeyId: No explicit free tier
- OSS storage package queries: 1000 free requests per month

### Usage Limits
- Dedicated Block Storage Cluster capacity: 61440~2334720GiB with 12288 GiB minimum increment
- Auto snapshot policies: Maximum 100 policies per account per region
- Snapshot consistency groups: Maximum 16 disks per group, total capacity ≤ 32 TiB
- API rate limits: Typically 100 QPS per account for most operations

### Billing Notes
- SCUs can only offset pay-as-you-go disk bills in the same region
- Archive snapshots require minimum 60-day retention; early deletion charges full 60-day fee
- Cross-region snapshot copying incurs additional network transmission fees
- KMS key usage for disk encryption generates separate KMS service charges