使用已转换为模块化的 Terraform,将 AWS 资源导入
首先,得出结论.
只需要一种选择:
可以使用 `terraform import module.[module name].aws_hogehoge [target]` 的方式来完成。
背景
我之前用Terraform来构建和管理AWS资源,感觉很不错,但是当我突然想要使用Terraform创建不常用的资源时,却变得很麻烦,因为需要经历很多尝试和错误。
最开始我还是倾向于在AWS管理控制台上点点鼠标,然后通过了解所需的信息是什么样的,再通过terraform import和复制粘贴来增加资源,这样更加高效。
所以我试了一下这种方法。
失败的例子 de
因为我之前没有创建过SNS主题,所以我尝试从管理控制台创建并使用terraform导入,但以失败告终。
首先创建一个terraform文件。
resource "aws_sns_topic" "alert_mail" {
}
导入
% terraform import aws_sns_topic.alert_mail arn:aws:sns:ap-northeast-1:[account_id]:[sns-name]
Error: resource address "aws_sns_topic.alert_mail" does not exist in the configuration.
Before importing this resource, please create its configuration in the root module. For example:
resource "aws_sns_topic" "alert_mail" {
# (resource arguments)
}
我失败了。为什么呢?
造成失敗的原因及解決对策
这个 Terraform 使用了同一个资源文件来共享 staging 环境和 production 环境,并通过变量进行区分的方法。
% tree .
.
├── production ←production 環境向けの設定
│ ├── main.tf
│ ├── terraform.tfvars
│ └── terraform.tfvars.sample
├── source ←terraform 本体(
│ ├── (諸々省略)
│ ├── variables.tf
│ └── hoge.tf
└── staging ←staging 環境向けの設定
├── main.tf
├── terraform.tfvars
└── terraform.tfvars.sample
生产和暂存环境的主要设置如下,将Terraform本体作为模块进行加载。
module "staging" {
source = "../source"
hogevar = var.hogevar
}
如果以这种方式进行模块化,似乎会迷失 terraform import 应该在何处进行导入。
因此,只要指定模块,就可以进行导入。
% terraform import module.staging.aws_sns_topic.alert_mail arn:aws:sns:ap-northeast-1:[account_id]:[sns-name]
(略)
module.staging.aws_sns_topic.alert_mail: Import prepared!
Prepared aws_sns_topic for 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.
只需从这里运行 terraform show 命令就可以知道设置了什么参数,然后将所需的信息转录到 .tf 文件中,就能轻松地使用 Terraform 进行配置管理。
Chinese paraphrase for “終わりに”:
结束时
这次是关于 Terraform (AWS) 的话题,我们正在获取 AS 番号并积极进行 VPC 同伴活动。(AS 146981)
我们正在积极招聘希望参与从本地基础设施到云基础设施以及 AS 运营等各种领域的工程师。
https://www.green-japan.com/company/2706/job/138717