Category: service
Edge Security Acceleration (ESA) - Pages, Edge Routine, KV, Site Management, Analytics & More
Use Alibaba Cloud OpenAPI (RPC) with official Python SDK to manage all ESA capabilities.
Alibaba Cloud ESA provides five core capabilities:
- - Pages — Deploy HTML or static directories to edge nodes (quick deployment flow based on Edge Routine)
- Edge Routine (ER) — Full lifecycle management of serverless edge functions
- Edge KV — Distributed edge key-value storage with Namespace/Key/Value management
- Site Management — Site management, DNS records, cache rules, certificates, etc.
- Analytics — Traffic analysis, time-series trends, Top-N rankings, bandwidth statistics, request metrics
Use Python SDK uniformly to call ESA OpenAPI.
Prerequisites
- - Prepare AccessKey (RAM user/role with least privilege).
- Install Python SDK: INLINECODE0
- ESA OpenAPI is RPC style; prefer SDK or OpenAPI Explorer to avoid manual signing.
SDK quickstart
CODEBLOCK0
Pages — Edge Page Deployment
Pages is a quick deployment flow based on Edge Routine, deploying HTML or static directories to the edge.
HTML Page Deployment Flow
CODEBLOCK1
Static Directory Deployment Flow
CODEBLOCK2
Zip Package Structure
The zip package structure depends on EDGE_ROUTINE_TYPE (automatically determined by checkEdgeRoutineType based on whether entry file and assets directory exist):
- - JSONLY:
routine/index.js (bundled with esbuild or --no-bundle to read source files directly) - ASSETSONLY: All static files under
assets/, maintaining original directory structure - JSANDASSETS:
routine/index.js + assets/ static resources (most common)
The assets/ path is relative to assets.directory in configuration. Configuration priority: CLI args > esa.jsonc / esa.toml.
Key Notes
- - Function name rules: lowercase letters/numbers/hyphens, start with lowercase letter, length >= 2
- Same name function: Reuse if exists, deploy new version code
- Deploy to both staging and production by default
- After successful deployment, get
defaultRelatedRecord via GetRoutine as access domain
Detailed reference: INLINECODE14
Edge Routine (ER) — Edge Functions
Manage the complete lifecycle of serverless edge functions via Python SDK.
Core Workflow
CODEBLOCK3
API Summary
- - Function Management:
CreateRoutine, DeleteRoutine, GetRoutine, GetRoutineUserInfo, INLINECODE19 - Code Version:
GetRoutineStagingCodeUploadInfo, CommitRoutineStagingCode, PublishRoutineCodeVersion, INLINECODE23 - Routes:
CreateRoutineRoute, UpdateRoutineRoute, DeleteRoutineRoute, GetRoutineRoute, ListRoutineRoutes, INLINECODE29 - Related Records:
CreateRoutineRelatedRecord, DeleteRoutineRelatedRecord, INLINECODE32
ER Code Format
CODEBLOCK4
Detailed reference: INLINECODE33
Edge KV — Edge Key-Value Storage
Distributed edge key-value storage, readable and writable in Edge Routine, also manageable via OpenAPI/SDK.
Core Concepts
- - Namespace: Isolation container for KV data, Key max 512 chars, Value max 2MB (high capacity 25MB)
- Supports TTL expiration:
Expiration (Unix timestamp) or ExpirationTtl (seconds)
API Summary
- - Namespace:
CreateKvNamespace, DeleteKvNamespace, GetKvNamespace, GetKvAccount, INLINECODE40 - Single Key Operations:
PutKv, GetKv, GetKvDetail, DeleteKv, INLINECODE45 - Batch Operations:
BatchPutKv, BatchDeleteKv, BatchPutKvWithHighCapacity, BatchDeleteKvWithHighCapacity, INLINECODE50
Quick Start
CODEBLOCK5
Detailed reference: INLINECODE51
Site Management — Site Management
Use Python SDK to manage ESA sites, DNS records, cache rules, etc.
API behavior notes
- - Most list APIs support pagination via
PageNumber + PageSize. - INLINECODE54 returns sites across all regions; no need to iterate regions.
- Newly created sites start as
pending; complete access verification via VerifySite to activate. - Deleting a site removes all associated configuration.
- INLINECODE57 can switch between CNAME and NS, but switching to CNAME may fail if incompatible DNS records exist.
- DNS record APIs (
CreateRecord, ListRecords, etc.) work for both NS and CNAME connected sites. CNAME sites are limited to CNAME and A/AAAA types only, and records cannot disable acceleration (proxy must stay enabled). - DNS record
Type parameter must be exact: use A/AAAA (not A), CNAME, MX, TXT, NS, SRV, CAA. - INLINECODE71 supports two config types:
global (site-wide default) and rule (conditional rule with match expression).
Workflow
1) Confirm target site ID, access type (CNAME/NS), and desired action.
2) Find API group and exact operation name in references/api_overview.md.
3) Call API with Python SDK (preferred) or OpenAPI Explorer.
4) Verify results with describe/list APIs.
5) If you need repeatable inventory or summaries, use scripts/ and write outputs under output/aliyun-esa-manage/.
SDK priority
1) Python SDK (preferred)
2) OpenAPI Explorer
3) Other SDKs (only if Python is not feasible)
Python SDK scripts (recommended for inventory)
- - List all ESA sites: INLINECODE77
- Summarize sites by plan: INLINECODE78
- Check site status: INLINECODE79
- List DNS records for a site: INLINECODE80
Analytics — Traffic Analysis
Query and analyze ESA site traffic data using DescribeSiteTimeSeriesData and DescribeSiteTopData APIs.
Core Features
- - Time-Series Data: Query traffic trends with configurable time granularity
- Top-N Rankings: Get rankings by country/IP/host/path/status code dimensions
- Multiple Metrics: Traffic, Requests, RequestTraffic, PageView
- Rich Dimensions: Country, province, ISP, browser, device, host, path, status code, etc.
Two Main APIs
1. DescribeSiteTimeSeriesData - Time-Series Trends
Query traffic trends over time, returning aggregated data points.
Time Granularity Rules:
| Time Range | Interval | Interval Value |
|---|
| <= 3 hours | 1 minute | INLINECODE83 |
| 3-12 hours |
5 minutes |
300 |
| 12 hours - 1 day | 15 minutes |
900 |
| 1-10 days | 1 hour |
3600 |
| 10-31 days | 1 day |
86400 |
2. DescribeSiteTopData - Top-N Rankings
Query Top-N ranking data by various dimensions.
Limit Options: 5, 10, INLINECODE90
Available Metrics (FieldName)
| Field | Type | Description |
|---|
| INLINECODE91 | int | Response traffic from ESA to client (bytes) |
| INLINECODE92 |
int | Number of requests |
|
RequestTraffic | int | Client request traffic (bytes) |
|
PageView | int | Page views |
Available Dimensions
Geographic Dimensions: ClientCountryCode (country), ClientProvinceCode (province), ClientISP (ISP), INLINECODE98
Client Info: ClientIP, ClientIPVersion, ClientBrowser, ClientDevice, INLINECODE103
Request Details: ClientRequestHost, ClientRequestMethod, ClientRequestPath, ClientRequestProtocol, ClientRequestQuery, ClientRequestReferer, INLINECODE110
Response/Cache: EdgeCacheStatus, EdgeResponseStatusCode, EdgeResponseContentType, INLINECODE114
Others: ALL (aggregated), SiteId (account-level query), Version, ClientSSLProtocol, INLINECODE119
Error Handling
| HTTP Code | Error Code | Description |
|---|
| 400 | INLINECODE120 | Time range exceeded (max 31 days) |
| 400 |
InvalidEndTime.Mismatch | EndTime earlier than StartTime |
| 400 |
InvalidParameter.Field | Invalid field name |
| 400 |
InvalidParameter.Dimension | Invalid dimension |
| 400 |
InvalidTime.Malformed | Time format error (use yyyy-MM-ddTHH:mm:ssZ) |
Detailed reference: references/time-series.md, references/top-data.md, INLINECODE127
Common operation mapping
Site Management
- - Create site: INLINECODE128
- List sites:
ListSites (supports SiteName, Status, AccessType, Coverage filters) - Get site details: INLINECODE134
- Delete site: INLINECODE135
- Check site name availability: INLINECODE136
- Verify site ownership: INLINECODE137
- Update access type: INLINECODE138
- Update coverage: INLINECODE139
- Get current nameservers: INLINECODE140
- Update custom nameservers: INLINECODE141
- Pause/resume site:
UpdateSitePause, INLINECODE143 - Site exclusivity:
UpdateSiteNameExclusive, INLINECODE145 - Version management:
ActivateVersionManagement, INLINECODE147
Site Configuration
- - IPv6:
GetIPv6, INLINECODE149
DNS Records
NS access: full record type support. CNAME access: only CNAME and A/AAAA, proxy must stay enabled.
- - Create record: INLINECODE152
- List records:
ListRecords (supports Type, RecordName, Proxied filters) - Get record: INLINECODE157
- Update record: INLINECODE158
- Delete record: INLINECODE159
- Batch create: INLINECODE160
- Export records: INLINECODE161
Cache Rules
- - Create cache rule: INLINECODE162
- List cache rules: INLINECODE163
- Get cache rule: INLINECODE164
- Update cache rule: INLINECODE165
- Delete cache rule: INLINECODE166
Cache rule expression notes (important):
- -
CreateCacheRule parameters are flat, not a nested JSON Rule object. - The
Rule parameter is a match condition expression string. See Rule Expression Syntax section below. - Quick reminders:
ends_with()/starts_with() must use function-call style; matches (regex) requires standard plan or above. - Set edge cache TTL with
--EdgeCacheMode override_origin --EdgeCacheTtl <seconds>.
Rule Expression Syntax
ESA uses a unified rule engine expression syntax across multiple features (cache rules, WAF custom rules, rate limiting, URL rewrite, header modification, etc.).
When to use
Use this syntax for the Rule parameter in any ESA API that accepts a match condition expression:
- -
CreateCacheRule / UpdateCacheRule - Cache rules - INLINECODE177 /
UpdateWafRule - WAF custom rules - INLINECODE179 - Rate limiting rules
- INLINECODE180 /
UpdateRewriteUrlRule - URL rewrite rules - Origin rules, redirect rules, header modification rules, etc.
Expression format
CODEBLOCK6
Max nesting depth: 2 levels.
Operator syntax - two styles
Infix style (operator between field and value):
CODEBLOCK7
Function style (operator wraps field):
CODEBLOCK8
Common patterns
CODEBLOCK9
Key Gotchas
- 1.
ends_with and starts_with must use function-call syntax, NOT infix. - INLINECODE184 (regex) requires standard plan or above; basic plan returns
RuleRegexQuotaCheckFailed. - INLINECODE186 with URI must include path separator:
"/test" is correct; "test" alone causes CompileRuleError. - List values in
in operator are space-separated inside braces: {"a.com" "b.com"}. - Outer parentheses are optional for single conditions.
- Use
ne for "not equal", never use not...eq. - Use
not...in for negating set membership (not before field), not not in.
Plan Limitations
| Plan | eq/ne/in/startswith/endswith | contains | matches (regex) |
|---|
| Basic | Supported | Supported | Not supported |
| Standard |
Supported | Supported | Supported |
| Enterprise | Supported | Supported | Supported |
AccessKey priority (must follow, align with README)
1) Environment variables: ALICLOUD_ACCESS_KEY_ID / ALICLOUD_ACCESS_KEY_SECRET / ALICLOUD_REGION_ID
Region policy: ALICLOUD_REGION_ID is an optional default. If unset, decide the most reasonable region for the task; if unclear, ask the user.
2) Shared config file: ~/.alibabacloud/credentials (region still from env)
Auth setup (README-aligned)
Environment variables:
CODEBLOCK10
Also supported by the Alibaba Cloud SDKs:
CODEBLOCK11
Shared config file:
INLINECODE201
CODEBLOCK12
API discovery
- - Product code: INLINECODE202
- Default API version: INLINECODE203
- Metadata endpoint: INLINECODE204
- Use OpenAPI metadata endpoints to list APIs and get schemas (see references).
Output policy
If you need to save responses or generated artifacts, write them under:
INLINECODE205
References
Pages, ER & KV
- - Pages Deployment Reference: INLINECODE206
- Edge Routine Reference: INLINECODE207
- Edge KV Storage Reference: INLINECODE208
Site Management
- - API overview: INLINECODE209
- Endpoints: INLINECODE210
- Sites: INLINECODE211
- DNS records: INLINECODE212
- Cache: INLINECODE213
- Sources: INLINECODE214
- Rule expression - generation guide: INLINECODE215
- Rule expression - match fields: INLINECODE216
- Rule expression - operators: INLINECODE217
- Rule expression - examples: INLINECODE218
Analytics
- - Time-Series Data API: INLINECODE219
- Top-N Data API: INLINECODE220
- Metrics and Dimensions Reference: INLINECODE221
技能名称: aliyun-esa-manage
详细描述:
类别: 服务
边缘安全加速 (ESA) - Pages、边缘函数、KV、站点管理、数据分析等
使用阿里云OpenAPI (RPC) 配合官方Python SDK管理所有ESA功能。
阿里云ESA提供五大核心能力:
- - Pages — 将HTML或静态目录部署到边缘节点(基于边缘函数的快速部署流程)
- 边缘函数 (ER) — 无服务器边缘函数的全生命周期管理
- 边缘KV — 分布式边缘键值存储,支持命名空间/键/值管理
- 站点管理 — 站点管理、DNS记录、缓存规则、证书等
- 数据分析 — 流量分析、时序趋势、Top-N排名、带宽统计、请求指标
统一使用Python SDK调用ESA OpenAPI。
前提条件
- - 准备AccessKey(RAM用户/角色,遵循最小权限原则)。
- 安装Python SDK:pip install alibabacloudesa20240910 alibabacloudteaopenapi alibabacloudcredentials
- ESA OpenAPI为RPC风格;优先使用SDK或OpenAPI Explorer,避免手动签名。
SDK快速入门
python
from alibabacloud_esa20240910.client import Client as Esa20240910Client
from alibabacloudesa20240910 import models as esamodels
from alibabacloudteaopenapi import models as openapimodels
def createclient(regionid: str = cn-hangzhou) -> Esa20240910Client:
config = openapimodels.Config(
regionid=regionid,
endpoint=esa.cn-hangzhou.aliyuncs.com,
)
return Esa20240910Client(config)
Pages — 边缘页面部署
Pages是基于边缘函数的快速部署流程,将HTML或静态目录部署到边缘。
HTML页面部署流程
CreateRoutine → GetRoutineStagingCodeUploadInfo → 上传代码到OSS
→ CommitRoutineStagingCode → PublishRoutineCodeVersion(staging)
→ PublishRoutineCodeVersion(production) → GetRoutine(获取访问URL)
静态目录部署流程
CreateRoutine → CreateRoutineWithAssetsCodeVersion → 打包zip并上传到OSS
→ 轮询 GetRoutineCodeVersionInfo(等待可用状态)
→ CreateRoutineCodeDeployment(staging) → CreateRoutineCodeDeployment(production)
→ GetRoutine(获取访问URL)
Zip包结构
Zip包结构取决于EDGEROUTINETYPE(根据入口文件和静态资源目录是否存在,由checkEdgeRoutineType自动判断):
- - JSONLY: routine/index.js(使用esbuild打包,或--no-bundle直接读取源文件)
- ASSETSONLY: assets/下的所有静态文件,保持原始目录结构
- JSANDASSETS: routine/index.js + assets/静态资源(最常见)
assets/路径相对于配置中的assets.directory。配置优先级:CLI参数 > esa.jsonc / esa.toml。
关键说明
- - 函数命名规则:小写字母/数字/连字符,以小写字母开头,长度 >= 2
- 同名函数:如果存在则复用,部署新版本代码
- 默认同时部署到预发和生产环境
- 部署成功后,通过GetRoutine获取defaultRelatedRecord作为访问域名
详细参考:references/pages.md
边缘函数 (ER) — 边缘函数
通过Python SDK管理无服务器边缘函数的完整生命周期。
核心工作流
CreateRoutine → GetRoutineStagingCodeUploadInfo → 上传代码到OSS
→ CommitRoutineStagingCode → PublishRoutineCodeVersion
→ (CreateRoutineRoute) → GetRoutine
API概览
- - 函数管理: CreateRoutine, DeleteRoutine, GetRoutine, GetRoutineUserInfo, ListUserRoutines
- 代码版本: GetRoutineStagingCodeUploadInfo, CommitRoutineStagingCode, PublishRoutineCodeVersion, DeleteRoutineCodeVersion
- 路由: CreateRoutineRoute, UpdateRoutineRoute, DeleteRoutineRoute, GetRoutineRoute, ListRoutineRoutes, ListSiteRoutes
- 关联记录: CreateRoutineRelatedRecord, DeleteRoutineRelatedRecord, ListRoutineRelatedRecords
ER代码格式
javascript
export default {
async fetch(request) {
return new Response(Hello, {
headers: { content-type: text/html;charset=UTF-8 },
});
},
};
详细参考:references/er.md
边缘KV — 边缘键值存储
分布式边缘键值存储,可在边缘函数中读写,也可通过OpenAPI/SDK管理。
核心概念
- - 命名空间: KV数据的隔离容器,Key最大512字符,Value最大2MB(高容量模式25MB)
- 支持TTL过期:Expiration(Unix时间戳)或ExpirationTtl(秒)
API概览
- - 命名空间: CreateKvNamespace, DeleteKvNamespace, GetKvNamespace, GetKvAccount, DescribeKvAccountStatus
- 单键操作: PutKv, GetKv, GetKvDetail, DeleteKv, PutKvWithHighCapacity
- 批量操作: BatchPutKv, BatchDeleteKv, BatchPutKvWithHighCapacity, BatchDeleteKvWithHighCapacity, ListKvs
快速入门
python
client = create_client()
创建命名空间
client.create
kvnamespace(esa_models.CreateKvNamespaceRequest(namespace=my-ns))
写入
client.put
kv(esamodels.PutKvRequest(namespace=my-ns, key=k1, value=v1))
读取
resp = client.get
kv(esamodels.GetKvRequest(namespace=my-ns, key=k1))
详细参考:references/kv.md
站点管理 — 站点管理
使用Python SDK管理ESA站点、DNS记录、缓存规则等。
API行为说明
- - 大多数列表API支持通过PageNumber + PageSize分页。
- ListSites返回所有区域的站点;无需遍历区域。
- 新创建的站点初始状态为pending;通过VerifySite完成接入验证后激活。
- 删除站点会移除所有关联配置。
- UpdateSiteAccessType可在CNAME和NS之间切换,但如果存在不兼容的DNS记录,切换到CNAME可能失败。
- DNS记录API(CreateRecord, ListRecords等)适用于NS和CNAME接入的站点。CNAME站点仅支持CNAME和A/AAAA类型,且记录不能关闭加速(代理必须保持启用)。
- DNS记录的Type参数必须精确:使用A/AAAA(而非A)、CNAME、MX、TXT、NS、SRV、CAA。
- CreateCacheRule支持两种配置类型:global(站点级默认)和rule(带匹配表达式的条件规则)。
工作流程
1) 确认目标站点ID、接入类型(CNAME/NS)和所需操作。
2) 在references/api_overview.md中找到API分组和精确操作名称。
3) 使用Python SDK(首选)或OpenAPI Explorer调用API。
4) 使用describe/list API验证结果。
5) 如果需要可重复的清单或摘要,使用scripts/并将输出写入output/aliyun-esa-manage/。
SDK优先级
1) Python SDK(首选)
2) OpenAPI Explorer
3) 其他SDK(仅当Python不可行时)
Python SDK脚本(推荐用于清单)
- - 列出所有ESA站点:scripts/listsites.py
- 按套餐汇总站点:scripts/summarysitesbyplan.py
- 检查站点状态:scripts/checksitestatus.py
- 列出站点的DNS记录:scripts/listdnsrecords.py
数据分析 — 流量分析
使用DescribeSiteTimeSeriesData和DescribeSiteTopDataAPI查询和分析ESA站点流量数据。
核心功能
- - 时序数据:查询流量趋势,可配置时间粒度
- Top-N排名:按国家/IP/主机/路径/状态码维度获取排名
- 多指标:流量、请求数、请求流量、页面浏览量
- 丰富维度:国家、省份、运营商、浏览器、设备、主机、路径、状态码等
两个主要API
1. DescribeSiteTimeSeriesData - 时序趋势
查询随时间变化的流量趋势,返回聚合数据点。
时间粒度规则:
| 时间范围