/alibabacloud-core:alibabacloud-terraform-importfrom alibabacloud-core
Guides step-by-step import of existing Alibaba Cloud resources into Terraform, covering environment checks, authentication, resource discovery, HCL generation, state import, validation, and dependency graph. Supports one-time migration and incremental sync.
Ships in alibabacloud-core. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them.
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:
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.list-resource-types results with IaCService
list-resource-types Terraform mappings. Apply the ResourceCenter alias table
in references/resource-hub-api.md to handle code mismatches such as EIP,
NAT, MongoDB, and ACK.get-provider-document through MCP to confirm provider support,
import instructions, arguments, and exported attributes. Do not fetch or read
provider docs by default for common resources already covered by local
references.references/api-commands.md,
references/terraform-patterns.md, and references/resource-types.md
provide verified discovery commands, HCL templates, and complex import ID
formats.All Alibaba Cloud API calls MUST be executed through the alibabacloud-core
MCP CallCLI-compatible tool. This includes every command that starts with
aliyun <product> ..., aliyun resourcecenter ..., aliyun iacservice ...,
aliyun sts ..., and aliyun ossutil ....
Tool names may be namespace-prefixed by the host client. Select the MCP tool
whose name ends with AlibabaCloud___CallCLI or is documented by the installed
plugin as CallCLI, and pass the CLI command string as that tool's command
argument.
Do NOT execute Alibaba Cloud API commands in the local shell unless the user
explicitly opts into a local CLI fallback because MCP is unavailable. Local shell
execution is still allowed for non-cloud local operations: terraform, python3,
mkdir, file writes, JSON processing, and local environment checks.
The bash snippets in this skill and its references/ are command references.
For cloud API commands, run the aliyun ... line via MCP CallCLI rather than
copying the entire bash block into a local shell. Avoid shell pipes,
redirections, variables, or command substitutions inside CallCLI; resolve values
first and pass one concrete aliyun ... command per MCP call.
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):
aliyun vpc describe-vpcs --biz-region-id cn-shanghai --page-size 50
Parameter conversion rules:
--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--page-size (not PageSize)--vpc-id, InstanceIds -> --instance-ids). Use aliyun <product> <command> --help to confirm--endpoint resourcecenter.aliyuncs.com on
every aliyun resourcecenter ... command. Do not rely on CLI plugin endpoint
auto-resolution for ResourceCenter.aliyun ossutil ls; get
bucket details with aliyun ossutil api get-bucket-* --bucket <bucket>
commands such as get-bucket-acl, get-bucket-versioning,
get-bucket-lifecycle, get-bucket-encryption, get-bucket-tags,
get-bucket-policy, and get-bucket-info. Do not use ossutil stat as the
only source for redundancy_type; it may omit DataRedundancyType.Run the following local commands to detect the environment. The local aliyun
CLI is optional when MCP CallCLI is available; Terraform import/state operations
still require local Terraform.
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:
brew tap hashicorp/tap && brew install hashicorp/tap/terraformOnce all tools are ready, proceed to Phase 2.
Configure API invocation attribution:
When using MCP CallCLI, prefer MCP/plugin-level attribution when available. If the user explicitly opts into local aliyun CLI fallback, configure AI-Mode before executing any local aliyun command:
# Enable AI-Mode (required)
aliyun configure ai-mode enable
# Set User-Agent identifier (required)
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 local aliyun CLI commands will automatically carry AI-Mode and User-Agent identifiers. MCP CallCLI commands are still preferred for cloud API calls. See the "Command Format Requirements" section above for command formatting rules.
Disable AI-Mode (when the session ends or if needed):
aliyun configure ai-mode disable
This Skill relies on the Alibaba Cloud default credential chain for authentication, supporting the following methods (by priority):
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 MCP CallCLI and the default credential chain (without explicitly passing AK/SK):
aliyun sts get-caller-identity 2>&1
Analyze the output:
If an error occurs, prompt the user to:
aliyun configure or environment variables)references/ram-policies.md for required permissionsAsk the user for the following information:
~/alicloud-terraform)After user confirmation, automatically complete the following:
.import/ subdirectory (for storing intermediate artifacts)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 trackingterraform init in the target directoryterraform 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 resolutioniacservice list-resource-types through MCP CallCLI (paginate to get
all), replace the ALIYUN prefix in the resourceType field with ACS,
and build a terraformResourceType <-> ResourceCode bidirectional mapping
table.resourcecenter list-resource-types --endpoint resourcecenter.aliyuncs.com through MCP CallCLI and join its ResourceType
values with the IaCService mapping table to determine which resource types
are both discoverable by ResourceCenter and representable as Terraform
resources.references/resource-hub-api.md into byResourceCode so ResourceCenter
codes that differ from IaCService codes (e.g., ACS::EIP::EipAddress vs
ACS::EIP::Address) resolve correctly without LLM fallback..import/resource-type-mapping.json for Phase 4/5/6.
Initialize .import/provider-doc-index.json as an empty cache keyed by
terraformResourceType; later phases append compact provider doc evidence.
If either API call fails or permissions are insufficient, fall back to the
static mapping table in references/resource-hub-api.md and native product
APIs in references/api-commands.md.Call aliyun resourcecenter list-resource-types --endpoint resourcecenter.aliyuncs.com through MCP CallCLI 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. Every
ResourceCenter call in this phase must include --endpoint resourcecenter.aliyuncs.com. See references/resource-hub-api.md for details.
Do not rely on a SupportedFeatures field in this response; some environments
omit it. Treat returned ResourceType values as candidates and probe API A/B
once per target resource type, caching success or failure. If the call fails or
insufficient permissions, skip Step 0 and use native product APIs for resource
discovery throughout.
For each target resource type, choose discovery method by the following priority:
references/resource-hub-api.mdreferences/api-commands.mdKnown native-API fallbacks:
vpc describe-nat-gateways when the user asks for NAT resources or a VPC
dependency tree includes them.If the user needs to discover resource types not in references/api-commands.md:
First check provider docs through IaCService get-provider-document via MCP
CallCLI, not WebFetch, to determine support:
aliyun iacservice get-provider-document --resource-type alicloud_<name> --endpoint iac.cn-zhangjiakou.aliyuncs.com
Cache the result or extracted evidence in .import/provider-doc-index.json.
Extract only the relevant sections (Import, Argument Reference,
Attributes Reference) instead of loading or reciting the full document.
Import section -> Supports terraform import, proceed normallyImport section but provider supports the resource -> Can import via manual tfstate construction; inform user of risks before proceedingAfter 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 cloud API commands through MCP CallCLI, 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:
Present the resource discovery report and ask the user:
Based on the user's chosen depth strategy:
references/dependency-rules.md to sort Phase 4 discovered resourcesreferences/dependency-rules.mdLayer 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.
Process resources in batches by type. For each resource type:
references/terraform-patterns.md and
references/api-commands.md, provider doc fetch is optional.get-provider-document once for the distinct terraformResourceType..import/provider-doc-index.json: import
support status, import ID format if present, required arguments, key
optional arguments relevant to the cloud details, and exported attributes.Provider-version and field-safety rules:
terraform providers schema -json or the initialized provider version to
choose version-sensitive attribute names. For alicloud_security_group, use
security_group_name only when the provider schema supports it; otherwise use
legacy name.description = "". Some
alicloud provider schemas reject empty descriptions or would plan to clear a
non-empty cloud-side description.get-bucket-info,
get-bucket-lifecycle, get-bucket-encryption, get-bucket-tags,
get-bucket-policy, get-bucket-versioning, and get-bucket-cors.
Only emit blocks or attributes that are present in the cloud result or
imported state. Set redundancy_type to the actual value from
get-bucket-info or imported state; never default it to LRS or ZRS.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.
When generating HCL for each resource, determine for each field value whether to replace with a terraform resource address, using the following priority:
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.
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.
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.
After generating each resource block, immediately append a record to the mapping table:
<cloud resource ID> -> <terraform resource address>
# 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:
<type>_<name> format (e.g., alicloud_vpc.vpc_prod_main)var.db_password)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.
Before generating each import command, resolve the import ID format in this order:
references/resource-types.md for known composite IDs and special cases..import/provider-doc-index.json.get-provider-document via MCP CallCLI, extracting only the
Import section.Batch 1 — Network foundation:
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:
terraform import alicloud_nat_gateway.nat_<name> <nat-id>
terraform import alicloud_eip_address.eip_<name> <eip-id>
Batch 3 — Compute:
terraform import alicloud_instance.ecs_<name> <instance-id>
terraform import alicloud_disk.disk_<name> <disk-id>
Batch 4 — Storage:
terraform import alicloud_oss_bucket.bucket_<name> <bucket-name>
Batch 5 — Database:
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:
terraform import alicloud_slb_load_balancer.slb_<name> <slb-id>
Batch 7 — DNS:
terraform import alicloud_dns_domain.domain_<name> <domain-name>
After each batch, analyze output and handle common errors:
ResourceNotFound: Resource ID is incorrect, re-verifyPermissionDenied: Need Describe permission for the corresponding resourcealready managed: Resource already in state, skipreferences/resource-types.mdExecute the following commands to validate import results:
# List all resources in state
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 9references/terraform-patterns.md, provide fix recommendations and inform user, execute fix after user confirmationCommon diff causes:
ignore_changes to ignore)lifecycle { ignore_changes = [...] })Execute the following commands to generate a resource relationship graph:
# Export state JSON
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:
Refer to examples/dependency-graph.txt for example format.
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. Run
terraform state list locally, but run the aliyun ... cloud query through MCP
CallCLI:
# ECS example
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:
terraform state rm alicloud_instance.<name>
3. Detect configuration drift:
Execute the following command to detect drift:
terraform plan -refresh=true 2>&1
For detailed incremental sync procedures, refer to references/incremental-sync.md.
references/resource-types.md — Complete resource type mapping table (20+ resource types)references/terraform-patterns.md — HCL code templates + common diff fixesreferences/state-management.md — terraform state command referencereferences/api-commands.md — aliyun CLI command quick reference for MCP CallCLI product API queriesreferences/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 proceduresDo not read reference files fully unless they are directly needed for the current phase. Prefer targeted search by resource type, product, API name, or error message.
examples/dependency-graph.txt (opens in a new tab)examples/ecs-example.tf (opens in a new tab)examples/import-commands.sh (opens in a new tab)examples/oss-example.tf (opens in a new tab)examples/provider.tf (opens in a new tab)examples/rds-example.tf (opens in a new tab)examples/vpc-example.tf (opens in a new tab)references/api-commands.md (opens in a new tab)references/dependency-rules.md (opens in a new tab)references/incremental-sync.md (opens in a new tab)references/ram-policies.md (opens in a new tab)references/resource-hub-api.md (opens in a new tab)references/resource-types.md (opens in a new tab)references/state-management.md (opens in a new tab)references/terraform-patterns.md (opens in a new tab)What SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
10 skills in this plugin
/alibabacloud-cli-cost-estimationPre-execution cost estimation for Alibaba Cloud CLI operations. Use this skill whenever a user asks "how much will this cost", before executing any chargeable operation (create / resize / renew / bandwidth change), or when planning a multi-step workflow whose total cost should be known up front. Covers the --estimate-cost flag (quote without executing), --estimate-cost-context (usage assumptions and future-state overrides for multi-step workflows), reading the quote JSON correctly (pricingMode, pricingUnit, delta amounts), and reconciling quotes against actual bills.
/alibabacloud-cli-guidanceGuide for Alibaba Cloud CLI (aliyun) command syntax, plugin system, parameter naming, and best practices. Use this skill to generate correct CLI commands, understand plugin vs built-in command differences, structured parameter syntax, output filtering, pagination, and error troubleshooting. This skill is a CLI knowledge reference — when MCP tools (AlibabaCloud___CallCLI, etc.) are available, always prefer MCP tools for execution rather than running aliyun commands locally in the shell.
/alibabacloud-find-skillsUse this skill when users want to search, discover, browse, or find Alibaba Cloud (阿里云) agent skills. Triggers include: "find a skill for X", "search alicloud skills", "阿里云有什么 skill","阿里云", "搜索阿里云技能", "有没有管理 ECS/RDS/OSS 的 skill", "阿里云 skills 有哪些类目", "帮我找一个 skill", "browse alicloud skills", "list alicloud skill categories", "is there an alicloud skill that can...", "what alicloud skills are available", "XX Skill 的内容是什么", "我想了解阿里云 XX Skill 具体做什么","帮我安装阿里云 Skill","使用阿里云相关的skill", "阿里云 agent skill 市场", "搜一下阿里云的 skill", "建一个数据分析项目有没有相关 skill".
npx claudepluginhub aliyun/alibabacloud-agent-toolkit --plugin alibabacloud-coreOther plugins' skills for the same job