Managing existing resources
Learn how to import existing cloud resources into Terraform using the import command, import block, or Terraformer.
Background
Terraform automates cloud resource management through Infrastructure as Code (IaC). New resources can be created directly with Terraform code, but existing resources or those created outside Terraform require importing. The import process generates resource code and a state file, enabling ongoing Terraform management.
Resource import brings existing cloud resources under Terraform management.
Scenarios
Resource import applies to these common scenarios:
-
Manage existing resources: Transition resources managed by other tools, such as the console, API, or command-line interface (CLI), to Terraform management.
-
Resolve resource drift: When a Terraform-managed resource is modified outside of Terraform, its state diverges from the configuration. Re-import the resource to sync the state.
-
Refactor code: Split a monolithic configuration file into smaller files to reduce management complexity as your resource count grows.
-
Quickly deploy resources: Replicate and deploy an existing resource architecture to a different region or account.
-
Quickly recover resources: Regularly back up your resource architecture. If a stability issue occurs, you can use the backup code to quickly recover the architecture.
Procedure
Three methods are available to import resources:
-
The import command: Imports a single resource using the native Terraform command
terraform import. -
The import block: Imports one or more resources by writing a Terraform import block and running
terraform planandterraform apply. -
The Terraformer tool: Imports resources in batches by running commands with the open-source Terraformer tool to filter and query them.
Choose the method that best fits your scenario.
|
Import method |
Advantages |
Disadvantages |
Scenarios |
|
The import command |
|
|
Manage existing resources Resolve resource drift Refactor code |
|
The import block |
|
|
Manage existing resources Resolve resource drift Refactor code Quickly deploy resources |
|
Terraformer |
|
|
Manage existing resources Resolve resource drift Refactor code Quickly deploy resources Quickly recover resources |
The Terraform import command
The <a class="ne-link" data-href="https://developer.hashicorp.com/terraform/cli/commands/import" href="https://developer.hashicorp.com/terraform/cli/commands/import" id="653ac62fdfgjr" target="_blank">terraform import</a> command imports resources by specifying a resource address and a resource ID, and accepts several configuration parameters.
Prerequisites
-
Prepare a Terraform runtime environment using one of the following methods:
-
Create resources with Terraform: Cloud Shell comes pre-installed with Terraform and configured credentials. Suitable for quick access.
-
Install and configure Terraform: Suitable for restricted network environments or custom development setups.
-
-
Grant read-only permissions for the relevant resources to the active account.
Usage
The command format is terraform import [options] <address> <id>.
-
Resource address: The format is
<resource_type>.<resource_name>. It includes the resource type and name, and serves as the identifier for the infrastructure in the state file.-
For example, the resource address for the VPC in the following configuration snippet is
alicloud_vpc.default.
resource "alicloud_vpc" "default" { vpc_name = "tf-example" cidr_block = "10.0.0.0/8" } -
-
Resource ID: A resource ID uniquely identifies a resource for import. The ID format varies by resource type — check the Provider documentation.
-
For example, the resource ID for
alicloud_security_groupis the security group ID. The resource ID foralicloud_security_group_rulefollows a specific format.

-
-
Configuration options: The Terraform import command accepts additional options documented in the official usage instructions.
Example
The following example imports an Object Storage Service (OSS) bucket:
-
Create a working directory. In the directory, create a configuration file named main.tf and define the address of the resource to import.
resource "alicloud_oss_bucket" "default"{ } -
The ID of an alicloud_oss_bucket resource is the bucket name.
-
Initialize the runtime environment.
terraform init -
Run the import command.
# Replace this with your bucket name terraform import alicloud_oss_bucket.default oss-bucket-importThe following output indicates a successful import:
alicloud_oss_bucket.default: Importing from ID "oss-bucket-import"... alicloud_oss_bucket.default: Import prepared! Prepared alicloud_oss_bucket for import alicloud_oss_bucket.default: Refreshing state... [id=oss-bucket-import] Import successful! The resources that were imported are shown above. These resources are now in your Terraform state and will henceforth be managed by Terraform. -
After importing, resource properties are not added to your template automatically. Run
terraform showto view all properties of the imported resource:# alicloud_oss_bucket.default: resource "alicloud_oss_bucket" "default" { acl = "private" bucket = "oss-bucket-import" creation_date = "2024-11-22" extranet_endpoint = "oss-cn-beijing.aliyuncs.com" id = "oss-bucket-import" intranet_endpoint = "oss-cn-beijing-internal.aliyuncs.com" location = "oss-cn-beijing" owner = "1511928*****" redundancy_type = "ZRS" resource_group_id = "rg-acf***" storage_class = "Standard" tags = {} access_monitor { status = "Disabled" } }Add this information to your template and remove read-only properties as described in alicloud_oss_bucket , you can use Terraform to manage your resources.
The Terraform import block
Terraform v1.5.0 and later supports resource imports using an `import` block. Write an `import` block in your configuration file to specify the resource ID and address, then run the terraform plan and terraform apply commands to preview and execute the import.
For more information, see the official documentation.
Prerequisites
-
Prepare a Terraform runtime environment using one of the following methods:
NoteRequires Terraform v1.5.0 or later.
-
Create resources with Terraform: Cloud Shell comes pre-installed with Terraform and configured credentials. Suitable for quick access.
-
Install and configure Terraform: Suitable for restricted network environments or custom development setups.
-
-
Grant read-only permissions for the relevant resources to the active account.
Usage
The syntax is as follows:
import {
to = alicloud_oss_bucket.example
id = "oss-bucket-import"
}
# Optional
# resource "alicloud_oss_bucket" "example" {
# # (other resource arguments...)
# }
The import block offers two advantages over the import command:
-
Automatically generates configuration. Import to an existing resource address, or use
-generate-config-outto auto-generate the configuration file. -
Batch imports. Use
for_eachin an `import` block to import multiple resources. Resources with similar attributes can share a resource address, differentiated by index.
These two features cannot be combined. The Terraform CLI does not support auto-generating configurations for resources that use for_each.
Example
The following example imports an OSS bucket using an import block:
-
Create a working directory with a main.tf file. Write an import block to specify the resource ID and address.
import { to = alicloud_oss_bucket.default id = "oss-bucket-import" } -
Initialize the runtime environment.
terraform init -
Run
terraform planto preview the import. Use-generate-config-outto auto-generate the template.terraform plan -generate-config-out=generated.tfThe following information is displayed:
alicloud_oss_bucket.default: Preparing import... [id=oss-bucket-import] alicloud_oss_bucket.default: Refreshing state... [id=oss-bucket-import] Terraform will perform the following actions: # alicloud_oss_bucket.default will be imported # (config will be generated) resource "alicloud_oss_bucket" "default" { acl = "private" bucket = "oss-bucket-import" creation_date = "2024-11-22" extranet_endpoint = "oss-cn-beijing.aliyuncs.com" id = "oss-bucket-import" intranet_endpoint = "oss-cn-beijing-internal.aliyuncs.com" location = "oss-cn-beijing" owner = "15119****" redundancy_type = "ZRS" resource_group_id = "rg-acfmzaq*****" storage_class = "Standard" tags = {} access_monitor { status = "Disabled" } } Plan: 1 to import, 0 to add, 0 to change, 0 to destroy. ╷ │ Warning: Config generation is experimental │ │ Generating configuration during import is currently experimental, and the generated configuration │ format may change in future versions. ╵ ───────────────────────────────────────────────────────────────────────────────────────────────────── Terraform has generated configuration and written it to generated.tf. Please review the configuration and edit it as necessary before adding it to version control. Note: You didn't use the -out option to save this plan, so Terraform can't guarantee to take exactly these actions if you run "terraform apply" now. -
After confirming the plan, run
terraform applyto execute the import.terraform applyEnter yes when prompted. The following output indicates that the import is successful:
...... Do you want to perform these actions? Terraform will perform the actions described above. Only 'yes' will be accepted to approve. Enter a value: yes alicloud_oss_bucket.default: Importing... [id=oss-bucket-import] alicloud_oss_bucket.default: Import complete [id=oss-bucket-import] Apply complete! Resources: 1 imported, 0 added, 0 changed, 0 destroyed.
The Terraformer tool
The open-source Terraformer tool batch-imports resources from your account into Terraform templates. It supports a subset of resources per cloud provider; additional resources require custom provider development.
Two versions of Terraformer are available:
-
Open-source Terraformer: The original version, supporting resource import from multiple cloud providers.
-
Alibaba Cloud Terraformer: An enhanced version supporting Alibaba Cloud resources exclusively.
|
Feature |
Open-source Terraformer |
Alibaba Cloud Terraformer |
|
View the list of supported products for import |
❌ |
✅ |
|
View the list of supported resource types for import |
❌ |
✅ |
|
Filter by region |
✅ |
✅ |
|
Filter by excluding specified regions |
❌ |
❌ |
|
Filter by zone |
❌ |
✅ |
|
Filter by excluding specified zones |
❌ |
❌ |
|
Filter by product |
❌ |
✅ |
|
Filter by excluding specified products |
❌ |
✅ |
|
Filter by resource type |
✅ |
✅ |
|
Filter by excluding specified resource types |
✅ |
✅ |
|
Filter by a list of resource IDs |
✅ |
✅ |
|
Filter by excluding a specified list of resource IDs |
❌ |
❌ |
|
Filter by resource name |
✅ |
✅ |
|
Filter by resource group |
✅ |
✅ |
|
Filter by tag |
✅ |
✅ |
|
Automatically create resource dependencies |
❌ |
✅ |
|
Automatically generate variables |
❌ |
✅ |
|
Automatically generate outputs |
❌ |
❌ |
Open-source Terraformer
Prerequisites
-
Download and install Terraformer
Terraformer is available as an all-provider package or per-provider packages. The following examples show Linux and macOS installation. Additional options are in the Installation guide.
-
Linux users
export PROVIDER=all curl -LO "https://github.com/GoogleCloudPlatform/terraformer/releases/download/$(curl -s https://api.github.com/repos/GoogleCloudPlatform/terraformer/releases/latest | grep tag_name | cut -d '"' -f 4)/terraformer-${PROVIDER}-linux-amd64" chmod +x terraformer-${PROVIDER}-linux-amd64 sudo mv terraformer-${PROVIDER}-linux-amd64 /usr/local/bin/terraformer-
macOS users
export PROVIDER=all curl -LO "https://github.com/GoogleCloudPlatform/terraformer/releases/download/$(curl -s https://api.github.com/repos/GoogleCloudPlatform/terraformer/releases/latest | grep tag_name | cut -d '"' -f 4)/terraformer-${PROVIDER}-darwin-amd64" chmod +x terraformer-${PROVIDER}-darwin-amd64 sudo mv terraformer-${PROVIDER}-darwin-amd64 /usr/local/bin/terraformer -
-
Dependencies
-
Grant the current account read-only permissions for the relevant resources.
-
Install Terraform
NoteYou can skip this step if you run the command in Cloud Shell.
For more information, see Install and configure Terraform.
-
Download the relevant provider. You can configure the provider in one of the following two ways:
-
Initialize the provider in the directory from which you run the Terraformer command.
-
Download the provider to the ~/.terraform.d/plugins/ path.
-
-
Configure access credentials. Terraformer currently supports authentication only by reading a local profile. By default, the first credential in the profile is used for the import. For more information about how to configure Alibaba Cloud access credentials, see Configure credentials.
-
Usage
The following example uses terraformer-all-darwin-amd64 v0.8.24.
Terraformer supports four commands: help, import, plan, and version.
-
help: Display details about a command.

-
version: Display the current version number.

-
import: Import resources for a specified provider.

-
plan: Preview resources to be imported for a specified provider.
Example
The following example imports all Alibaba Cloud VPCs in the China (Hangzhou) region.
-
Create a directory to store the imported templates and state files.
mkdir example && cd example -
Run the following command:
terraformer-all-darwin-arm64 import alicloud --resources=vpc --regions=cn-hangzhou --path-pattern={output} --path-output=./-
--resources: Specifies the collection of resources to import. -
--regions: Specifies the region where the resources are located. -
--path-pattern: Specifies the pattern for the generated directory structure. -
--path-output: Specifies the output path for the generated files.
-
-
The generated template files are as follows. By default, region information is added to the directory path. To consolidate all resource templates into one file, use the
--compactparameter, which outputs all resources toresources.tf.└── cn-hangzhou ├── outputs.tf ├── provider.tf ├── terraform.tfstate ├── variables.tf ├── vpc.tf └── vswitch.tf 2 directories, 6 files -
For Terraform
>=0.13.0, run the following command to update the state file for version compatibility.terraform state replace-provider -auto-approve "registry.terraform.io/-/alicloud" "aliyun/alicloud"
Alibaba Cloud Terraformer - aliterraformer (Recommended)
aliterraformer extends open-source Terraformer with broader resource coverage, enhanced credential configuration, and additional import filtering dimensions.
Prerequisites
-
Download and install
Download aliterraformer from Alibaba Cloud OSS:
macOS
# amd64 wget https://terraform-share.oss-cn-hangzhou.aliyuncs.com/aliterraformer/aliterraformer_darwin_amd64.zip # arm64 wget https://terraform-share.oss-cn-hangzhou.aliyuncs.com/aliterraformer/aliterraformer_darwin_arm64.zipLinux
# amd64 wget https://terraform-share.oss-cn-hangzhou.aliyuncs.com/aliterraformer/aliterraformer_linux_amd64.zip # arm wget https://terraform-share.oss-cn-hangzhou.aliyuncs.com/aliterraformer/aliterraformer_linux_arm.zip # arm64 wget https://terraform-share.oss-cn-hangzhou.aliyuncs.com/aliterraformer/aliterraformer_linux_arm64.zipWindows
# amd64 wget https://terraform-share.oss-cn-hangzhou.aliyuncs.com/aliterraformer/aliterraformer_windows_amd64.zip # 386 wget https://terraform-share.oss-cn-hangzhou.aliyuncs.com/aliterraformer/aliterraformer_windows_386.zipFor example, on macOS, decompress the file after downloading:
unzip aliterraformer_darwin_amd64.zip chmod +x aliterraformer sudo mv aliterraformer /usr/local/bin/aliterraformer -
Dependencies
Like open-source Terraformer, you need the terraform and terraform-provider-alicloud binaries and configured access credentials.
-
Grant read-only permissions for the relevant resources to the Resource Access Management (RAM) account.
-
Install Terraform
For more information, see Install and configure Terraform. You can skip this step if you run the command in Cloud Shell.
-
Download terraform-provider-alicloud
You can specify the provider version for import. The cache directory structure differs between pre-v0.13.0 and v0.13.0+. The following paths apply to v0.13.0+:
# 1. Set using the TF_DATA_TFER_DIR environment variable <$TF_DATA_TFER_DIR>/providers/registry.terraform.io/aliyun/alicloud/1.239.0/darwin_arm64/terraform-provider-alicloud_v1.239.0 # 2. Set in the hidden directory of the current working directory .terraform/providers/registry.terraform.io/aliyun/alicloud/1.239.0/darwin_arm64/terraform-provider-alicloud_v1.239.0 # 3. Set in the hidden directory of the user's root directory <HOME>/.terraform.d/plugins/registry.terraform.io/aliyun/alicloud/1.239.0/darwin_arm64/terraform-provider-alicloud_v1.239.0 -
Configure access credentials
In addition to using profiles, you can set access credentials in aliterraformer using environment variables and command parameters:
# 1. Using the ALICLOUD_ACCESS_KEY and ALICLOUD_SECRET_KEY environment variables $ export ALICLOUD_ACCESS_KEY=xxxx $ export ALICLOUD_SECRET_KEY=xxxxx # 2. By passing the --access-key and --secret-key command parameters $ aliterraformer import alicloud --access-key=xxxx --secret-key=xxx ... # 3. By setting and passing the AK through the profile mechanism $ aliterraformer import alicloud --profile=default ...
-
Usage
aliterraformer supports five commands: help, version, products, resources, import. The products, resources commands are additions to open-source Terraformer.
-
help: View details about the supported commands.
aliterraformer help
-
version: View the current Terraformer version.
aliterraformer version -
products: List products supported for import in the current version.
aliterraformer products
-
resources: List importable resource types for a product. Use
-pto specify the product.aliterraformer resources -p <productName>

-
import: Import resources. Specify alicloud for Alibaba Cloud. Run the following command to view available parameters:
aliterraformer import alicloud -h
Define the resource collection to import, then optionally filter resources and extract properties as variables.
-
Build a resource collection:
Four flags define the import scope: <--products>, <--resources>, <--excludes-products>, and <--excludes>. Combine them to build a resource collection:
-
Import specific resources
# Import a VPC, a vSwitch, and an ECS instance aliterraformer import alicloud -r=vpc,vswitch,instance -
Import specific products
# Import all resources under the ACK and ALB products aliterraformer import alicloud --products=ACK,ALB -
Import specific products and resources
# Import all resources under the ACK and ECS products, and all VPCs and vSwitches aliterraformer import alicloud --products=ACK,ECS -r=vpc,vswitch -
Import specific products, but exclude some resources within those products
# Import all resources under ACK except alicloud_cs_kubernetes aliterraformer import alicloud --products=ACK --excludes=cs_kubernetes -
Import all resources from all products
# Entering ALL for products means all products aliterraformer import alicloud --products=ALL -
Import all resources from all products, but exclude specific products
# Import all products except VPNGateway and WAF aliterraformer import alicloud --products=ALL --excludes-products=VPNGateway,WAF -
Import all resources from all products, but exclude specific products and resources
# Import all products except VPNGateway and WAF, and exclude the alicloud_cs_kubernetes resource aliterraformer import alicloud --products=ALL --excludes-products=VPNGateway,WAF --excludes=cs_kubernetes
-
-
Filter resources
Format:
--filter=Type1.AttrKey=AttrValue1;AttrValue2,Type2.AttrKey=AttrValue1;AttrValue2. Omitting Type applies the filter to all resources.-
Import a VPC with the ID vpc-123
# To specify multiple values, separate them with semicolons: --filter="vpc.id=vpc-123;vpc-456" aliterraformer import alicloud -r=vpc --filter="vpc.id=vpc-123" -
Import a VPC and a vSwitch that are both named tf-example
aliterraformer import alicloud -r=vpc,vswitch --filter="vpc.vpc_name=tf-example,vswitch.vswitch_name=tf-example" -
Import a VPC and an ECS instance that both belong to the resource group rg-12345
aliterraformer import alicloud -r=vpc,instance --filter="resource_group_id=rg-12345"
-
-
Extract properties as variables using output-variables
Format:
r1:attr1,attr2;r2:attr1,attr2,attr3.-
Extract vpc_id and vswitch_id from an ECS instance as variables
aliterraformer import alicloud -r=instance --output-variables="instance:vpc_id,vswitch_id"
-
-
Example
This example imports a VPC, vSwitch, and ECS instance with VPC ID vpc-12345 in China (Hangzhou), extracting the vSwitch zone_id as a variable:
-
Create a directory to store the imported templates and state files.
mkdir example && cd example -
Construct the import command.
aliterraformer import alicloud \ --regions=cn-hangzhou \ -r=vpc,vswitch,instance \ --filter="vpc.id=vpc-12345,vswitch.vpc_id=vpc-12345,instance.vpc_id=vpc-12345" \ --output-variables="vswitch:zone_id" \ --path-output=example \ --path-pattern={output} \ --compact-
--path-output: Specifies the import folder. -
--path-pattern: Directory structure for imported templates. Default:{output}/{provider}/{service}/. Alternatives:{output}/{provider}/and{output}/. Using--path-pattern={output}places all templates in a single folder. -
--compact: Consolidates all resources into a singleresources.tffile instead of separate{service}.tffiles.
-
-
After the import, the following files are generated in the example directory:
. ├── outputs.tf ├── provider.tf ├── resources.tf ├── terraform.tfstate └── variables.tfWithout
--path-pattern={output}, the directory structure is:. └── alicloud ├── instance │ ├── provider.tf │ ├── terraform.tfstate │ └── variables.tf ├── vpc │ ├── outputs.tf │ ├── provider.tf │ ├── terraform.tfstate │ ├── variables.tf │ └── vpc.tf └── vswitch ├── outputs.tf ├── provider.tf ├── terraform.tfstate ├── variables.tf └── vswitch.tf -
For Terraform
>=0.13.0, run the following command to update the state file for version compatibility.terraform state replace-provider -auto-approve "registry.terraform.io/-/alicloud" "aliyun/alicloud"
Feedback and suggestions
For questions or suggestions, join the DingTalk group (Group ID: 34240022836) or submit an issue on the Alibaba Cloud Terraform Provider GitHub page.






