alibabacloud-terraform-code-generation

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Alibaba Cloud Terraform Code Generation

阿里云Terraform代码生成

Turn natural-language Alibaba Cloud infrastructure requirements into validated Terraform for the current
aliyun/alicloud
provider. Resource knowledge is pulled from the provider's own docs at generation time — no local gold examples are maintained.
将自然语言描述的阿里云基础设施需求转换为针对当前
aliyun/alicloud
提供商的验证版Terraform代码。资源相关知识在生成时从提供商官方文档获取——不维护本地示例模板。

Hard rules (never violate)

硬性规则(绝对不可违反)

1. Credentials — never leak, never require

1. 凭证规则——绝不泄露,绝不要求

NEVER read, print, ask for, or write AK/SK values anywhere — HCL, comments, env declarations, shell output, logs. The alicloud provider resolves credentials through seven mechanisms (env AK/SK, shared
config.json
, ECS instance RAM role, Assume Role, OIDC/RRSA, sidecar URI, static HCL) — see
references/auth-and-network.md
for the full chain. All read by the provider itself, never by this skill. Do NOT recommend the deprecated
ALICLOUD_*
/
ALIBABACLOUD_*
(no-underscore) env-var names — the current names are
ALIBABA_CLOUD_ACCESS_KEY_ID
/
_ACCESS_KEY_SECRET
/
_SECURITY_TOKEN
.
绝对不要在任何地方读取、打印、索要或写入AK/SK值——包括HCL代码、注释、环境变量声明、Shell输出、日志。Alicloud提供商通过七种机制解析凭证(环境变量AK/SK、共享
config.json
文件、ECS实例RAM角色、角色扮演、OIDC/RRSA、Sidecar URI、静态HCL配置)——完整机制链请参考
references/auth-and-network.md
。所有凭证均由提供商自行读取,本技能绝不处理。请勿推荐已弃用的
ALICLOUD_*
/
ALIBABACLOUD_*
(无下划线)环境变量名称——当前标准名称为
ALIBABA_CLOUD_ACCESS_KEY_ID
/
_ACCESS_KEY_SECRET
/
_SECURITY_TOKEN

2. Honest reporting — never claim a step you didn't run

2. 诚实报告——绝不虚构未执行的步骤

Never report
fmt: ok
/
validate: ok
/
plan: ok
unless the corresponding command actually executed AND returned that status. When a step is skipped (tool missing, user opt-out), state "SKIPPED" (or "FAILED") with a reason. Paraphrasing real output is fine; fabricating it is not.
除非实际执行了对应命令且返回对应状态,否则绝不要报告
fmt: ok
/
validate: ok
/
plan: ok
。当步骤被跳过(工具缺失、用户选择退出)时,必须标注**"SKIPPED"(或"FAILED"**)并说明原因。转述真实输出是允许的,但绝对不能伪造输出。

3.
terraform apply
is off-limits

3.
terraform apply
严格禁用

This skill NEVER runs
terraform apply
.
plan
is opt-in (Step 8);
apply
is strictly the user's action.
本技能绝不执行
terraform apply
命令。
plan
命令为可选执行(步骤8);
apply
命令完全由用户自行操作。

Environment (soft recommendations)

环境建议(非强制)

  • Terraform ≥ 1.5 recommended. Do not install or download Terraform automatically; Step 6 checks whether
    terraform
    is on PATH and reports the actual validation status.
  • Network is required — Step 4.2 WebFetches each resource's provider doc.
  • 推荐使用Terraform ≥ 1.5版本。不要自动安装或下载Terraform;步骤6会检查
    terraform
    是否在PATH中,并报告实际验证状态。
  • 需要网络连接——步骤4.2会通过WebFetch获取每个资源的提供商文档。

Workflow

工作流程

Step 1. Parse requirement

步骤1. 解析需求

Extract:
  • region
    — default
    cn-hangzhou
    .
  • resources[]
    { alicloud_type, quantity, attributes }
    .
  • Non-functional: multi-AZ, encryption, backup, HA, IOPS.
If ambiguous (e.g. "搭个数据库"), ask at most one clarifying question.
提取以下信息:
  • region
    ——默认值为
    cn-hangzhou
  • resources[]
    ——格式为
    { alicloud_type, quantity, attributes }
  • 非功能性需求:多可用区、加密、备份、高可用、IOPS。
若需求存在歧义(例如"搭个数据库"),最多提出一个澄清问题。

Step 2. Resolve target directory

步骤2. 确定目标目录

Extract
<target-dir>
from the user's request (explicit path like
myshop-infra/
or current working directory if unspecified). All subsequent
fmt
/
init
/
validate
commands run in this directory.
Before writing any
.tf
file, MUST create the directory:
bash
mkdir -p <target-dir>
All file writes MUST prefix paths with
<target-dir>/
— never write to the current working directory directly, never write to a generic
outputs/
parent. After generation completes, verify the structure:
bash
ls -R <target-dir>
从用户请求中提取
<target-dir>
(明确路径如
myshop-infra/
,若未指定则使用当前工作目录)。后续所有
fmt
/
init
/
validate
命令均在此目录下执行。
在写入任何
.tf
文件前,必须创建该目录:
bash
mkdir -p <target-dir>
所有文件写入操作必须以
<target-dir>/
作为路径前缀——绝不要直接写入当前工作目录,也不要写入通用的
outputs/
父目录。生成完成后,验证目录结构:
bash
ls -R <target-dir>

Step 3. Sketch architecture

步骤3. 绘制架构草图

Before any HCL, sketch a dependency table — one row per resource:
resourcedepends onAZ / placement
  • Expand
    resources[]
    with implied infra (VPC → VSwitch → SecurityGroup → workload); user parse often skips these.
  • The expanded list is the input to Step 4's gate.
在编写任何HCL代码前,绘制依赖关系表——每行对应一个资源:
资源依赖项可用区/部署位置
  • 扩展
    resources[]
    ,补充隐含的基础设施资源(VPC → VSwitch → SecurityGroup → 工作负载);用户的需求描述通常会遗漏这些资源。
  • 扩展后的列表将作为步骤4的输入。

Step 4. Pre-HCL gate (MANDATORY)

步骤4. HCL生成前置检查(强制执行)

For every distinct
alicloud_*
type from Step 3 (resources and data sources), execute 4.1 → 4.2 → 4.3. The calls per type are independent — issue them in parallel across types.
对于步骤3中每个不同的
alicloud_*
类型(包括资源和数据源),依次执行4.1 → 4.2 → 4.3。各类型的检查相互独立——需并行执行

4.1 Pre-doc lookup (catalog + patterns, in parallel)

4.1 文档前置查询(目录+模式,并行执行)

Two local lookups; run them concurrently before going to WebFetch:
(a) Catalog lookup — confirm the resource exists and check deprecation. The catalog (
references/alicloud-providers.md
) is ~2600 lines; do NOT
Read
it whole
— use
grep
, which returns just the row(s) you need:
bash
grep "alicloud_<name>" references/alicloud-providers.md
Three outcomes:
  • Row found, status column empty → note the
    [doc](<url>)
    from the row; proceed to 4.2.
  • **Row found, status
    ⚠️ 弃用 → 
    <new_name>
    ** → switch the plan to 
    <new_name>
    and re-lookup. NEVER emit the deprecated name. Common catch:
    alicloud_fc_function
    alicloud_fcv3_function`.
  • Row not found → stop. Ask the user whether the name was a typo; don't invent an
    alicloud_<guess>
    .
(b) Pattern lookup (conditional) — if the user's requirement matches a product-specific idiom listed in
references/resource-patterns.md
(e.g. RDS cross-AZ HA, OSS lifecycle noncurrent, VPC peering), read the relevant section. These idioms are NOT in the provider doc's Required list but are what the user actually wants (e.g.
zone_id_slave_a
for RDS HA is optional per the doc but required for real cross-AZ placement). Missing them produces "validates but silently wrong" output.
When a matching pattern section is found, ALL attributes listed in that section's "Required attributes" table MUST appear in the generated HCL — treat them as mandatory even if the provider doc marks them Optional.
bash
undefined
执行两项本地查询;在WebFetch前并行运行
(a) 目录查询——确认资源存在并检查是否已弃用。目录文件
references/alicloud-providers.md
约2600行;不要完整读取——使用
grep
命令仅获取所需行:
bash
grep "alicloud_<name>" references/alicloud-providers.md
三种结果:
  • 找到对应行,状态列为空——记录行中的
    [doc](<url>)
    链接;继续执行4.2。
  • **找到对应行,状态为
    ⚠️ 弃用 → 
    <new_name>
    **——将计划切换为使用
    <new_name>
    并重新查询。绝对不要输出已弃用的名称。常见案例:
    alicloud_fc_function
    alicloud_fcv3_function`。
  • 未找到对应行——停止操作。询问用户名称是否存在拼写错误;不要自行猜测并生成
    alicloud_<guess>
    资源。
(b) 模式查询(条件触发)——若用户需求与
references/resource-patterns.md
中列出的产品特定规范匹配(例如RDS跨可用区高可用、OSS生命周期非当前版本管理、VPC对等连接),则读取相关章节。这些规范未在提供商文档的「必填项」列表中,但却是用户实际需要的功能(例如RDS高可用所需的
zone_id_slave_a
在文档中标记为可选,但实际跨可用区部署时为必填项)。遗漏这些规范会导致代码「验证通过但实际无效」。
当找到匹配的模式章节时,该章节「必填属性」表中列出的所有属性必须出现在生成的HCL代码中——即使提供商文档标记为可选,也需将其视为必填项。
bash
undefined

Quick check whether a relevant pattern exists, then Read only the section:

快速检查是否存在相关模式,然后仅读取对应章节:

grep -in "<keyword>" references/resource-patterns.md
undefined
grep -in "<keyword>" references/resource-patterns.md
undefined

4.2 Fetch provider doc (WebFetch)

4.2 获取提供商文档(WebFetch)

WebFetch the doc URL from 4.1. If it fails or returns no useful content, construct the raw URL directly from the catalog row's
doc
URL. Preserve the catalog kind: resources use
website/docs/r/
, data sources use
website/docs/d/
.
https://raw.githubusercontent.com/aliyun/terraform-provider-alicloud/master/website/docs/{r|d}/<doc_name>.html.markdown
If both fail, fall back to the local catalog row in
references/alicloud-providers.md
. Prefix the recitation header with
doc unreachable: used local catalog
. Do NOT fetch any other URL — only the two URLs above or the local catalog are trusted sources.
通过WebFetch获取4.1中得到的文档URL。若获取失败或未返回有效内容,则直接从目录行的
doc
URL构造原始URL。保留目录中的资源类型:资源使用
website/docs/r/
,数据源使用
website/docs/d/
https://raw.githubusercontent.com/aliyun/terraform-provider-alicloud/master/website/docs/{r|d}/<doc_name>.html.markdown
若两种方式均失败,则回退使用本地目录文件
references/alicloud-providers.md
中的对应行。在输出内容前添加前缀
doc unreachable: used local catalog
绝对不要获取其他URL——仅信任上述两个URL或本地目录文件。

4.3 Recite (proof-of-read)

4.3 输出验证内容(已读取证明)

Before writing any HCL, emit and verify a complete per-resource brief:
  • Required params (verbatim list from the doc, or from the local catalog if the 4.2 fallback was taken)
  • 2–5 key Optional params relevant to the user's requirement
  • A minimal HCL snippet from the doc's "Example Usage" (omit with the note
    no example available
    only when the fallback was taken)
If Required or Optional params are missing, return to 4.2. Skipping or using a partial recitation is a hard failure; WebFetch failure uses the 4.2 fallback, not memory.
在编写任何HCL代码前,输出并验证每个资源的完整摘要:
  • 必填参数(直接从文档中提取列表,若使用4.2的回退方案则从本地目录提取)
  • 2-5个与用户需求相关的关键可选参数
  • 文档「示例用法」中的最小HCL代码片段(仅当使用回退方案时可标注
    no example available
若必填或可选参数缺失,请返回4.2重新获取。跳过或使用不完整的验证内容属于严重错误;WebFetch失败时必须使用4.2的回退方案,而非依赖记忆。

Step 5. Generate

步骤5. 生成代码

5.1 Write HCL from the recitations, not memory

5.1 基于验证内容编写HCL代码,而非记忆

Use ONLY the params established in 4.3. If you need a param that wasn't in the recited brief, re-fetch 4.2 with a deeper read; do not guess.
Before writing a field, look up the resource in
references/deprecated-fields.md
(see §5.6 for the four row-kinds and their handling rules):
bash
grep '`alicloud_<resource>`' references/deprecated-fields.md
If the user's requirement touches a product with a specific usage pattern (e.g. RDS cross-AZ HA, VPC peering, OSS lifecycle), also consult
references/resource-patterns.md
for the non-obvious attributes.
仅使用4.3中确定的参数。若需要验证内容中未包含的参数,请重新执行4.2进行深度读取;不要自行猜测。
在写入字段前,在
references/deprecated-fields.md
中查询对应资源(请参考§5.6中的四种行类型及处理规则):
bash
grep '`alicloud_<resource>`' references/deprecated-fields.md
若用户需求涉及具有特定使用模式的产品(例如RDS跨可用区高可用、VPC对等连接、OSS生命周期管理),还需参考
references/resource-patterns.md
获取非显性属性。

5.2 Data-source enforcement (MANDATORY — no hardcoded IDs)

5.2 数据源强制规则(强制执行——禁止硬编码ID)

Resolve via
data
blocks, never literals. These also pass Step 4's gate:
  • zone_id
    data "alicloud_zones"
    (filter by
    available_resource_creation
    ).
  • image_id
    data "alicloud_images"
    (filter by
    name_regex
    ,
    owners = "system"
    ,
    most_recent = true
    ).
  • instance_type
    data "alicloud_instance_types"
    (filter by
    cpu_core_count
    ,
    memory_size
    , AZ).
通过
data
块解析,绝不使用字面量。这些
data
块也需通过步骤4的检查:
  • zone_id
    data "alicloud_zones"
    (通过
    available_resource_creation
    过滤)。
  • image_id
    data "alicloud_images"
    (通过
    name_regex
    owners = "system"
    most_recent = true
    过滤)。
  • instance_type
    data "alicloud_instance_types"
    (通过
    cpu_core_count
    memory_size
    、可用区过滤)。

5.4 Provider block (content contract)

5.4 提供商块(内容约定)

Two Terraform blocks must appear somewhere in the project's
*.tf
files. Terraform merges all
*.tf
in a directory, so file organization is a style choice, not a contract — see "File organization" below.
Block 1 —
terraform { required_providers {} }
:
hcl
terraform {
  required_version = ">= 1.5"
  required_providers {
    alicloud = {
      source  = "aliyun/alicloud"
      version = "~> 1.274"
    }
  }
}
  • Provider version: resolve the latest published stable
    aliyun/alicloud
    1.x version, then write a pessimistic minor constraint (
    1.278.0
    ->
    ~> 1.278
    ). Lookup sources, in order:
    1. https://registry.terraform.io/v1/providers/aliyun/alicloud/versions
    2. https://registry.terraform.io/providers/aliyun/alicloud/latest
    3. https://github.com/aliyun/terraform-provider-alicloud/releases
      or
      https://github.com/aliyun/terraform-provider-alicloud/tags
  • If lookup fails, fall back to
    ~> 1.274
    . Accepted form is
    ~> 1.<minor>
    from a confirmed published 1.x release. Do NOT write open-ended constraints (
    >= 1.x
    ,
    >= 1.239.0
    ) or bare version strings.
Block 2 —
provider "alicloud" {}
with BOTH
region = var.region
and
configuration_source
:
hcl
provider "alicloud" {
  region               = var.region
  configuration_source = "AlibabaCloud-Agent-Skills/alibabacloud-terraform-code-generation"
}
  • configuration_source
    is the attribution signature — required.
  • region
    MUST reference
    var.region
    , not a hardcoded literal.
File organization (recommended, not required): conventional split is
terraform.tf
(Block 1) +
providers.tf
(Block 2). Also acceptable: a single
versions.tf
containing both blocks, or either block at the top of
main.tf
. Pick what fits the project — Terraform merges all
*.tf
equivalently. Do NOT add a filename check; run the content check below instead.
Post-generation verification (cross-file content grep):
bash
undefined
项目的
*.tf
文件中必须包含两个Terraform块。Terraform会合并目录中的所有
*.tf
文件,因此文件组织方式属于风格选择,而非强制约定——请参考下文的「文件组织建议」。
块1 —
terraform { required_providers {} }
:
hcl
terraform {
  required_version = ">= 1.5"
  required_providers {
    alicloud = {
      source  = "aliyun/alicloud"
      version = "~> 1.274"
    }
  }
}
  • 提供商版本:解析最新发布的稳定版
    aliyun/alicloud
    1.x版本,然后写入悲观次要版本约束(例如
    1.278.0
    ~> 1.278
    )。查询来源优先级:
    1. https://registry.terraform.io/v1/providers/aliyun/alicloud/versions
    2. https://registry.terraform.io/providers/aliyun/alicloud/latest
    3. https://github.com/aliyun/terraform-provider-alicloud/releases
      https://github.com/aliyun/terraform-provider-alicloud/tags
  • 若查询失败,则回退使用
    ~> 1.274
    。仅接受已确认发布的1.x版本对应的
    ~> 1.<minor>
    格式。不要写入开放式约束(
    >= 1.x
    >= 1.239.0
    )或裸版本字符串。
块2 —
provider "alicloud" {}
,必须包含
region = var.region
configuration_source
hcl
provider "alicloud" {
  region               = var.region
  configuration_source = "AlibabaCloud-Agent-Skills/alibabacloud-terraform-code-generation"
}
  • configuration_source
    为归属签名——必填项。
  • region
    必须引用
    var.region
    ,而非硬编码字面量。
文件组织建议(非强制):常规拆分方式为
terraform.tf
(块1) +
providers.tf
(块2)。也可接受将两个块放在单个
versions.tf
文件中,或任一放在
main.tf
文件顶部。根据项目需求选择即可——Terraform会等效合并所有
*.tf
文件。不要添加文件名检查;请执行下文的内容检查。
生成后验证(跨文件内容grep检查):
bash
undefined

1. required_providers has aliyun/alicloud with a ~> 1.<minor> version

1. 检查required_providers是否包含aliyun/alicloud,且版本为~> 1.<minor>格式

awk ' /required_providers[[:space:]]{/ { in_req=1 } in_req && /alicloud[[:space:]]=[[:space:]]{/ { in_ali=1 } in_ali && /source[[:space:]]=[[:space:]]"aliyun/alicloud"/ { source=1 } in_ali && /version[[:space:]]=[[:space:]]"~>[[:space:]]1.[0-9]+"/ { version=1 } in_ali && /^[[:space:]]}/ { in_ali=0 } END { exit(source && version ? 0 : 1) } ' <target-dir>/.tf
&& echo OK_VERSION || echo BAD_OR_MISSING_VERSION
awk ' /required_providers[[:space:]]{/ { in_req=1 } in_req && /alicloud[[:space:]]=[[:space:]]{/ { in_ali=1 } in_ali && /source[[:space:]]=[[:space:]]"aliyun/alicloud"/ { source=1 } in_ali && /version[[:space:]]=[[:space:]]"~>[[:space:]]1.[0-9]+"/ { version=1 } in_ali && /^[[:space:]]}/ { in_ali=0 } END { exit(source && version ? 0 : 1) } ' <target-dir>/.tf
&& echo OK_VERSION || echo BAD_OR_MISSING_VERSION

2. configuration_source attribution present somewhere

2. 检查是否存在configuration_source归属信息

grep -Rq 'configuration_source = "AlibabaCloud-Agent-Skills/alibabacloud-terraform-code-generation"'
<target-dir>/*.tf
&& echo OK_CFG_SOURCE || echo MISSING_CFG_SOURCE
grep -Rq 'configuration_source = "AlibabaCloud-Agent-Skills/alibabacloud-terraform-code-generation"'
<target-dir>/*.tf
&& echo OK_CFG_SOURCE || echo MISSING_CFG_SOURCE

3. region uses variable, not hardcoded

3. 检查region是否使用变量,而非硬编码

grep -Rq 'region\s*=\svar.region' <target-dir>/.tf
&& echo OK_REGION_VAR || echo HARDCODED_REGION

All three must return OK. If any fails, fix the offending content and
re-run — do NOT proceed to Step 6 with failures.
grep -Rq 'region\s*=\svar.region' <target-dir>/.tf
&& echo OK_REGION_VAR || echo HARDCODED_REGION

三项检查必须全部返回OK。若任意一项失败,请修复对应内容并重新执行——不要带着失败进入步骤6。

5.5 Style baseline

5.5 风格基准

  • 2-space indent;
    =
    aligned within a block; snake_case semantic resource labels (
    alicloud_vswitch.app_a
    , not
    vsw1
    ).
  • Every tag-supporting resource should carry a non-empty
    tags
    block for ops hygiene — pick reasonable keys for the scenario (common choices:
    ManagedBy
    ,
    Project
    ,
    Environment
    ,
    CreatedBy
    ). Skill does not prescribe specific tag keys or values.
  • 使用2空格缩进;块内
    =
    对齐;资源标签使用蛇形命名法(例如
    alicloud_vswitch.app_a
    ,而非
    vsw1
    )。
  • 所有支持标签的资源应包含非空的
    tags
    块,以提升运维可读性——根据场景选择合理的标签键(常见选项:
    ManagedBy
    Project
    Environment
    CreatedBy
    )。本技能不指定具体的标签键或值。

5.6 Deprecated-field audit — static grep pass (MANDATORY)

5.6 弃用字段检查——静态grep扫描(强制执行)

Run before
terraform
is needed — this is a pure-grep pass on the HCL you just wrote. For every resource in this generation, grep the project against
references/deprecated-fields.md
and handle each row-kind:
  • rename row → if the old field name appears in HCL you just wrote, replace it with the new field name. Examples that show up most often:
    • alicloud_ram_role
      :
      name
      role_name
      ,
      document
      assume_role_policy_document
    • alicloud_security_group
      :
      name
      security_group_name
    • alicloud_db_database
      :
      name
      data_base_name
  • split / soft-split row → do NOT write the inline field on the parent. Declare the replacement sub-resource only when the user's requirement needs that capability, or when
    references/resource-patterns.md
    says the sub-resource has an explicit safe default. Example: for OSS buckets,
    alicloud_oss_bucket_acl
    defaults to
    private
    , but logging/CORS/website sub-resources are omitted unless the user asks for those features.
  • deprecated-no-replacement row → stop using the field, no substitute.
Applies only to files written in this generation — do NOT refactor pre-existing user files you weren't asked to touch.
Post-audit verification (bash grep — must return all OK):
bash
undefined
在需要使用
terraform
命令前执行——这是对刚编写的HCL代码的纯grep扫描。对于本次生成的每个资源,在项目中扫描
references/deprecated-fields.md
并处理每种行类型:
  • **rename(重命名)**行——若刚编写的HCL代码中出现旧字段名,替换为新字段名。最常见案例:
    • alicloud_ram_role
      :
      name
      role_name
      document
      assume_role_policy_document
    • alicloud_security_group
      :
      name
      security_group_name
    • alicloud_db_database
      :
      name
      data_base_name
  • **split / soft-split(拆分/软拆分)**行——不要在父资源中写入内联字段。仅当用户需求需要该功能,或
    references/resource-patterns.md
    说明子资源有明确安全默认值时,才声明替代子资源。示例:对于OSS存储桶,
    alicloud_oss_bucket_acl
    默认值为
    private
    ,但日志/CORS/网站子资源仅在用户明确要求时才添加。
  • **deprecated-no-replacement(弃用无替代)**行——停止使用该字段,无替代方案。
仅适用于本次生成的文件——不要重构用户未要求修改的现有文件。
检查后验证(bash grep——必须全部返回OK):
bash
undefined

Walk deprecated-fields.md row by row and check whether any deprecated

遍历deprecated-fields.md的每一行,检查生成的资源中是否仍在使用已弃用的字段。

field that applies to a generated resource is still in use.

使用awk提取单个资源块后再匹配字段,避免短字段名(如name、document)误匹配复合字段名(如role_name、policy_document)。

Uses awk to extract individual resource blocks before field matching,

so that short field names (name, document) don't falsely match

substrings in compound field names (role_name, policy_document).

grep '|
alicloud_' references/deprecated-fields.md | while IFS='|' read _ resource field kind _; do   resource=$(echo "$resource" | tr -d ' 
') field=$(echo "$field" | tr -d ' ') kind=$(echo "$kind" | tr -d ' ')

Only check if this resource exists in the generated HCL

if grep -Rq "resource "$resource"" <target-dir>/.tf; then case "$kind" in rename|deprecated-no-replacement) awk -v res="$resource" -v fld="$field" ' $0 ~ "resource "" res """ { in_block=1; next } in_block && /^}/ { in_block=0 } in_block && $0 ~ "(^|[^[:alnum:]])" fld "([^[:alnum:]]|$)" { found=1; exit } END { exit found ? 0 : 1 } ' <target-dir>/.tf
&& echo "DEPRECATED: $resource.$field" || echo "OK: $resource.$field" ;; split|soft-split) grep -q "\b$field\b\s*=" <target-dir>/*.tf
&& echo "DEPRECATED: $resource.$field (inline — use standalone sub-resource)"
|| echo "OK: $resource.$field (not inline)" ;; esac fi done

**HARD GATE: must pass before Step 6** — If the script above produces
any `DEPRECATED:` line:

1. Read each `DEPRECATED:` line — it names the resource and field.
2. Look up that resource+field in `references/deprecated-fields.md`
   to get the **Action** column (rename target, split sub-resource,
   etc.).
3. Apply the fix in the HCL.
4. Re-run the verification script.
5. Repeat until **every line returns `OK:`**. This is a blocking gate —
   do NOT proceed to Step 6 with any `DEPRECATED:` output. Do NOT claim
   "verified" unless the script produces all `OK:`.
grep '|
alicloud_' references/deprecated-fields.md | while IFS='|' read _ resource field kind _; do   resource=$(echo "$resource" | tr -d ' 
') field=$(echo "$field" | tr -d ' ') kind=$(echo "$kind" | tr -d ' ')

仅检查该资源是否存在于生成的HCL代码中

if grep -Rq "resource "$resource"" <target-dir>/.tf; then case "$kind" in rename|deprecated-no-replacement) awk -v res="$resource" -v fld="$field" ' $0 ~ "resource "" res """ { in_block=1; next } in_block && /^}/ { in_block=0 } in_block && $0 ~ "(^|[^[:alnum:]])" fld "([^[:alnum:]]|$)" { found=1; exit } END { exit found ? 0 : 1 } ' <target-dir>/.tf
&& echo "DEPRECATED: $resource.$field" || echo "OK: $resource.$field" ;; split|soft-split) grep -q "\b$field\b\s*=" <target-dir>/*.tf
&& echo "DEPRECATED: $resource.$field (inline — use standalone sub-resource)"
|| echo "OK: $resource.$field (not inline)" ;; esac fi done

**硬性检查:必须通过后才能进入步骤6**——若上述脚本输出任何`DEPRECATED:`行:

1. 读取每个`DEPRECATED:`行——其中包含资源和字段名称。
2. 在`references/deprecated-fields.md`中查询该资源+字段,获取「Action」列的内容(重命名目标、拆分后的子资源等)。
3. 在HCL代码中应用修复。
4. 重新执行验证脚本。
5. 重复操作直到**所有行均返回`OK:`**。这是阻塞性检查——若存在`DEPRECATED:`输出,绝对不要进入步骤6。除非脚本全部返回`OK:`,否则不要声称「已验证」。

Step 6. Validate + provider deprecation detection

步骤6. 验证+提供商弃用检测

If
terraform
is on PATH:
bash
(cd <target-dir> \
  && terraform fmt -recursive \
  && terraform init -backend=false \
  && terraform validate -json)
Loop until both conditions are met (max 3 fix attempts total):
  1. Parse
    validate -json
    . If there are errors → fix the offending file, then go to step 3.
  2. Scan
    validate -json
    diagnostics[].summary
    for
    [DEPRECATED]
    strings. The provider emits authoritative deprecation annotations (e.g.
    "document": "[DEPRECATED] … New field 'assume_role_policy_document' instead."
    ). If found → fix the matching field, then go to step 3.
  3. Re-run
    cd <target-dir> && terraform validate -json
    and go back to step 1.
Exit the loop only when validate reports no errors AND no
[DEPRECATED]
diagnostics
. After 3 attempts without reaching this state: proceed to Step 7 with
Validation: FAILED (<diagnostic excerpt>)
and include the failing HCL verbatim in the optional notes.
If
init
fails with a network error
(cannot reach
registry.terraform.io
): not a config bug. Point the user at the mirror-source configuration in
references/auth-and-network.md
, then proceed to Step 7 — the Summary MUST use
Validation: SKIPPED (init failed — network/unreachable)
. Do not retry blindly, do not write
~/.terraformrc
yourself.
If
terraform
is absent: SKIP this step and surface that fact in Step 7's summary (Hard rule §2) with
Validation: SKIPPED (terraform binary not on PATH)
.
terraform
在PATH中:
bash
(cd <target-dir> \
  && terraform fmt -recursive \
  && terraform init -backend=false \
  && terraform validate -json)
循环直到满足以下两个条件(最多尝试修复3次):
  1. 解析
    validate -json
    输出。若存在错误——修复对应文件,然后回到步骤3。
  2. 扫描
    validate -json
    diagnostics[].summary
    字段,查找
    [DEPRECATED]
    字符串。提供商会输出权威的弃用注释(例如
    "document": "[DEPRECATED] … New field 'assume_role_policy_document' instead."
    )。若找到——修复对应字段,然后回到步骤3。
  3. 重新执行
    cd <target-dir> && terraform validate -json
    ,然后回到步骤1。
仅当验证报告无错误且无
[DEPRECATED]
诊断信息
时,才退出循环。若3次尝试后仍未达到该状态:进入步骤7,标注
Validation: FAILED (<diagnostic excerpt>)
,并在可选注释中包含失败的HCL代码原文。
init
因网络错误失败
(无法连接
registry.terraform.io
):这不属于配置错误。引导用户参考
references/auth-and-network.md
中的镜像源配置,然后进入步骤7——摘要必须标注
Validation: SKIPPED (init failed — network/unreachable)
。不要盲目重试,不要自行修改
~/.terraformrc
terraform
不存在:跳过此步骤,并在步骤7的摘要中说明该情况(符合硬性规则§2),标注
Validation: SKIPPED (terraform binary not on PATH)

Step 7. Coverage check + summarize

步骤7. 覆盖检查+生成摘要

MANDATORY — runs regardless of generation outcome. Even if earlier steps were interrupted (init network failure, validate loop exhausted, terraform not on PATH), this step MUST execute. The
Files written:
and
Validation:
lines are the final contract with downstream evaluators — skipping them is a hard failure.
Coverage check. Enumerate resource blocks in the generated HCL and compare with Step 3's sketch. If any sketch row is missing, return to Step 5 and add it — do not skip a row because "the user didn't explicitly name it".
Summary template — print in the user's language, using exactly this structure (fill
<bracketed>
placeholders, keep the two line labels
Files written:
and
Validation:
verbatim):
Files written:
<path/to/file1>
<path/to/file2>
...

Validation: <one-of-four-exact-strings-below>

Deprecation routing: <If re-routed: `<original_name>` → `<new_name>`; else: None>

<optional: architecture notes, design decisions, deploy hints — free-form
here is fine, but NOT inside the lines above>
The
Validation:
line must be one of these exact strings, chosen from what actually happened in Step 6. Do NOT paraphrase or fold it into prose:
  • Validation: terraform fmt+validate: ok
  • Validation: SKIPPED (terraform binary not on PATH)
  • Validation: SKIPPED (<reason>)
  • Validation: FAILED (<diagnostic excerpt>)
    — after 3 retries hit the cap
Edge cases:
  • Init timeout →
    Validation: FAILED (init timed out — provider installation exceeded time limit)
  • Init network-unreachable →
    Validation: SKIPPED (init failed — network/unreachable)
  • Init failed after fmt succeeded → use the root-cause string above, not a hybrid status.
强制执行——无论生成结果如何都需运行。即使之前步骤被中断(初始化网络失败、验证循环达到上限、terraform未安装),此步骤也必须执行。
Files written:
Validation:
行是与下游评估者的最终约定——跳过此步骤属于严重错误。
覆盖检查。枚举生成的HCL代码中的资源块,并与步骤3的草图对比。若草图中的任何行缺失,请返回步骤5添加——不要因为「用户未明确提及」而跳过该行。
摘要模板——使用用户的语言输出,严格遵循以下结构(填充
<>
占位符,保留
Files written:
Validation:
两个标签的原文):
Files written:
<path/to/file1>
<path/to/file2>
...

Validation: <以下四个精确字符串之一>

Deprecation routing: <若进行了路由替换:`<original_name>` → `<new_name>`;否则:None>

<可选:架构说明、设计决策、部署提示——此处可自由发挥,但不要写入上述标签行内>
Validation:
行必须是以下精确字符串之一,根据步骤6的实际执行情况选择。不要转述或融入散文:
  • Validation: terraform fmt+validate: ok
  • Validation: SKIPPED (terraform binary not on PATH)
  • Validation: SKIPPED (<reason>)
  • Validation: FAILED (<diagnostic excerpt>)
    ——3次重试后达到上限
边缘案例:
  • 初始化超时 →
    Validation: FAILED (init timed out — provider installation exceeded time limit)
  • 初始化网络不可达 →
    Validation: SKIPPED (init failed — network/unreachable)
  • 格式化成功但初始化失败 → 使用上述根因字符串,不要使用混合状态。

Step 8 (optional).
terraform plan

步骤8(可选).
terraform plan

Only when the user asks. Pre-flight probes all seven credential paths from
references/auth-and-network.md
without reading any value:
bash
(
  [[ -n "${ALIBABA_CLOUD_ACCESS_KEY_ID:-}" ]] && [[ -n "${ALIBABA_CLOUD_ACCESS_KEY_SECRET:-}" ]] && echo "ready:env-ak-sk"
  [[ -f "$HOME/.aliyun/config.json" ]]                                                           && echo "ready:shared-config"
  { [[ -n "${ALIBABA_CLOUD_CREDENTIALS_FILE:-}" ]] && [[ -f "${ALIBABA_CLOUD_CREDENTIALS_FILE}" ]]; } && echo "ready:custom-credentials-file"
  [[ -n "${ALIBABA_CLOUD_ECS_METADATA:-}" ]]                                                      && echo "ready:ecs-ram-role"
  [[ -n "${ALIBABA_CLOUD_ROLE_ARN:-}" ]]                                                          && echo "ready:assume-role"
  [[ -n "${ALIBABA_CLOUD_CREDENTIALS_URI:-}" ]]                                                   && echo "ready:sidecar"
) | head -1
  • Any line of output → a credential path is available:
    (cd <target-dir> && terraform init && terraform plan -out=tfplan)
    ; surface the output.
  • Empty output
    NO_CREDENTIALS
    . Tell the user about all viable paths (env AK/SK, shared
    ~/.aliyun/config.json
    +
    ALIBABA_CLOUD_PROFILE
    , ECS instance RAM role, Assume Role chain, OIDC/RRSA, sidecar URI) — do NOT just push env AK/SK. Point them at
    references/auth-and-network.md
    for the full setup. Then stop. Never read or print secret values.
仅在用户要求时执行。预检查会探测
references/auth-and-network.md
中的全部七种凭证路径,但不会读取任何凭证值:
bash
(
  [[ -n "${ALIBABA_CLOUD_ACCESS_KEY_ID:-}" ]] && [[ -n "${ALIBABA_CLOUD_ACCESS_KEY_SECRET:-}" ]] && echo "ready:env-ak-sk"
  [[ -f "$HOME/.aliyun/config.json" ]]                                                           && echo "ready:shared-config"
  { [[ -n "${ALIBABA_CLOUD_CREDENTIALS_FILE:-}" ]] && [[ -f "${ALIBABA_CLOUD_CREDENTIALS_FILE}" ]]; } && echo "ready:custom-credentials-file"
  [[ -n "${ALIBABA_CLOUD_ECS_METADATA:-}" ]]                                                      && echo "ready:ecs-ram-role"
  [[ -n "${ALIBABA_CLOUD_ROLE_ARN:-}" ]]                                                          && echo "ready:assume-role"
  [[ -n "${ALIBABA_CLOUD_CREDENTIALS_URI:-}" ]]                                                   && echo "ready:sidecar"
) | head -1
  • 有任何输出——存在可用的凭证路径:执行
    (cd <target-dir> && terraform init && terraform plan -out=tfplan)
    ;输出执行结果。
  • 无输出——
    NO_CREDENTIALS
    。告知用户所有可行的凭证路径(环境变量AK/SK、共享
    ~/.aliyun/config.json
    +
    ALIBABA_CLOUD_PROFILE
    、ECS实例RAM角色、角色扮演链、OIDC/RRSA、Sidecar URI)——不要仅推荐环境变量AK/SK。引导用户参考
    references/auth-and-network.md
    获取完整设置说明。然后停止操作。绝对不要读取或打印机密值。

References

参考资料

SourceWhen to read
references/alicloud-providers.md
(local)
Step 4.1 — resource existence, deprecation mark, doc URL
Provider doc (WebFetch of the URL from 4.1)Step 4.2 — authoritative Required / Optional per resource
references/deprecated-fields.md
(local)
Step 5.1 — known field-level renames not flagged by
terraform validate
references/resource-patterns.md
(local)
Step 5.1 — product-specific idioms not emphasized by the provider doc (RDS HA, …)
references/auth-and-network.md
(local)
Step 6 failure branch — mirror-source config; Step 8 pre-flight — full credential chain
The local catalog is one markdown table row per
alicloud_*
resource and data source, with a
[doc](<url>)
cell and, for deprecated entries, a
⚠️ 弃用 → 
<new_name>`` marker. It is generated from the upstream provider repo by
scripts/build_alicloud_providers.py
; re-run that script when a new
aliyun/alicloud
release introduces or shifts deprecations.
来源读取时机
references/alicloud-providers.md
(本地)
步骤4.1——资源存在性、弃用标记、文档URL
提供商文档(WebFetch获取4.1中的URL)步骤4.2——每个资源的权威必填/可选参数
references/deprecated-fields.md
(本地)
步骤5.1——
terraform validate
未标记的已知字段重命名
references/resource-patterns.md
(本地)
步骤5.1——提供商文档未强调的产品特定规范(如RDS高可用等)
references/auth-and-network.md
(本地)
步骤6失败分支——镜像源配置;步骤8预检查——完整凭证链
本地目录文件为每个
alicloud_*
资源和数据源对应一行Markdown表格,包含
[doc](<url>)
单元格,对于已弃用的条目,还包含
⚠️ 弃用 → 
<new_name>``标记。该文件由上游提供商仓库通过
scripts/build_alicloud_providers.py
生成;当
aliyun/alicloud
新版本引入或变更弃用规则时,需重新运行该脚本。