通过 terraform import 导入
Developer / Terraform / Terraform CLI / Import Infrastructure
- Import existing resources overview | https://developer.hashicorp.com/terraform/cli/import
- Import existing resources | https://developer.hashicorp.com/terraform/cli/import/usage
- terraform import command reference | https://developer.hashicorp.com/terraform/cli/commands/import
该方式仅能将现有 resource 导入到 state 文件中,而不能直接转化为具体的 resource {} 配置。
我们需要导入并修改配置,所以我们暂时不研究该方式。
通过 import {} 导入
Import Terraform configuration | https://developer.hashicorp.com/terraform/tutorials/state/state-import | 该文档介绍通过 import {} 将 Infrastructure 配置导出到配置文件的方法。通过该方法,我们能够将已有的 Infrastructure 配置导入到本地的配置文件。
Developer / Terraform / Configuration Language / Import
- Import | https://developer.hashicorp.com/terraform/language/import | 针对 import {} 指令,参考文档以获取更多使用方法。
- Generating configuration | https://developer.hashicorp.com/terraform/language/import/generating-configuration |
步骤大致如下:
- Identify the existing infrastructure you will import.
- Define an import block for the resources.
- 其中,import {} 包含 id / to 两个字段
- 还需要定义 resource {} 部分,其要与 import {} to 部分相对应。
- 定义方法:
- 或,按需自行编写 resource {} 部分。
- 或,通过 terraform plan -generate-config-out=generated.tf 直接生成。
- 其生成的内容均为默认值,需要进行处理,否则执行 terraform apply 命令会导致应用被修改。
- 相关字段:
- 关键字段:需要参考 Provider 手册,其 resource 中 Schema / Required 指出需要定义的字段。
- 其他字段:根据环境信息,补充其他字段,方式 terraform apply 时意外修改当前运行时配置。
- 定义方法:
- Run terraform plan to review the import plan and optionally generate configuration for the resources.
- 需要留意变更内容,重点检查是否会修改当前正在运行的服务。
- Prune generated configuration to only the required arguments.
- 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