LoginSignup
1
1

More than 1 year has passed since last update.

module 化した Terraform に AWS リソースを import する

Posted at

先に結論

terraform import module.[module name].aws_hogehoge [target] のようにすればいい。

背景

AWS リソースを Terraform でいい感じに構築して構成管理していたが、あまり扱わないリソースをいきなり Terraform で作ろうと思うと Try&Error が多くなったりしてめんどくさい。
最初はやっぱ AWS 管理コンソールからポチポチしてしまって、必要な情報がどういうものになるのか把握したうえで terraform import → コピペでリソースを増やすほうが効率的。
というわけでやってみた。

失敗例

SNS topic 作ったことなかったし、管理コンソールから作成→ terraform import してみたが失敗。

まずは terraform file を作って

sns.tf
resource "aws_sns_topic" "alert_mail" {

}

import

% 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 環境向けに同じ resource file を共有し、それぞれ変数で作り分ける手法を取っていた。

こんな感じ
% 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

production / staging それぞれの main に↓のように設定して module として Terraform 本体を読み込むようにしていた。

main.tf
module "staging" {
  source = "../source"

  hogevar = var.hogevar
}

このように module 化されている場合、terraform import はどこに import すべきなのか見失うらしい。
なので、module を指定してあげれば 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 で構成管理することができる。

終わりに

今回は Terraform (AWS) ネタでしたが、ねこじゃらしは AS 番号を取得し、ピアリング活動も積極的に行っています。(AS 146981)
オンプレからクラウドインフラにとどまらず AS 運用まで多くのことに携わりたいエンジニアを積極的に募集しています。
https://www.green-japan.com/company/2706/job/138717

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1