「Terraform」- 将资源转化为配置 | Import Existing Resources

通过 terraform import 导入

Developer / Terraform / Terraform CLI / Import Infrastructure

该方式仅能将现有 resource 导入到 state 文件中,而不能直接转化为具体的 resource {} 配置。

我们需要导入并修改配置,所以我们暂时不研究该方式。

通过 import {} 导入

Import Terraform configuration | https://developer.hashicorp.com/terraform/tutorials/state/state-import | 该文档介绍通过 import {} 将 Infrastructure 配置导出到配置文件的方法。通过该方法,我们能够将已有的 Infrastructure 配置导入到本地的配置文件。

Developer / Terraform / Configuration Language / Import

步骤大致如下:

  1. Identify the existing infrastructure you will import.
  2. Define an import block for the resources.
    1. 其中,import {} 包含 id / to 两个字段
    2. 还需要定义 resource {} 部分,其要与 import {} to 部分相对应。
      1. 定义方法:
        1. 或,按需自行编写 resource {} 部分。
        2. 或,通过 terraform plan -generate-config-out=generated.tf 直接生成。
          1. 其生成的内容均为默认值,需要进行处理,否则执行 terraform apply 命令会导致应用被修改。
      2. 相关字段:
        1. 关键字段:需要参考 Provider 手册,其 resource 中 Schema / Required 指出需要定义的字段。
        2. 其他字段:根据环境信息,补充其他字段,方式 terraform apply 时意外修改当前运行时配置。
  3. Run terraform plan to review the import plan and optionally generate configuration for the resources.
    1. 需要留意变更内容,重点检查是否会修改当前正在运行的服务。
  4. Prune generated configuration to only the required arguments.
  5. Apply the configuration to bring the resource into your Terraform state file.

在 Import 的同时,terraform 能够完成更新。https://developer.hashicorp.com/terraform/tutorials/state/state-import#import-and-update-the-resource

在文件中,定义资源,并在其他资源中引用该资源。https://developer.hashicorp.com/terraform/tutorials/state/state-import#create-image-resource

通过 Terraformer 工具

无论是 terraform import 还是 import {} 都无法直接输出 Terraform 配置。

Terraformer | CLI tool to generate terraform files from existing infrastructure (reverse Terraform). Infrastructure to Code

https://github.com/GoogleCloudPlatform/terraformer