alibabacloud-terraform-import

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Alibaba Cloud Resource Terraform Import Wizard

阿里云资源Terraform导入向导

Step-by-step guide to import existing resources under an Alibaba Cloud account into local Terraform management. Automatically performs environment checks, resource discovery, HCL generation, state import, etc. Users only need to confirm at key decision points.
Two modes are supported:
  • One-time migration: Complete Phase 1-9 end to end
  • Incremental sync: When a Terraform working directory already exists, jump directly to incremental sync mode
本向导将逐步引导您把阿里云账号下的现有资源导入本地Terraform管理,自动完成环境检查、资源发现、HCL代码生成、状态导入等操作,用户仅需在关键决策节点进行确认即可。
支持两种模式:
  • 一次性迁移:完整执行阶段1至阶段9的全流程
  • 增量同步:当Terraform工作目录已存在时,直接跳转至增量同步模式

Resource Support Scope

资源支持范围

  • Theoretical scope: Any resource in the alicloud provider that has a Read method (i.e., can read state from the cloud). Most resources can be imported directly via the
    terraform import
    command or
    import
    blocks (Terraform 1.5+); a few resources without an Importer can be imported by manually constructing tfstate, but this requires exact matching of the provider's state structure and carries some risk. Check support status at
    https://registry.terraform.io/providers/aliyun/alicloud/latest/docs
    .
  • Pre-built resources: ~50 common resource types (networking, compute, storage, databases, load balancing, DNS, RAM, ACK, FC) with verified API discovery commands, HCL templates, and import ID formats in
    references/
  • Beyond pre-built scope: Will look up provider docs on the fly to provide commands and templates; accuracy depends on documentation content; users should verify before executing

  • 理论支持范围:alicloud provider中所有具备Read方法的资源(即能从云端读取状态的资源)。大多数资源可直接通过
    terraform import
    命令或
    import
    块(Terraform 1.5+版本)导入;少数无Importer的资源可通过手动构造tfstate导入,但这要求与provider的状态结构完全匹配,存在一定风险。可访问
    https://registry.terraform.io/providers/aliyun/alicloud/latest/docs
    查看支持状态。
  • 预构建支持资源:约50种常见资源类型(网络、计算、存储、数据库、负载均衡、DNS、RAM、ACK、FC),在
    references/
    目录中已验证其API发现命令、HCL模板和导入ID格式
  • 超出预构建范围的资源:将实时查询provider文档以提供命令和模板,准确性取决于文档内容,用户执行前需自行验证

Command Format Requirements

命令格式要求

All aliyun CLI commands must use plugin mode (lowercase-hyphenated format). CamelCase command names and parameter names are prohibited. Violating this rule will cause parameter errors or call failures.
Example (correct plugin-mode format):
bash
aliyun vpc describe-vpcs --biz-region-id cn-shanghai --page-size 50
Parameter conversion rules:
  • Region: Prefer
    --biz-region-id
    (business parameter, corresponds to the API's RegionId);
    --region
    (framework parameter, controls endpoint region) should only be used when the API's RegionId is optional
  • Pagination:
    --page-size
    (not PageSize)
  • Others: Convert CamelCase parameter names to lowercase-hyphenated (VpcId ->
    --vpc-id
    , InstanceIds ->
    --instance-ids
    ). Use
    aliyun <product> <command> --help
    to confirm
  • OSS: Use
    aliyun ossutil ls oss://
    exclusively

所有aliyun CLI命令必须使用插件模式(小写连字符格式)。禁止使用驼峰式命令名和参数名。 违反此规则会导致参数错误或调用失败。
示例(正确的插件模式格式):
bash
aliyun vpc describe-vpcs --biz-region-id cn-shanghai --page-size 50
参数转换规则:
  • 地域:优先使用
    --biz-region-id
    (业务参数,对应API的RegionId);仅当API的RegionId为可选参数时,才使用
    --region
    (框架参数,控制端点地域)
  • 分页:使用
    --page-size
    (而非PageSize)
  • 其他参数:将驼峰式参数名转换为小写连字符格式(VpcId ->
    --vpc-id
    ,InstanceIds ->
    --instance-ids
    )。可使用
    aliyun <product> <command> --help
    确认参数格式
  • OSS:仅使用
    aliyun ossutil ls oss://
    命令

Phase 1: Environment Check

阶段1:环境检查

Run the following commands to detect the environment:
bash
echo "=== aliyun CLI ===" && aliyun --version 2>&1 || echo "NOT_INSTALLED"
echo "=== terraform ===" && terraform --version 2>&1 || echo "NOT_INSTALLED"
echo "=== python3 ===" && python3 --version 2>&1 || echo "NOT_INSTALLED"
echo "=== OS ===" && uname -s 2>&1
Automatically handle missing tools based on output:
  • aliyun CLI missing (macOS): Run
    brew install aliyun-cli
  • aliyun CLI missing (Linux): Run
    curl -sSL --connect-timeout 10 --max-time 120 https://aliyuncli.alicdn.com/aliyun-cli-linux-latest-amd64.tgz | tar xz && sudo mv aliyun /usr/local/bin/
  • terraform missing (macOS): Run
    brew tap hashicorp/tap && brew install hashicorp/tap/terraform
  • terraform missing (Linux): Direct user to https://developer.hashicorp.com/terraform/install for manual installation (requires root)
Once all tools are ready, proceed to Phase 2.
Configure aliyun CLI AI-Mode:
All aliyun CLI commands must have AI-Mode configured so Alibaba Cloud can identify AI invocation scenarios and provide optimized support. Before executing any aliyun CLI command, run:
bash
undefined
运行以下命令检测环境:
bash
echo "=== aliyun CLI ===" && aliyun --version 2>&1 || echo "NOT_INSTALLED"
echo "=== terraform ===" && terraform --version 2>&1 || echo "NOT_INSTALLED"
echo "=== python3 ===" && python3 --version 2>&1 || echo "NOT_INSTALLED"
echo "=== OS ===" && uname -s 2>&1
根据输出自动处理缺失工具:
  • 缺失aliyun CLI(macOS):运行
    brew install aliyun-cli
  • 缺失aliyun CLI(Linux):运行
    curl -sSL --connect-timeout 10 --max-time 120 https://aliyuncli.alicdn.com/aliyun-cli-linux-latest-amd64.tgz | tar xz && sudo mv aliyun /usr/local/bin/
  • 缺失terraform(macOS):运行
    brew tap hashicorp/tap && brew install hashicorp/tap/terraform
  • 缺失terraform(Linux):引导用户前往https://developer.hashicorp.com/terraform/install手动安装(需root权限)
所有工具准备就绪后,进入阶段2。
配置aliyun CLI AI模式:
所有aliyun CLI命令必须配置AI模式,以便阿里云识别AI调用场景并提供优化支持。执行任何aliyun CLI命令前,请先运行:
bash
undefined

Enable AI-Mode (required)

启用AI模式(必填)

aliyun configure ai-mode enable
aliyun configure ai-mode enable

Set User-Agent identifier (required)

设置User-Agent标识(必填)

aliyun configure ai-mode set-user-agent --user-agent "AlibabaCloud-Agent-Skills/alibabacloud-terraform-import"
aliyun configure ai-mode set-user-agent --user-agent "AlibabaCloud-Agent-Skills/alibabacloud-terraform-import"

Update plugins to latest version (recommended)

更新插件至最新版本(推荐)

aliyun plugin update

All subsequent aliyun CLI commands will automatically carry AI-Mode and User-Agent identifiers. See the "Command Format Requirements" section above for command formatting rules.

**Disable AI-Mode (when the session ends or if needed):**
```bash
aliyun configure ai-mode disable

aliyun plugin update

后续所有aliyun CLI命令将自动携带AI模式和User-Agent标识。命令格式规则请参考上文「命令格式要求」部分。

**关闭AI模式(会话结束或需要时):**
```bash
aliyun configure ai-mode disable

Phase 2: Authentication Configuration

阶段2:身份认证配置

This Skill relies on the Alibaba Cloud default credential chain for authentication, supporting the following methods (by priority):
  1. Environment variables (ALICLOUD_ACCESS_KEY / ALICLOUD_SECRET_KEY) — highest priority
  2. aliyun CLI configuration file (~/.aliyun/config.json)
  3. ECS RAM role (only when running on ECS)
Important: The Terraform alicloud provider and aliyun CLI each read credentials independently, both prioritizing environment variables. When environment variables and CLI profile point to different accounts, environment variables take precedence.
Verify authentication:
Verify identity via the default credential chain (without explicitly passing AK/SK):
bash
aliyun sts get-caller-identity 2>&1
Analyze the output:
  • Confirm AccountId and UserId, record Region
  • If the credential source is unexpected (e.g., environment variables and CLI profile point to different accounts), inform the user of the credential conflict and suggest unifying credential configuration before retrying
If an error occurs, prompt the user to:
  • Check whether credentials are configured (via
    aliyun configure
    or environment variables)
  • Check permissions (requires ReadOnlyAccess or corresponding resource Describe permissions)
  • Refer to
    references/ram-policies.md
    for required permissions

本Skill依赖阿里云默认凭证链进行认证,支持以下方式(按优先级排序):
  1. 环境变量(ALICLOUD_ACCESS_KEY / ALICLOUD_SECRET_KEY)—— 优先级最高
  2. aliyun CLI配置文件(~/.aliyun/config.json)
  3. ECS RAM角色(仅在ECS上运行时可用)
重要提示:Terraform alicloud provider和aliyun CLI各自独立读取凭证,均优先使用环境变量。当环境变量与CLI配置文件指向不同账号时,环境变量优先级更高。
验证身份认证:
通过默认凭证链验证身份(无需显式传递AK/SK):
bash
aliyun sts get-caller-identity 2>&1
分析输出:
  • 确认AccountId和UserId,记录地域信息
  • 若凭证来源不符合预期(例如环境变量与CLI配置文件指向不同账号),告知用户存在凭证冲突,建议统一凭证配置后重试
若出现错误,提示用户:
  • 检查是否已配置凭证(通过
    aliyun configure
    或环境变量)
  • 检查权限(需ReadOnlyAccess或对应资源的Describe权限)
  • 参考
    references/ram-policies.md
    查看所需权限

Phase 3: Working Directory Initialization

阶段3:工作目录初始化

Ask the user for the following information:
  • Target working directory path (default
    ~/alicloud-terraform
    )
  • Target Region (confirm if already inferred from Phase 2, otherwise ask)
  • Whether a Terraform working directory already exists (skip this Phase if so)
After user confirmation, automatically complete the following:
  1. Create working directory and
    .import/
    subdirectory (for storing intermediate artifacts)
  2. Generate
    provider.tf
    in the target directory (refer to
    examples/provider.tf
    ), replacing the region default with the user-confirmed Region. The provider block must include
    configuration_source = "AlibabaCloud-Agent-Skills/alibabacloud-terraform-import"
    for UA tracking
  3. Run
    terraform init
    in the target directory
  4. Analyze init output, confirm provider download succeeded
  5. (Optional enhancement) Run
    terraform providers schema -json
    , extract fields ending in
    _id
    or
    _ids
    from all resources to build a reference field whitelist for Phase 6. If schema output is too large causing parse timeout, skip this step; Phase 6 will fall back to static dependency rules for reference resolution
  6. (Optional enhancement) Call
    iacservice list-resource-types
    (paginate to get all), replace the
    ALIYUN
    prefix in the
    resourceType
    field with
    ACS
    to build a
    terraformResourceType <-> ResourceCode
    bidirectional mapping table, written to
    .import/resource-type-mapping.json
    for use in Phase 4/5/6. If the call fails or insufficient permissions, fall back to the static mapping table in
    references/resource-hub-api.md
    . Skipping this step does not affect the core import flow, only affects ResourceCenter API resource type conversion
  7. Inform user that initialization is complete, proceed to Phase 4

向用户询问以下信息:
  • 目标工作目录路径(默认
    ~/alicloud-terraform
  • 目标地域(若已从阶段2推断出则确认,否则询问)
  • Terraform工作目录是否已存在(若已存在则跳过本阶段)
用户确认后,自动完成以下操作:
  1. 创建工作目录及
    .import/
    子目录(用于存储中间产物)
  2. 在目标目录生成
    provider.tf
    (参考
    examples/provider.tf
    ),将默认地域替换为用户确认的地域。provider块必须包含
    configuration_source = "AlibabaCloud-Agent-Skills/alibabacloud-terraform-import"
    以实现UA追踪
  3. 在目标目录运行
    terraform init
  4. 分析初始化输出,确认provider下载成功
  5. (可选增强) 运行
    terraform providers schema -json
    ,从所有资源中提取以
    _id
    _ids
    结尾的字段,构建参考字段白名单供阶段6使用。若schema输出过大导致解析超时,则跳过此步骤;阶段6将 fallback 至静态依赖规则解析引用关系
  6. (可选增强) 调用
    iacservice list-resource-types
    (分页获取全部),将
    resourceType
    字段中的
    ALIYUN
    前缀替换为
    ACS
    ,构建
    terraformResourceType <-> ResourceCode
    双向映射表,写入
    .import/resource-type-mapping.json
    供阶段4/5/6使用。若调用失败或权限不足,则 fallback 至
    references/resource-hub-api.md
    中的静态映射表。跳过此步骤不影响核心导入流程,仅影响资源中心API的资源类型转换
  7. 告知用户初始化完成,进入阶段4

Phase 4: Resource Discovery

阶段4:资源发现

Step 0 — Query ResourceCenter Supported Resource Types (execute first)
Run
aliyun resourcecenter list-resource-types
to get the list of resource types supported by API A (search-resources) and API B (list-resource-relationships), cache for use in this Phase and Phase 5. See
references/resource-hub-api.md
for details.
If the call fails or insufficient permissions, skip Step 0 and use native product APIs for resource discovery throughout.
Step 1 — Discover Resources
For each target resource type, choose discovery method by the following priority:
  1. If the resource type is in API A's support list -> Use API A (search-resources) for batch query, see
    references/resource-hub-api.md
  2. Otherwise -> Fall back to native product API commands in
    references/api-commands.md
If the user needs to discover resource types not in
references/api-commands.md
:
  • First check provider docs (
    https://registry.terraform.io/providers/aliyun/alicloud/latest/docs
    ) to determine support:
    • Has
      Import
      section -> Supports
      terraform import
      , proceed normally
    • No
      Import
      section but provider supports the resource -> Can import via manual tfstate construction; inform user of risks before proceeding
    • Provider does not support the resource at all -> Clearly inform that import is not possible
  • After confirming support, check aliyun CLI docs (
    https://help.aliyun.com/document_detail/110244.html
    ) or corresponding product API docs for discovery commands
Execute the appropriate commands, collect output, and generate a resource discovery report summarizing counts and ID lists by type.
Empty discovery results handling:
If a resource type (e.g., NAT Gateway) returns empty results but the user expects them to exist, proactively investigate:
  • Confirm whether the resource is in a different Region
  • Confirm whether the current credentials have Describe permission for that resource
  • Confirm whether the resource has been released (can check audit logs)
  • Inform user that discovery results don't match expectations, ask for confirmation before continuing

步骤0 — 查询资源中心支持的资源类型(优先执行)
运行
aliyun resourcecenter list-resource-types
获取API A(search-resources)和API B(list-resource-relationships)支持的资源类型列表,缓存后供本阶段和阶段5使用。详情请参考
references/resource-hub-api.md
若调用失败或权限不足,跳过步骤0,全程使用原生产品API进行资源发现。
步骤1 — 发现资源
针对每种目标资源类型,按以下优先级选择发现方式:
  1. 若资源类型在API A的支持列表中 -> 使用API A(search-resources)批量查询,参考
    references/resource-hub-api.md
  2. 否则 -> Fallback至
    references/api-commands.md
    中的原生产品API命令
若用户需要发现
references/api-commands.md
中未包含的资源类型:
  • 首先查看provider文档(
    https://registry.terraform.io/providers/aliyun/alicloud/latest/docs
    )确认支持情况:
    • 包含
      Import
      章节 -> 支持
      terraform import
      ,正常执行
    • Import
      章节但provider支持该资源 -> 可通过手动构造tfstate导入;执行前需告知用户相关风险
    • provider完全不支持该资源 -> 明确告知无法导入
  • 确认支持后,查看aliyun CLI文档(
    https://help.aliyun.com/document_detail/110244.html
    )或对应产品API文档获取发现命令
执行相应命令,收集输出,生成资源发现报告,按资源类型汇总数量和ID列表。
空发现结果处理:
若某资源类型(如NAT网关)返回空结果但用户预期其存在,主动排查:
  • 确认资源是否在其他地域
  • 确认当前凭证是否具备该资源的Describe权限
  • 确认资源是否已释放(可查看审计日志)
  • 告知用户发现结果与预期不符,继续前请用户确认

Phase 5: Select Import Scope and Depth

阶段5:选择导入范围与深度

Present the resource discovery report and ask the user:
  • Import all or select specific resource types?
  • Filter by VPC scope?
  • Filter by Tag?
  • Import depth strategy:
    1. Import only discovered resources (no related resource queries, depth=0)
    2. Import one level of related resources (depth=1)
    3. Import complete dependency tree (depth=unlimited, recommended)
Build Resource Dependency Graph (based on depth strategy)
Based on the user's chosen depth strategy:
Depth=0 (import only discovered resources):
  • Skip API B calls
  • Directly use static dependency rules from
    references/dependency-rules.md
    to sort Phase 4 discovered resources
  • Generate import order
Depth=1 (import one level of related resources):
  • For each resource discovered in Phase 4, if its type is in API B's support list -> Call API B (list-resource-relationships) to get directly related resources
  • Do not recursively call API B for returned related resources
  • Merge discovered resources and one-level related resources, topologically sort the resource graph, generate import order
Depth=unlimited (import complete dependency tree, recommended):
  • From Phase 4 discovered resources, identify root resources with no parent dependencies (VPC, OSS Bucket, DNS domains, RAM users, etc.)
  • For each root resource, if its type is in API B's support list -> Call API B to get related resources
  • Recursively call API B for related resources until no new resources appear (new resource set == empty set)
  • For resource types not supported by API B -> Fall back to static dependency rules in
    references/dependency-rules.md
  • Merge all relationship trees, topologically sort the resource graph, generate import order
Fallback static import order (when API B is unavailable):
Layer 0: VPC, OSS Bucket (no dependencies)
Layer 1: VSwitch, Security Group, EIP (depend on VPC)
Layer 2: NAT Gateway, SLB (depend on VPC + VSwitch)
Layer 3: ECS Instance (depends on VSwitch + Security Group)
Layer 4: Disk (depends on ECS)
Layer 5: RDS, Redis, MongoDB (depend on VSwitch)
Layer 6: DNS Record (depends on Domain)
For detailed dependency rules, refer to
references/dependency-rules.md
.

展示资源发现报告并询问用户:
  • 导入全部资源还是选择特定资源类型?
  • 是否按VPC范围过滤?
  • 是否按标签过滤?
  • 导入深度策略
    1. 仅导入已发现的资源(不查询关联资源,深度=0)
    2. 导入一级关联资源(深度=1)
    3. 导入完整依赖树(深度=不限,推荐)
构建资源依赖关系图(基于深度策略)
根据用户选择的深度策略执行:
深度=0(仅导入已发现资源):
  • 跳过API B调用
  • 直接使用
    references/dependency-rules.md
    中的静态依赖规则对阶段4发现的资源排序
  • 生成导入顺序
深度=1(导入一级关联资源):
  • 针对阶段4发现的每个资源,若其类型在API B的支持列表中 -> 调用API B(list-resource-relationships)获取直接关联资源
  • 不对返回的关联资源递归调用API B
  • 合并已发现资源和一级关联资源,对资源图进行拓扑排序,生成导入顺序
深度=不限(导入完整依赖树,推荐):
  • 从阶段4发现的资源中,识别无父依赖的根资源(VPC、OSS Bucket、DNS域名、RAM用户等)
  • 针对每个根资源,若其类型在API B的支持列表中 -> 调用API B获取关联资源
  • 对关联资源递归调用API B,直到无新资源出现(新资源集合为空)
  • 对于API B不支持的资源类型 -> Fallback至
    references/dependency-rules.md
    中的静态依赖规则
  • 合并所有关系树,对资源图进行拓扑排序,生成导入顺序
API B不可用时的Fallback静态导入顺序:
第0层:VPC、OSS Bucket(无依赖)
第1层:VSwitch、安全组、EIP(依赖VPC)
第2层:NAT网关、SLB(依赖VPC + VSwitch)
第3层:ECS实例(依赖VSwitch + 安全组)
第4层:磁盘(依赖ECS)
第5层:RDS、Redis、MongoDB(依赖VSwitch)
第6层:DNS记录(依赖域名)
详细依赖规则请参考
references/dependency-rules.md

Phase 6: Generate Terraform HCL Code

阶段6:生成Terraform HCL代码

Process resources in batches by type. For each resource type:
  1. Execute detail retrieval commands (JSON format)
  2. Parse JSON, generate corresponding .tf files and write to working directory
One file per resource type, filename format:
<product>_<resource_type>.tf
:
vpc_vpcs.tf
vpc_vswitches.tf
vpc_security_groups.tf
vpc_eips.tf
vpc_nat_gateways.tf
ecs_instances.tf
ecs_disks.tf
oss_buckets.tf
rds_instances.tf
kvstore_instances.tf
dds_instances.tf
slb_load_balancers.tf
alidns_domains.tf
alidns_records.tf
Refer to
references/terraform-patterns.md
for HCL code templates and
examples/
for examples.
Cross-Resource Reference Resolution (three-layer strategy)
When generating HCL for each resource, determine for each field value whether to replace with a terraform resource address, using the following priority:
  1. API B relationship first: If the resource was discovered via API B (list-resource-relationships), its parent or related resources are already determined. Combined with the reference field whitelist extracted in Phase 3, find type-matching
    _id
    fields in the current resource and directly replace with the corresponding terraform resource address. The relationship is definitive, no guessing needed.
  2. Whitelist + mapping table dual-match fallback: For resources not covered by API B, if the field name is in the Phase 3 reference field whitelist and the field value has a corresponding entry in the resource ID mapping table, replace with terraform resource address.
  3. dependency-rules.md static rules fallback: For edge cases not covered by the above two layers (composite IDs, reference fields not ending in
    _id
    , etc.), refer to static rules in
    references/dependency-rules.md
    .
Resource ID Mapping Table
After generating each resource block, immediately append a record to the mapping table:
<cloud resource ID>  ->  <terraform resource address>
按资源类型批量处理。针对每种资源类型:
  1. 执行详情查询命令(JSON格式)
  2. 解析JSON,生成对应的.tf文件并写入工作目录
每种资源类型对应一个文件,文件名格式:
<product>_<resource_type>.tf
vpc_vpcs.tf
vpc_vswitches.tf
vpc_security_groups.tf
vpc_eips.tf
vpc_nat_gateways.tf
ecs_instances.tf
ecs_disks.tf
oss_buckets.tf
rds_instances.tf
kvstore_instances.tf
dds_instances.tf
slb_load_balancers.tf
alidns_domains.tf
alidns_records.tf
HCL代码模板请参考
references/terraform-patterns.md
,示例请参考
examples/
目录。
跨资源引用解析(三层策略)
生成每个资源的HCL时,判断每个字段值是否需要替换为Terraform资源地址,按以下优先级执行:
  1. 优先使用API B关系:若资源通过API B(list-resource-relationships)发现,其父资源或关联资源已确定。结合阶段3提取的参考字段白名单,找到当前资源中匹配类型的
    _id
    字段,直接替换为对应的Terraform资源地址。此关系明确,无需猜测。
  2. 白名单+映射表双重匹配Fallback:对于API B未覆盖的资源,若字段名在阶段3的参考字段白名单中,且字段值在资源ID映射表中有对应条目,则替换为Terraform资源地址。
  3. dependency-rules.md静态规则Fallback:对于上述两层未覆盖的边缘情况(复合ID、不以
    _id
    结尾的引用字段等),参考
    references/dependency-rules.md
    中的静态规则。
资源ID映射表
生成每个资源块后,立即向映射表追加记录:
<云端资源ID>  ->  <Terraform资源地址>

Example:

示例:

vpc-bp1xxx -> alicloud_vpc.vpc_prod_main vsw-bp1aaa -> alicloud_vswitch.vsw_prod_a sg-bp1xxx -> alicloud_security_group.sg_web

Write the mapping table to `.import/id-mapping.json` for use in subsequent phases.

**Other key principles:**
- Resource names use `<type>_<name>` format (e.g., `alicloud_vpc.vpc_prod_main`)
- Password/secret fields use variables (`var.db_password`)
- Preserve original tags

---
vpc-bp1xxx -> alicloud_vpc.vpc_prod_main vsw-bp1aaa -> alicloud_vswitch.vsw_prod_a sg-bp1xxx -> alicloud_security_group.sg_web

将映射表写入`.import/id-mapping.json`,供后续阶段使用。

**其他核心原则:**
- 资源名称使用`<type>_<name>`格式(例如`alicloud_vpc.vpc_prod_main`)
- 密码/密钥字段使用变量(`var.db_password`)
- 保留原标签

---

Phase 7: Import State

阶段7:导入状态

Based on the topological sort generated in Phase 5, generate the complete list of
terraform import
commands, present to user for confirmation, then execute in batches.
Batch 1 — Network foundation:
bash
terraform import alicloud_vpc.vpc_<name> <vpc-id>
terraform import alicloud_vswitch.vsw_<name> <vsw-id>
terraform import alicloud_security_group.sg_<name> <sg-id>
Batch 2 — Network ancillary:
bash
terraform import alicloud_nat_gateway.nat_<name> <nat-id>
terraform import alicloud_eip_address.eip_<name> <eip-id>
Batch 3 — Compute:
bash
terraform import alicloud_instance.ecs_<name> <instance-id>
terraform import alicloud_disk.disk_<name> <disk-id>
Batch 4 — Storage:
bash
terraform import alicloud_oss_bucket.bucket_<name> <bucket-name>
Batch 5 — Database:
bash
terraform import alicloud_db_instance.rds_<name> <db-id>
terraform import alicloud_kvstore_instance.redis_<name> <redis-id>
terraform import alicloud_mongodb_instance.mongo_<name> <mongo-id>
Batch 6 — Load Balancing:
bash
terraform import alicloud_slb_load_balancer.slb_<name> <slb-id>
Batch 7 — DNS:
bash
terraform import alicloud_dns_domain.domain_<name> <domain-name>
After each batch, analyze output and handle common errors:
  • ResourceNotFound
    : Resource ID is incorrect, re-verify
  • PermissionDenied
    : Need Describe permission for the corresponding resource
  • already managed
    : Resource already in state, skip
  • ID format error: Refer to import format in
    references/resource-types.md

根据阶段5生成的拓扑排序,生成完整的
terraform import
命令列表,展示给用户确认后批量执行。
批次1 — 网络基础资源:
bash
terraform import alicloud_vpc.vpc_<name> <vpc-id>
terraform import alicloud_vswitch.vsw_<name> <vsw-id>
terraform import alicloud_security_group.sg_<name> <sg-id>
批次2 — 网络辅助资源:
bash
terraform import alicloud_nat_gateway.nat_<name> <nat-id>
terraform import alicloud_eip_address.eip_<name> <eip-id>
批次3 — 计算资源:
bash
terraform import alicloud_instance.ecs_<name> <instance-id>
terraform import alicloud_disk.disk_<name> <disk-id>
批次4 — 存储资源:
bash
terraform import alicloud_oss_bucket.bucket_<name> <bucket-name>
批次5 — 数据库资源:
bash
terraform import alicloud_db_instance.rds_<name> <db-id>
terraform import alicloud_kvstore_instance.redis_<name> <redis-id>
terraform import alicloud_mongodb_instance.mongo_<name> <mongo-id>
批次6 — 负载均衡资源:
bash
terraform import alicloud_slb_load_balancer.slb_<name> <slb-id>
批次7 — DNS资源:
bash
terraform import alicloud_dns_domain.domain_<name> <domain-name>
每个批次执行后,分析输出并处理常见错误:
  • ResourceNotFound
    :资源ID错误,重新验证
  • PermissionDenied
    :需要对应资源的Describe权限
  • already managed
    :资源已在状态中,跳过
  • ID格式错误:参考
    references/resource-types.md
    中的导入格式

Phase 8: Validation

阶段8:验证

Execute the following commands to validate import results:
bash
undefined
执行以下命令验证导入结果:
bash
undefined

List all resources in state

列出状态中的所有资源

terraform state list 2>&1
terraform state list 2>&1

Run plan, target is No changes

执行计划,目标为无变更

terraform plan -refresh=true 2>&1

Analyze plan output:
- `No changes` -> Validation passed, proceed to Phase 9
- Has diff -> Analyze the cause, refer to common diff fix patterns in `references/terraform-patterns.md`, provide fix recommendations and inform user, execute fix after user confirmation

Common diff causes:
- Tag format mismatch (need to adjust tags syntax in HCL)
- Password fields cannot be read from API (use `ignore_changes` to ignore)
- Computed field differences (add `lifecycle { ignore_changes = [...] }`)
- Default value differences (explicitly set values matching the cloud)

---
terraform plan -refresh=true 2>&1

分析计划输出:
- `No changes` -> 验证通过,进入阶段9
- 存在差异 -> 分析原因,参考`references/terraform-patterns.md`中的常见差异修复模式,提供修复建议并告知用户,用户确认后执行修复

常见差异原因:
- 标签格式不匹配(需调整HCL中的标签语法)
- 密码字段无法从API读取(使用`ignore_changes`忽略)
- 计算字段差异(添加`lifecycle { ignore_changes = [...] }`)
- 默认值差异(显式设置与云端匹配的值)

---

Phase 9: Resource Relationship Graph

阶段9:资源关系图

Execute the following commands to generate a resource relationship graph:
bash
undefined
执行以下命令生成资源关系图:
bash
undefined

Export state JSON

导出状态JSON

terraform show -json > .import/tf_state.json 2>&1
terraform show -json > .import/tf_state.json 2>&1

Extract dependencies

提取依赖关系

python3 -c " import json, sys with open('.import/tf_state.json') as f: state = json.load(f) resources = state.get('values', {}).get('root_module', {}).get('resources', []) print(f'Total resources: {len(resources)}') for r in resources: deps = r.get('depends_on', []) if deps: for d in deps: print(f' {d} --> {r["address"]}') " 2>&1

Based on output, generate a text-format resource relationship graph (tree structure) showing:
- Network layer -> Compute layer -> Data layer dependency chains
- Security group cross-cutting references
- Load balancer backend binding relationships

Refer to `examples/dependency-graph.txt` for example format.

---
python3 -c " import json, sys with open('.import/tf_state.json') as f: state = json.load(f) resources = state.get('values', {}).get('root_module', {}).get('resources', []) print(f'Total resources: {len(resources)}') for r in resources: deps = r.get('depends_on', []) if deps: for d in deps: print(f' {d} --> {r["address"]}') " 2>&1

基于输出生成文本格式的资源关系图(树形结构),展示:
- 网络层 -> 计算层 -> 数据层的依赖链
- 安全组的跨域引用
- 负载均衡的后端绑定关系

示例格式请参考`examples/dependency-graph.txt`。

---

Incremental Sync Mode

增量同步模式

Use this mode when a Terraform working directory already exists. Automatically detects three types of changes:
1. Detect new resources (exist in cloud, not in state):
Execute the following commands to compare state and cloud ID lists:
bash
undefined
当Terraform工作目录已存在时使用此模式,自动检测三类变更:
1. 检测新增资源(存在于云端,不存在于状态中):
执行以下命令对比状态与云端ID列表:
bash
undefined

ECS example

ECS示例

terraform state list | grep alicloud_instance aliyun ecs describe-instances --biz-region-id $REGION --page-size 100
--output cols=InstanceId rows=Instances.Instance 2>&1

Compare the two lists, find the difference set, generate HCL + import commands for new resources, inform user for confirmation before executing.

**2. Detect deleted resources (exist in state, not in cloud):**

Run existence checks for each resource in state; if API returns empty, execute:
```bash
terraform state rm alicloud_instance.<name>
3. Detect configuration drift:
Execute the following command to detect drift:
bash
terraform plan -refresh=true 2>&1
For detailed incremental sync procedures, refer to
references/incremental-sync.md
.

terraform state list | grep alicloud_instance aliyun ecs describe-instances --biz-region-id $REGION --page-size 100
--output cols=InstanceId rows=Instances.Instance 2>&1

对比两个列表,找出差异集合,为新增资源生成HCL+导入命令,告知用户确认后执行。

**2. 检测已删除资源(存在于状态中,不存在于云端):**

对状态中的每个资源执行存在性检查;若API返回空结果,执行:
```bash
terraform state rm alicloud_instance.<name>
3. 检测配置漂移:
执行以下命令检测漂移:
bash
terraform plan -refresh=true 2>&1
详细增量同步流程请参考
references/incremental-sync.md

References

参考文档

  • references/resource-types.md
    — Complete resource type mapping table (20+ resource types)
  • references/terraform-patterns.md
    — HCL code templates + common diff fixes
  • references/state-management.md
    — terraform state command reference
  • references/api-commands.md
    — aliyun CLI command quick reference (native product API fallback path)
  • references/dependency-rules.md
    — Resource dependency layers and import order (API B fallback path)
  • references/resource-hub-api.md
    — ResourceCenter API guide (list-resource-types / search-resources / list-resource-relationships)
  • references/incremental-sync.md
    — Detailed incremental sync procedures
  • references/resource-types.md
    — 完整资源类型映射表(20+种资源类型)
  • references/terraform-patterns.md
    — HCL代码模板+常见差异修复方案
  • references/state-management.md
    — terraform state命令参考
  • references/api-commands.md
    — aliyun CLI命令速查(原生产品API fallback路径)
  • references/dependency-rules.md
    — 资源依赖层级与导入顺序(API B fallback路径)
  • references/resource-hub-api.md
    — 资源中心API指南(list-resource-types / search-resources / list-resource-relationships)
  • references/incremental-sync.md
    — 详细增量同步流程