2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

作成済みのEC2をterraform管理にする

Posted at

terraform importコマンドを使用すれば、既存のリソースをterraform管理に出来るらしいので挑戦。今回はAWSのEC2でやってみます。

事前準備

EC2を事前に手動で作成しておきます。

そのあとに、インスタンスIDとAMI IDとインスタンスタイプを控えておきます。(terraformでEC2を管理するのに必須なステータス)

image.png

image.png

image.png

インポート前の準備

プロバイダ情報の記載

インポートの為にプロバイダの指定が必要なので、terraformを管理する予定のディレクトリでファイルを作成しプロバイダ情報を記載。今回はAWSで、リージョンは東京を指定。

EC2インスタンス情報の記載

リソースはEC2なので、aws_instanceを使用。
その中に事前に控えておいたAMI IDインスタンスタイプを記載します。

プロバイダとEC2インスタンスの情報を記載したファイルは下記のようになります。
amiとinstance_typeの箇所の記載は自身の環境に合わせて変更します。

main.tf
# プロバイダ情報
provider "aws" {
  region = "ap-northeast-1"
}

# EC2インスタンス情報を記載
resource "aws_instance" "imported" {
  ami = "ami-0f27d081df46f326c"
  instance_type = "t2.micro"
}

import実施

対象ディレクトリでterraform initを実施し、Terraformの準備をします。

# terraform init

インスタンスIDを指定し、importを実施。

terraform import aws_instance.imported i-037fec03a06ff16c7

確認

これでimportは完了です。terraform planを実施し、差分が無いことを確認出来ればOKです。

# 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.

aws_instance.imported: Refreshing state... [id=i-037fec03a06ff16c7]

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

No changes. Infrastructure is up-to-date.

さらに管理されてるか気になるのであれば、terraform destroyを実施します。管理しているEC2が削除対象として出力されるはずです。

# terraform destroy
aws_instance.imported: Refreshing state... [id=i-037fec03a06ff16c7]

An execution plan has been generated and is shown below.
Resource actions are indicated with the following symbols:
  - destroy

Terraform will perform the following actions:

  # aws_instance.imported will be destroyed
  - resource "aws_instance" "imported" {
      - ami                          = "ami-0f27d081df46f326c" -> null
<省略>

終わりに

管理外のリソースをimport出来ると知ったので、実際に試しました。
ちなみにリソースに必要な引数は事前に調べなくても、planを実施すればterraformに記載すべきステータスを教えてくれます。

例えば、amiを指定せずにplanを実施すればamiを指定するようにとエラーメッセージが出ます。

# terraform plan

Error: Missing required argument

  on main.tf line 5, in resource "aws_instance" "imported":
   5: resource "aws_instance" "imported" {

The argument "ami" is required, but no definition was found.
2
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
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?