Managing existing resources

更新时间:
复制 MD 格式

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.

image

Scenarios

Resource import applies to these common scenarios:

  1. Manage existing resources: Transition resources managed by other tools, such as the console, API, or command-line interface (CLI), to Terraform management.

  2. 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.

  3. Refactor code: Split a monolithic configuration file into smaller files to reduce management complexity as your resource count grows.

  4. Quickly deploy resources: Replicate and deploy an existing resource architecture to a different region or account.

  5. 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:

  1. The import command: Imports a single resource using the native Terraform command terraform import.

  2. The import block: Imports one or more resources by writing a Terraform import block and running terraform plan and terraform apply.

  3. 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

  • Simple and direct. Runs a native Terraform command.

  • Automatically generates a state file.

  • Requires you to manually retrieve the resource ID, which can be error-prone.

  • Inefficient for multiple resources because it only supports importing one resource at a time.

  • Requires you to write the resource code manually.

Manage existing resources

Resolve resource drift

Refactor code

The import block

  • Simple to use. Runs native Terraform commands.

  • Supports batch import of multiple resources.

  • Allows you to write code for complex import logic.

  • Requires writing import code, which has a learning curve.

  • Cannot generate dependencies between multiple resources.

  • Can have a high configuration cost for batch imports.

Manage existing resources

Resolve resource drift

Refactor code

Quickly deploy resources

Terraformer

  • Automatically filters and selects the resource collection to import.

  • Automatically generates Terraform resource code.

  • Automatically generates dependencies between resources.

  • Requires you to download and install Terraformer.

  • Is not a native Terraform command and has a learning and configuration cost.

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:

  • 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_group is the security group ID. The resource ID for alicloud_security_group_rule follows a specific format.

    image.png

  • 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:

  1. 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"{ }
  2. The ID of an alicloud_oss_bucket resource is the bucket name.

  3. Initialize the runtime environment.

    terraform init
  4. Run the import command.

    # Replace this with your bucket name
    terraform import alicloud_oss_bucket.default oss-bucket-import

    The 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.
    
  5. After importing, resource properties are not added to your template automatically. Run terraform show to 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:

    Note

    Requires Terraform v1.5.0 or later.

  • 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:

  1. Automatically generates configuration. Import to an existing resource address, or use -generate-config-out to auto-generate the configuration file.

  2. Batch imports. Use for_each in an `import` block to import multiple resources. Resources with similar attributes can share a resource address, differentiated by index.

Note

These two features cannot be combined. The Terraform CLI does not support auto-generating configurations for resources that use for_each.image.png

Example

The following example imports an OSS bucket using an import block:

  1. 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"
    }
  2. Initialize the runtime environment.

    terraform init
  3. Run terraform plan to preview the import. Use -generate-config-out to auto-generate the template.

    terraform plan -generate-config-out=generated.tf

    The 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.
  4. After confirming the plan, run terraform apply to execute the import.

    terraform apply 

    Enter 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:

  1. Open-source Terraformer: The original version, supporting resource import from multiple cloud providers.

  2. 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
  1. 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
  2. Dependencies

    1. Grant the current account read-only permissions for the relevant resources.

    2. Install Terraform

      Note

      You can skip this step if you run the command in Cloud Shell.

      For more information, see Install and configure Terraform.

    3. 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.

    4. 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.

  1. help: Display details about a command.

    image.png

  2. version: Display the current version number.

    image.png

  3. import: Import resources for a specified provider.

    image.png

  4. plan: Preview resources to be imported for a specified provider.

Example

The following example imports all Alibaba Cloud VPCs in the China (Hangzhou) region.

  1. Create a directory to store the imported templates and state files.

    mkdir example && cd example
  2. 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.

  3. 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 --compact parameter, which outputs all resources to resources.tf.

    └── cn-hangzhou
        ├── outputs.tf
        ├── provider.tf
        ├── terraform.tfstate
        ├── variables.tf
        ├── vpc.tf
        └── vswitch.tf
    
    2 directories, 6 files
  4. 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
  1. 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.zip

    Linux

    # 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.zip

    Windows

    # 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.zip

    For example, on macOS, decompress the file after downloading:

    unzip aliterraformer_darwin_amd64.zip
    chmod +x aliterraformer
    sudo mv aliterraformer /usr/local/bin/aliterraformer
  2. Dependencies

    Like open-source Terraformer, you need the terraform and terraform-provider-alicloud binaries and configured access credentials.

    1. Grant read-only permissions for the relevant resources to the Resource Access Management (RAM) account.

    2. Install Terraform

      For more information, see Install and configure Terraform. You can skip this step if you run the command in Cloud Shell.

    3. 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
    4. 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.

  1. help: View details about the supported commands.

    aliterraformer help

    image.png

  2. version: View the current Terraformer version.

    aliterraformer version
  3. products: List products supported for import in the current version.

    aliterraformer products

    image.png

  4. resources: List importable resource types for a product. Use -p to specify the product.

    aliterraformer resources -p <productName>

    image.png

    image.png

  5. import: Import resources. Specify alicloud for Alibaba Cloud. Run the following command to view available parameters:

    aliterraformer import alicloud -h

    image.png

    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:

  1. Create a directory to store the imported templates and state files.

    mkdir example && cd example
  2. 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 single resources.tf file instead of separate {service}.tf files.

  3. After the import, the following files are generated in the example directory:

    .
    ├── outputs.tf
    ├── provider.tf
    ├── resources.tf
    ├── terraform.tfstate
    └── variables.tf

    Without --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
  4. 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.

image