TerraformでEC2を作成する

# 概要  
WindowsにTerraformをインストールして使ってみる。

# Terraformをダウンロード  
以下のサイトからTerraformの実行ファイルをダウンロードする。　　
※今回はWindowsにダウンロードするのでWindows版を選択
https://developer.hashicorp.com/terraform/downloads  
![WS000000.JPG](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/2844260/40edcf51-76f3-f046-4f7c-54ec4740c923.jpeg)

ダウンロードしたZipファイルを解凍すると「terraform.exe」というファイルが出てくるので、適当な場所に保存する。  
私はとりあえず「C:\Users\xxx\terraform」配下に保存。
※Pathを通してあげるといい

# 確認
これで準備は完了したので、`terraform -v`と打ってみてコマンドが使えるか確認する。
こんな感じでバージョンが表示されればOK。
```
C:\Users\xxx\terraform>terraform -v
Terraform v1.5.2
on windows_amd64
+ provider registry.terraform.io/hashicorp/aws v5.7.0
```

# terraformでEC2を作成してみる
> 前提：AWS CLIはインストール済み、アクセスキー等の設定も終わっている状態

以下の内容でmain.tfというファイルを作成。
`.tf`の拡張子であればファイル名は何でもOK。
```terraform:main.tf
provider "aws" {
  region = "ap-northeast-1"
}

resource "aws_instance" "example" {
    ami = "ami-0d3bbfd074edd7acb"
    instance_type = "t2.micro"
    tags = {
      Name = "example"
    }
}
```
ファイルが作成できたら、`terraform init`コマンドを打つ。
このコマンドでリソース作成に必要なバイナリファイルをダウンロードする。
`Terraform has been successfully initialized!`と表示されれば成功。
```
C:\Users\xxx\terraform>terraform init

Initializing the backend...

Initializing provider plugins...
- Reusing previous version of hashicorp/aws from the dependency lock file
- Using previously-installed hashicorp/aws v5.7.0

Terraform has been successfully initialized!

You may now begin working with Terraform. Try running "terraform plan" to see
any changes that are required for your infrastructure. All Terraform commands
should now work.

If you ever set or change modules or backend configuration for Terraform,
rerun this command to reinitialize your working directory. If you forget, other
commands will detect it and remind you to do so if necessary.
```
次に`terraform plan`コマンドで実行計画を確認。
```
C:\Users\xxx\terraform>terraform plan

Terraform used the selected providers to generate the following execution plan. Resource actions are indicated with the following symbols:
  + create

Terraform will perform the following actions:

  # aws_instance.example will be created
  + resource "aws_instance" "example" {
      + ami                                  = "ami-0d3bbfd074edd7acb"
      + arn                                  = (known after apply)
      + associate_public_ip_address          = (known after apply)
      + availability_zone                    = (known after apply)
      + cpu_core_count                       = (known after apply)
      + cpu_threads_per_core                 = (known after apply)
      + disable_api_stop                     = (known after apply)
      + disable_api_termination              = (known after apply)
      + ebs_optimized                        = (known after apply)
      + get_password_data                    = false
      + host_id                              = (known after apply)
      + host_resource_group_arn              = (known after apply)
      + iam_instance_profile                 = (known after apply)
      + id                                   = (known after apply)
      + instance_initiated_shutdown_behavior = (known after apply)
      + instance_lifecycle                   = (known after apply)
      + instance_state                       = (known after apply)
      + instance_type                        = "t2.micro"
      + ipv6_address_count                   = (known after apply)
      + ipv6_addresses                       = (known after apply)
      + key_name                             = (known after apply)
      + monitoring                           = (known after apply)
      + outpost_arn                          = (known after apply)
      + password_data                        = (known after apply)
      + placement_group                      = (known after apply)
      + placement_partition_number           = (known after apply)
      + primary_network_interface_id         = (known after apply)
      + private_dns                          = (known after apply)
      + private_ip                           = (known after apply)
      + public_dns                           = (known after apply)
      + public_ip                            = (known after apply)
      + secondary_private_ips                = (known after apply)
      + security_groups                      = (known after apply)
      + source_dest_check                    = true
      + spot_instance_request_id             = (known after apply)
      + subnet_id                            = (known after apply)
      + tags                                 = {
          + "name" = "example"
        }
      + tags_all                             = {
          + "Name" = "example"
        }
      + tenancy                              = (known after apply)
      + user_data                            = (known after apply)
      + user_data_base64                     = (known after apply)
      + user_data_replace_on_change          = false
      + vpc_security_group_ids               = (known after apply)
    }

Plan: 1 to add, 0 to change, 0 to destroy.

───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────

Note: You didn't use the -out option to save this plan, so Terraform can't guarantee to take exactly these actions if you run "terraform apply" now.
```

これで想定通りにリソースが作成されることを確認出来たら、ついにapply！
`terraform apply`コマンドを実行。
```
C:\Users\xxx\terraform>terraform apply

Terraform used the selected providers to generate the following execution plan. Resource actions are indicated with the following symbols:
  + create

Terraform will perform the following actions:

  # aws_instance.example will be created

~中略~

Do you want to perform these actions?
  Terraform will perform the actions described above.
  Only 'yes' will be accepted to approve.

Enter a value: yes

aws_instance.example: Creating...
aws_instance.example: Still creating... [10s elapsed]
aws_instance.example: Still creating... [20s elapsed]
aws_instance.example: Still creating... [30s elapsed]
aws_instance.example: Creation complete after 32s [id=i-0c783fb471303f473]

Apply complete! Resources: 1 added, 0 changed, 0 destroyed.
```
途中`Enter a value:`と聞かれるのでPlan内容に問題がなければ`yes`を入力。
`Apply complete!`と表示されればOK。

> この時`InvalidAMIID.NotFound`エラーが発生したら以下を参照
> [「terraform apply」実行時の「invalidamiid.notfound」エラー](https://qiita.com/xiaochun0001/items/bec8e082c20e1b5a39b2)

コンソールでも確認。
ちゃんと作成されていた。
![WS000004.JPG](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/2844260/2f7ded01-c215-0e11-2459-31e198d0a443.jpeg)

# 作成したリソースを削除
次はリソースを削除する。
`terraform destroy`コマンドを打つ。
```
C:\Users\xxx\terraform>terraform destroy
aws_instance.example: Refreshing state... [id=i-0c783fb471303f473]

Terraform used the selected providers to generate the following execution plan. Resource actions are indicated with the following symbols:
  - destroy

Terraform will perform the following actions:

  # aws_instance.example will be destroyed

~中略~

Plan: 0 to add, 0 to change, 1 to destroy.

Do you really want to destroy all resources?
  Terraform will destroy all your managed infrastructure, as shown above.
  There is no undo. Only 'yes' will be accepted to confirm.

  Enter a value: yes

aws_instance.example: Destroying... [id=i-0c783fb471303f473]
aws_instance.example: Still destroying... [id=i-0c783fb471303f473, 10s elapsed]
aws_instance.example: Still destroying... [id=i-0c783fb471303f473, 20s elapsed]
aws_instance.example: Destruction complete after 30s

Destroy complete! Resources: 1 destroyed.
```
削除の時も`Enter a value:`と聞かれるのでPlan内容に問題がなければ`yes`を入力。
`Destroy complete!`と表示されればOK。

コンソールからも確認。
ちゃんと削除されていた。
![WS000005.JPG](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/2844260/92297b52-5c2a-dd19-cabd-f2ee79dcd038.jpeg)