alibabacloud-terraform-code-generation
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseAlibaba Cloud Terraform Code Generation
阿里云Terraform代码生成
Turn natural-language Alibaba Cloud infrastructure requirements into validated
Terraform for the current provider. Resource knowledge is
pulled from the provider's own docs at generation time — no local gold examples
are maintained.
aliyun/alicloud将自然语言描述的阿里云基础设施需求转换为针对当前提供商的验证版Terraform代码。资源相关知识在生成时从提供商官方文档获取——不维护本地示例模板。
aliyun/alicloudHard 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 , ECS instance RAM
role, Assume Role, OIDC/RRSA, sidecar URI, static HCL) — see
for the full chain. All read by the provider
itself, never by this skill. Do NOT recommend the deprecated /
(no-underscore) env-var names — the current names are
/ / .
config.jsonreferences/auth-and-network.mdALICLOUD_*ALIBABACLOUD_*ALIBABA_CLOUD_ACCESS_KEY_ID_ACCESS_KEY_SECRET_SECURITY_TOKEN绝对不要在任何地方读取、打印、索要或写入AK/SK值——包括HCL代码、注释、环境变量声明、Shell输出、日志。Alicloud提供商通过七种机制解析凭证(环境变量AK/SK、共享文件、ECS实例RAM角色、角色扮演、OIDC/RRSA、Sidecar URI、静态HCL配置)——完整机制链请参考。所有凭证均由提供商自行读取,本技能绝不处理。请勿推荐已弃用的/(无下划线)环境变量名称——当前标准名称为//。
config.jsonreferences/auth-and-network.mdALICLOUD_*ALIBABACLOUD_*ALIBABA_CLOUD_ACCESS_KEY_ID_ACCESS_KEY_SECRET_SECURITY_TOKEN2. Honest reporting — never claim a step you didn't run
2. 诚实报告——绝不虚构未执行的步骤
Never report / / 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: okvalidate: okplan: ok除非实际执行了对应命令且返回对应状态,否则绝不要报告//。当步骤被跳过(工具缺失、用户选择退出)时,必须标注**"SKIPPED"(或"FAILED"**)并说明原因。转述真实输出是允许的,但绝对不能伪造输出。
fmt: okvalidate: okplan: ok3. terraform apply
is off-limits
terraform apply3. terraform apply
严格禁用
terraform applyThis skill NEVER runs . is opt-in (Step 8); is
strictly the user's action.
terraform applyplanapply本技能绝不执行命令。命令为可选执行(步骤8);命令完全由用户自行操作。
terraform applyplanapplyEnvironment (soft recommendations)
环境建议(非强制)
- Terraform ≥ 1.5 recommended. Do not install or download Terraform
automatically; Step 6 checks whether is on PATH and reports the actual validation status.
terraform - Network is required — Step 4.2 WebFetches each resource's provider doc.
- 推荐使用Terraform ≥ 1.5版本。不要自动安装或下载Terraform;步骤6会检查是否在PATH中,并报告实际验证状态。
terraform - 需要网络连接——步骤4.2会通过WebFetch获取每个资源的提供商文档。
Workflow
工作流程
Step 1. Parse requirement
步骤1. 解析需求
Extract:
- — default
region.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 from the user's request (explicit path like
or current working directory if unspecified). All subsequent
/ / commands run in this directory.
<target-dir>myshop-infra/fmtinitvalidateBefore writing any file, MUST create the directory:
.tfbash
mkdir -p <target-dir>All file writes MUST prefix paths with — never write to
the current working directory directly, never write to a generic
parent. After generation completes, verify the structure:
<target-dir>/outputs/bash
ls -R <target-dir>从用户请求中提取(明确路径如,若未指定则使用当前工作目录)。后续所有//命令均在此目录下执行。
<target-dir>myshop-infra/fmtinitvalidate在写入任何文件前,必须创建该目录:
.tfbash
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:
| resource | depends on | AZ / placement |
|---|
- Expand with implied infra (VPC → VSwitch → SecurityGroup → workload); user parse often skips these.
resources[] - The expanded list is the input to Step 4's gate.
在编写任何HCL代码前,绘制依赖关系表——每行对应一个资源:
| 资源 | 依赖项 | 可用区/部署位置 |
|---|
- 扩展,补充隐含的基础设施资源(VPC → VSwitch → SecurityGroup → 工作负载);用户的需求描述通常会遗漏这些资源。
resources[] - 扩展后的列表将作为步骤4的输入。
Step 4. Pre-HCL gate (MANDATORY)
步骤4. HCL生成前置检查(强制执行)
For every distinct 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.
alicloud_*对于步骤3中每个不同的类型(包括资源和数据源),依次执行4.1 → 4.2 → 4.3。各类型的检查相互独立——需并行执行。
alicloud_*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 () is ~2600 lines; do NOT
it whole — use , which returns just the row(s) you need:
references/alicloud-providers.mdReadgrepbash
grep "alicloud_<name>" references/alicloud-providers.mdThree outcomes:
- Row found, status column empty → note the from the row; proceed to 4.2.
[doc](<url>) - **Row found, status <new_name>
⚠️ 弃用 →<new_name>** → switch the plan toalicloud_fc_functionand re-lookup. NEVER emit the deprecated name. Common catch: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 (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. for RDS
HA is optional per the doc but required for real cross-AZ placement).
Missing them produces "validates but silently wrong" output.
references/resource-patterns.mdzone_id_slave_aWhen 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) 目录查询——确认资源存在并检查是否已弃用。目录文件约2600行;不要完整读取——使用命令仅获取所需行:
references/alicloud-providers.mdgrepbash
grep "alicloud_<name>" references/alicloud-providers.md三种结果:
- 找到对应行,状态列为空——记录行中的链接;继续执行4.2。
[doc](<url>) - **找到对应行,状态为<new_name>
⚠️ 弃用 →<new_name>**——将计划切换为使用alicloud_fc_function并重新查询。绝对不要输出已弃用的名称。常见案例:alicloud_fcv3_function`。→ - 未找到对应行——停止操作。询问用户名称是否存在拼写错误;不要自行猜测并生成资源。
alicloud_<guess>
(b) 模式查询(条件触发)——若用户需求与中列出的产品特定规范匹配(例如RDS跨可用区高可用、OSS生命周期非当前版本管理、VPC对等连接),则读取相关章节。这些规范未在提供商文档的「必填项」列表中,但却是用户实际需要的功能(例如RDS高可用所需的在文档中标记为可选,但实际跨可用区部署时为必填项)。遗漏这些规范会导致代码「验证通过但实际无效」。
references/resource-patterns.mdzone_id_slave_a当找到匹配的模式章节时,该章节「必填属性」表中列出的所有属性必须出现在生成的HCL代码中——即使提供商文档标记为可选,也需将其视为必填项。
bash
undefinedQuick check whether a relevant pattern exists, then Read only the section:
快速检查是否存在相关模式,然后仅读取对应章节:
grep -in "<keyword>" references/resource-patterns.md
undefinedgrep -in "<keyword>" references/resource-patterns.md
undefined4.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 URL. Preserve
the catalog kind: resources use , data sources use
.
docwebsite/docs/r/website/docs/d/https://raw.githubusercontent.com/aliyun/terraform-provider-alicloud/master/website/docs/{r|d}/<doc_name>.html.markdownIf both fail, fall back to the local catalog row in
. Prefix the recitation header with
. Do NOT fetch any other URL —
only the two URLs above or the local catalog are trusted sources.
references/alicloud-providers.mddoc unreachable: used local catalog通过WebFetch获取4.1中得到的文档URL。若获取失败或未返回有效内容,则直接从目录行的URL构造原始URL。保留目录中的资源类型:资源使用,数据源使用。
docwebsite/docs/r/website/docs/d/https://raw.githubusercontent.com/aliyun/terraform-provider-alicloud/master/website/docs/{r|d}/<doc_name>.html.markdown若两种方式均失败,则回退使用本地目录文件中的对应行。在输出内容前添加前缀。绝对不要获取其他URL——仅信任上述两个URL或本地目录文件。
references/alicloud-providers.mddoc unreachable: used local catalog4.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
only when the fallback was taken)
no example available
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
(see §5.6 for the four row-kinds and
their handling rules):
references/deprecated-fields.mdbash
grep '`alicloud_<resource>`' references/deprecated-fields.mdIf the user's requirement touches a product with a specific usage pattern
(e.g. RDS cross-AZ HA, VPC peering, OSS lifecycle), also consult
for the non-obvious attributes.
references/resource-patterns.md仅使用4.3中确定的参数。若需要验证内容中未包含的参数,请重新执行4.2进行深度读取;不要自行猜测。
在写入字段前,在中查询对应资源(请参考§5.6中的四种行类型及处理规则):
references/deprecated-fields.mdbash
grep '`alicloud_<resource>`' references/deprecated-fields.md若用户需求涉及具有特定使用模式的产品(例如RDS跨可用区高可用、VPC对等连接、OSS生命周期管理),还需参考获取非显性属性。
references/resource-patterns.md5.2 Data-source enforcement (MANDATORY — no hardcoded IDs)
5.2 数据源强制规则(强制执行——禁止硬编码ID)
Resolve via blocks, never literals. These also pass Step 4's gate:
data- →
zone_id(filter bydata "alicloud_zones").available_resource_creation - →
image_id(filter bydata "alicloud_images",name_regex,owners = "system").most_recent = true - →
instance_type(filter bydata "alicloud_instance_types",cpu_core_count, AZ).memory_size
通过块解析,绝不使用字面量。这些块也需通过步骤4的检查:
datadata- →
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
files. Terraform merges all in a directory, so file organization
is a style choice, not a contract — see "File organization" below.
*.tf*.tfBlock 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 1.x version, then write a pessimistic minor constraint (
aliyun/alicloud->1.278.0). Lookup sources, in order:~> 1.278https://registry.terraform.io/v1/providers/aliyun/alicloud/versionshttps://registry.terraform.io/providers/aliyun/alicloud/latest- or
https://github.com/aliyun/terraform-provider-alicloud/releaseshttps://github.com/aliyun/terraform-provider-alicloud/tags
- If lookup fails, fall back to . Accepted form is
~> 1.274from a confirmed published 1.x release. Do NOT write open-ended constraints (~> 1.<minor>,>= 1.x) or bare version strings.>= 1.239.0
Block 2 — with BOTH
and :
provider "alicloud" {}region = var.regionconfiguration_sourcehcl
provider "alicloud" {
region = var.region
configuration_source = "AlibabaCloud-Agent-Skills/alibabacloud-terraform-code-generation"
}- is the attribution signature — required.
configuration_source - MUST reference
region, not a hardcoded literal.var.region
File organization (recommended, not required): conventional split is
(Block 1) + (Block 2). Also acceptable:
a single containing both blocks, or either block at the
top of . Pick what fits the project — Terraform merges all
equivalently. Do NOT add a filename check; run the content check
below instead.
terraform.tfproviders.tfversions.tfmain.tf*.tfPost-generation verification (cross-file content grep):
bash
undefined项目的文件中必须包含两个Terraform块。Terraform会合并目录中的所有文件,因此文件组织方式属于风格选择,而非强制约定——请参考下文的「文件组织建议」。
*.tf*.tf块1 — :
terraform { required_providers {} }hcl
terraform {
required_version = ">= 1.5"
required_providers {
alicloud = {
source = "aliyun/alicloud"
version = "~> 1.274"
}
}
}- 提供商版本:解析最新发布的稳定版1.x版本,然后写入悲观次要版本约束(例如
aliyun/alicloud→1.278.0)。查询来源优先级:~> 1.278https://registry.terraform.io/v1/providers/aliyun/alicloud/versionshttps://registry.terraform.io/providers/aliyun/alicloud/latest- 或
https://github.com/aliyun/terraform-provider-alicloud/releaseshttps://github.com/aliyun/terraform-provider-alicloud/tags
- 若查询失败,则回退使用。仅接受已确认发布的1.x版本对应的
~> 1.274格式。不要写入开放式约束(~> 1.<minor>、>= 1.x)或裸版本字符串。>= 1.239.0
块2 — ,必须包含和:
provider "alicloud" {}region = var.regionconfiguration_sourcehcl
provider "alicloud" {
region = var.region
configuration_source = "AlibabaCloud-Agent-Skills/alibabacloud-terraform-code-generation"
}- 为归属签名——必填项。
configuration_source - 必须引用
region,而非硬编码字面量。var.region
文件组织建议(非强制):常规拆分方式为(块1) + (块2)。也可接受将两个块放在单个文件中,或任一放在文件顶部。根据项目需求选择即可——Terraform会等效合并所有文件。不要添加文件名检查;请执行下文的内容检查。
terraform.tfproviders.tfversions.tfmain.tf*.tf生成后验证(跨文件内容grep检查):
bash
undefined1. 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
&& 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
&& 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
<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
<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
&& 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
&& 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 (
=, notalicloud_vswitch.app_a).vsw1 - Every tag-supporting resource should carry a non-empty block for ops hygiene — pick reasonable keys for the scenario (common choices:
tags,ManagedBy,Project,Environment). Skill does not prescribe specific tag keys or values.CreatedBy
- 使用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 is needed — this is a pure-grep pass on the HCL you
just wrote. For every resource in this generation, grep the project against
and handle each row-kind:
terraformreferences/deprecated-fields.md- 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→documentassume_role_policy_document - :
alicloud_security_group→namesecurity_group_name - :
alicloud_db_database→namedata_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 says the sub-resource has an explicit safe default. Example: for OSS buckets,
references/resource-patterns.mddefaults toalicloud_oss_bucket_acl, but logging/CORS/website sub-resources are omitted unless the user asks for those features.private - 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在需要使用命令前执行——这是对刚编写的HCL代码的纯grep扫描。对于本次生成的每个资源,在项目中扫描并处理每种行类型:
terraformreferences/deprecated-fields.md- **rename(重命名)**行——若刚编写的HCL代码中出现旧字段名,替换为新字段名。最常见案例:
- :
alicloud_ram_role→name、role_name→documentassume_role_policy_document - :
alicloud_security_group→namesecurity_group_name - :
alicloud_db_database→namedata_base_name
- **split / soft-split(拆分/软拆分)**行——不要在父资源中写入内联字段。仅当用户需求需要该功能,或说明子资源有明确安全默认值时,才声明替代子资源。示例:对于OSS存储桶,
references/resource-patterns.md默认值为alicloud_oss_bucket_acl,但日志/CORS/网站子资源仅在用户明确要求时才添加。private - **deprecated-no-replacement(弃用无替代)**行——停止使用该字段,无替代方案。
仅适用于本次生成的文件——不要重构用户未要求修改的现有文件。
检查后验证(bash grep——必须全部返回OK):
bash
undefinedWalk 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 '| ')
field=$(echo "$field" | tr -d ' ')
kind=$(echo "$kind" | tr -d ' ')
alicloud_' references/deprecated-fields.md | while IFS='|' read _ resource field kind _; do resource=$(echo "$resource" | 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
&& 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 '| ')
field=$(echo "$field" | tr -d ' ')
kind=$(echo "$kind" | tr -d ' ')
alicloud_' references/deprecated-fields.md | while IFS='|' read _ resource field kind _; do resource=$(echo "$resource" | 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
&& 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 is on PATH:
terraformbash
(cd <target-dir> \
&& terraform fmt -recursive \
&& terraform init -backend=false \
&& terraform validate -json)Loop until both conditions are met (max 3 fix attempts total):
- Parse . If there are errors → fix the offending file, then go to step 3.
validate -json - Scan
validate -jsonfordiagnostics[].summarystrings. The provider emits authoritative deprecation annotations (e.g.[DEPRECATED]). If found → fix the matching field, then go to step 3."document": "[DEPRECATED] … New field 'assume_role_policy_document' instead." - Re-run and go back to step 1.
cd <target-dir> && terraform validate -json
Exit the loop only when validate reports no errors AND no
diagnostics. After 3 attempts without reaching this
state: proceed to Step 7 with
and include the failing HCL verbatim in the optional notes.
[DEPRECATED]Validation: FAILED (<diagnostic excerpt>)If fails with a network error (cannot reach ):
not a config bug. Point the user at the mirror-source configuration in
, then proceed to Step 7 — the Summary
MUST use .
Do not retry blindly, do not write yourself.
initregistry.terraform.ioreferences/auth-and-network.mdValidation: SKIPPED (init failed — network/unreachable)~/.terraformrcIf is absent: SKIP this step and surface that fact in Step 7's
summary (Hard rule §2) with .
terraformValidation: SKIPPED (terraform binary not on PATH)若在PATH中:
terraformbash
(cd <target-dir> \
&& terraform fmt -recursive \
&& terraform init -backend=false \
&& terraform validate -json)循环直到满足以下两个条件(最多尝试修复3次):
- 解析输出。若存在错误——修复对应文件,然后回到步骤3。
validate -json - 扫描的
validate -json字段,查找diagnostics[].summary字符串。提供商会输出权威的弃用注释(例如[DEPRECATED])。若找到——修复对应字段,然后回到步骤3。"document": "[DEPRECATED] … New field 'assume_role_policy_document' instead." - 重新执行,然后回到步骤1。
cd <target-dir> && terraform validate -json
仅当验证报告无错误且无诊断信息时,才退出循环。若3次尝试后仍未达到该状态:进入步骤7,标注,并在可选注释中包含失败的HCL代码原文。
[DEPRECATED]Validation: FAILED (<diagnostic excerpt>)若因网络错误失败(无法连接):这不属于配置错误。引导用户参考中的镜像源配置,然后进入步骤7——摘要必须标注。不要盲目重试,不要自行修改。
initregistry.terraform.ioreferences/auth-and-network.mdValidation: SKIPPED (init failed — network/unreachable)~/.terraformrc若不存在:跳过此步骤,并在步骤7的摘要中说明该情况(符合硬性规则§2),标注。
terraformValidation: 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
and lines are the final contract with downstream
evaluators — skipping them is a hard failure.
Files written:Validation: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 placeholders, keep the two line labels
and verbatim):
<bracketed>Files written:Validation: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 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:Validation: terraform fmt+validate: okValidation: SKIPPED (terraform binary not on PATH)Validation: SKIPPED (<reason>)- — after 3 retries hit the cap
Validation: FAILED (<diagnostic excerpt>)
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:Validation: terraform fmt+validate: okValidation: SKIPPED (terraform binary not on PATH)Validation: SKIPPED (<reason>)- ——3次重试后达到上限
Validation: FAILED (<diagnostic excerpt>)
边缘案例:
- 初始化超时 →
Validation: FAILED (init timed out — provider installation exceeded time limit) - 初始化网络不可达 →
Validation: SKIPPED (init failed — network/unreachable) - 格式化成功但初始化失败 → 使用上述根因字符串,不要使用混合状态。
Step 8 (optional). terraform plan
terraform plan步骤8(可选). terraform plan
terraform planOnly when the user asks. Pre-flight probes all seven credential paths
from without reading any value:
references/auth-and-network.mdbash
(
[[ -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:
; surface the output.
(cd <target-dir> && terraform init && terraform plan -out=tfplan) - Empty output → . Tell the user about all viable paths (env AK/SK, shared
NO_CREDENTIALS+~/.aliyun/config.json, ECS instance RAM role, Assume Role chain, OIDC/RRSA, sidecar URI) — do NOT just push env AK/SK. Point them atALIBABA_CLOUD_PROFILEfor the full setup. Then stop. Never read or print secret values.references/auth-and-network.md
仅在用户要求时执行。预检查会探测中的全部七种凭证路径,但不会读取任何凭证值:
references/auth-and-network.mdbash
(
[[ -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) - 无输出——。告知用户所有可行的凭证路径(环境变量AK/SK、共享
NO_CREDENTIALS+~/.aliyun/config.json、ECS实例RAM角色、角色扮演链、OIDC/RRSA、Sidecar URI)——不要仅推荐环境变量AK/SK。引导用户参考ALIBABA_CLOUD_PROFILE获取完整设置说明。然后停止操作。绝对不要读取或打印机密值。references/auth-and-network.md
References
参考资料
| Source | When to read |
|---|---|
| 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 |
| Step 5.1 — known field-level renames not flagged by |
| Step 5.1 — product-specific idioms not emphasized by the provider doc (RDS HA, …) |
| Step 6 failure branch — mirror-source config; Step 8 pre-flight — full credential chain |
The local catalog is one markdown table row per resource and
data source, with a cell and, for deprecated entries, a
<new_name>`` marker. It is generated from the upstream provider
repo by ; re-run that script when a new
release introduces or shifts deprecations.
alicloud_*[doc](<url>)⚠️ 弃用 → scripts/build_alicloud_providers.pyaliyun/alicloud| 来源 | 读取时机 |
|---|---|
| 步骤4.1——资源存在性、弃用标记、文档URL |
| 提供商文档(WebFetch获取4.1中的URL) | 步骤4.2——每个资源的权威必填/可选参数 |
| 步骤5.1—— |
| 步骤5.1——提供商文档未强调的产品特定规范(如RDS高可用等) |
| 步骤6失败分支——镜像源配置;步骤8预检查——完整凭证链 |
本地目录文件为每个资源和数据源对应一行Markdown表格,包含单元格,对于已弃用的条目,还包含<new_name>``标记。该文件由上游提供商仓库通过生成;当新版本引入或变更弃用规则时,需重新运行该脚本。
alicloud_*[doc](<url>)⚠️ 弃用 → scripts/build_alicloud_providers.pyaliyun/alicloud