在Terrafomer中导入现有资源的步骤

最近我经常使用 Terraformer 来导入 AWS 资源,并在其中遇到了一些困难,因此我总结了这个过程的步骤。

logo-hashicorp-3f10732f.svg.png

使用terraformer导入

使用Terraformer获取所需的资源。

$ terraformer import aws --resources=hoge --profile=fuga --path-pattern ./

2. 将state mv中的资源名修改为更易于管理的名称。

由于Terraformer生成的资源名称有时会由于与现有资源的ID混淆而变得难以理解,因此可以通过使用”state mv”命令进行更改。该命令将应用于所有资源(可能会很麻烦)。

$ terraform state mv aws_s3_bucket.tfer--abcdefghijklmn aws_s3_bucket.fuga

3. 根据需要进行模块化处理

将现有的资源转化为模块,以便更容易管理。
或者,如果已经有模块存在,也可以使用它来重新编写资源。

4. 更换供应商。

当我在步骤3将代码重新写入模块并执行计划后,遇到了以下错误。

$ terraform plan
Refreshing Terraform state in-memory prior to plan...
The refreshed state will be used to calculate this plan, but will not be
persisted to local or remote state storage.


Error: Provider configuration not present

To work with aws_s3_bucket.hoge its original provider
configuration at provider["registry.terraform.io/-/aws"] is required, but it
has been removed. This occurs when a provider configuration is removed while
objects created by that provider still exist in the state. Re-add the provider
configuration to destroy aws_s3_bucket.hoge, after which you
can remove the provider configuration again.

看起来在terraformer导入时,它好像会将旧格式的registry.terraform.io/-/aws作为提供者导入?
因此,需要将其更改为在terraform v0.13及更高版本中使用的新提供者格式registry.terraform.io/hashicorp/aws。

$ terraform state replace-provider 'registry.terraform.io/-/aws' 'registry.terraform.io/hashicorp/aws'

5. 通过状态mv将资源从一个模块转换成另一个模块。

只要将资源(resource)改为模块(module),Terraform就无法检测到差异,因此它尝试进行销毁和重新添加操作,所以需要通过状态迁移(state mv)来关联资源和模块。

$ terraform state mv aws_acm_certificate.hoge module.acm_hoge.aws_acm_certificate.acm

请确认通过 terraform plan 命令没有产生任何差异。

$ terraform plan
...
...
Plan: 0 to add, 0 to change, 0 to destroy.

------------------------------------------------------------------------

Note: You didn't specify an "-out" parameter to save this plan, so Terraform
can't guarantee that exactly these actions will be performed if
"terraform apply" is subsequently run.

7. 将后端更改为S3等。 S3 .)

默认情况下,Terraformer将backend设置为本地,为了让任何人都能进行修改,需要将其更改为S3等。

terraform {
  backend "s3" {
    bucket                  = "hoge-backend"
    key                     = "tfstate.json"
    region                  = "ap-northeast-1"
  }
}
$ terraform init --reconfigure 

隨便聊聊

最开始,我困扰于无法理解步骤4中的错误。
最终在以下Stack Overflow页面上参考解决方法:
https://stackoverflow.com/questions/63590836/switch-terraform-0-12-6-to-0-13-0-gives-me-providerregistry-terraform-io-nul

在使用terraformer导入时,每次都需要手动移动resource真的很麻烦。
希望能事先给出一个前缀,取个好听的名字,但严格来说可能很困难呢,我觉得。
导入时需要一些技巧和力量呢,是的。

广告
将在 10 秒后关闭
bannerAds