terraformでEC2インスタンスを作成、更新、削除してみる

Cloud9でterraformを書いてEC2インスタンスを作ったり消したりしてみる。

・EC2インスタンス作成
　AMIとインスタンスタイプだけ指定してインスタンスを作成してみる

・EC2インスタンス更新（その１）
　Nameタグを追加してみる

・EC2インスタンス更新（その２）
　ユーザーデータを追加してみる
　マネジメントコンソールだと停止⇒ユーザデータの表示/変更⇒起動で
　インスタンスを作り直さずに行けそうだが、terraformだと作り直しになるらしい。

・EC2インスタンス終了
　リソースを削除してみる

##EC2インスタンス作成
まずは必須項目（AMIとインスタンスタイプ）だけ指定してインスタンスを作成してみる。

```sh:main.tf作成
vi main.tf

provider "aws" {
  region = "ap-northeast-1"
}

resource "aws_instance" "example" {
    ami           = "ami-06ad9296e6cf1e3cf"
    instance_type = "t2.micro"
}
```

```sh:terraform_init
$ terraform init

Initializing the backend...

Initializing provider plugins...
- Checking for available provider plugins...
- Downloading plugin for provider "aws" (hashicorp/aws) 2.70.0...

The following providers do not have any version constraints in configuration,
so the latest version was installed.

To prevent automatic upgrades to new major versions that may contain breaking
changes, it is recommended to add version = "..." constraints to the
corresponding provider blocks in configuration, with the constraint strings
suggested below.

* provider.aws: version = "~> 2.70"

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.
$ 
```

```sh:terraform_apply
$ terraform apply

An execution plan has been generated and is shown below.
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-06ad9296e6cf1e3cf"
      + 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)
      + get_password_data            = false
      + host_id                      = (known after apply)
      + id                           = (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)
      + network_interface_id         = (known after apply)
      + outpost_arn                  = (known after apply)
      + password_data                = (known after apply)
      + placement_group              = (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)
      + security_groups              = (known after apply)
      + source_dest_check            = true
      + subnet_id                    = (known after apply)
      + tenancy                      = (known after apply)
      + volume_tags                  = (known after apply)
      + vpc_security_group_ids       = (known after apply)

      + ebs_block_device {
          + delete_on_termination = (known after apply)
          + device_name           = (known after apply)
          + encrypted             = (known after apply)
          + iops                  = (known after apply)
          + kms_key_id            = (known after apply)
          + snapshot_id           = (known after apply)
          + volume_id             = (known after apply)
          + volume_size           = (known after apply)
          + volume_type           = (known after apply)
        }

      + ephemeral_block_device {
          + device_name  = (known after apply)
          + no_device    = (known after apply)
          + virtual_name = (known after apply)
        }

      + metadata_options {
          + http_endpoint               = (known after apply)
          + http_put_response_hop_limit = (known after apply)
          + http_tokens                 = (known after apply)
        }

      + network_interface {
          + delete_on_termination = (known after apply)
          + device_index          = (known after apply)
          + network_interface_id  = (known after apply)
        }

      + root_block_device {
          + delete_on_termination = (known after apply)
          + device_name           = (known after apply)
          + encrypted             = (known after apply)
          + iops                  = (known after apply)
          + kms_key_id            = (known after apply)
          + volume_id             = (known after apply)
          + volume_size           = (known after apply)
          + volume_type           = (known after apply)
        }
    }

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

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: Creation complete after 22s [id=i-0999997457adc75d0]

Apply complete! Resources: 1 added, 0 changed, 0 destroyed.
$ 
```
マネジメントコンソールで確認。
![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/651099/6217a6f4-4e91-3c7a-5c25-cd80569d1d97.png)
⇒インスタンスが追加された。

##EC2インスタンス更新（その１）
Nameタグを追加してみる。
main.tfに以下を追加。

```sh:
tags = {
    Name = "created by terraform"
}
```

```sh:terraform_apply
$ terraform apply
aws_instance.example: Refreshing state... [id=i-0999997457adc75d0]

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

Terraform will perform the following actions:

  # aws_instance.example will be updated in-place
  ~ resource "aws_instance" "example" {
        ami                          = "ami-06ad9296e6cf1e3cf"
        arn                          = "arn:aws:ec2:ap-northeast-1:056789090539:instance/i-0999997457adc75d0"
        associate_public_ip_address  = true
        availability_zone            = "ap-northeast-1a"
        cpu_core_count               = 1
        cpu_threads_per_core         = 1
        disable_api_termination      = false
        ebs_optimized                = false
        get_password_data            = false
        hibernation                  = false
        id                           = "i-0999997457adc75d0"
        instance_state               = "running"
        instance_type                = "t2.micro"
        ipv6_address_count           = 0
        ipv6_addresses               = []
        monitoring                   = false
        primary_network_interface_id = "eni-00001c25ed185ca9e"
        private_dns                  = "ip-172-31-39-147.ap-northeast-1.compute.internal"
        private_ip                   = "172.31.39.147"
        public_dns                   = "ec2-18-179-46-244.ap-northeast-1.compute.amazonaws.com"
        public_ip                    = "18.179.46.244"
        security_groups              = [
            "default",
        ]
        source_dest_check            = true
        subnet_id                    = "subnet-979e4bdf"
      ~ tags                         = {
          + "Name" = "created by terraform "
        }
        tenancy                      = "default"
        volume_tags                  = {}
        vpc_security_group_ids       = [
            "sg-e3560994",
        ]

        credit_specification {
            cpu_credits = "standard"
        }

        metadata_options {
            http_endpoint               = "enabled"
            http_put_response_hop_limit = 1
            http_tokens                 = "optional"
        }

        root_block_device {
            delete_on_termination = true
            device_name           = "/dev/xvda"
            encrypted             = false
            iops                  = 100
            volume_id             = "vol-0a3060ad172667412"
            volume_size           = 8
            volume_type           = "gp2"
        }
    }

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

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: Modifying... [id=i-0999997457adc75d0]
aws_instance.example: Modifications complete after 1s [id=i-0999997457adc75d0]

Apply complete! Resources: 0 added, 1 changed, 0 destroyed.
$
```
マネジメントコンソールで確認。
![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/651099/d3372b55-ebbc-d2c8-3af6-550ed8ac87d1.png)
⇒Nameタグが設定された。

##EC2インスタンス更新（その２）
ユーザーデータを追加してみる。
main.tfに以下を追加。

```sh:
user_data = <<EOF
    #!/bin/bash
    yum install -y httpd
    systemctl start httpd.service
    systemctl enable httpd.service
EOF
```

```sh:terraform_apply
 terraform apply
aws_instance.example: Refreshing state... [id=i-0999997457adc75d0]

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

Terraform will perform the following actions:

  # aws_instance.example must be replaced
-/+ resource "aws_instance" "example" {
        ami                          = "ami-06ad9296e6cf1e3cf"
      ~ arn                          = "arn:aws:ec2:ap-northeast-1:056789090539:instance/i-0999997457adc75d0" -> (known after apply)
      ~ associate_public_ip_address  = true -> (known after apply)
      ~ availability_zone            = "ap-northeast-1a" -> (known after apply)
      ~ cpu_core_count               = 1 -> (known after apply)
      ~ cpu_threads_per_core         = 1 -> (known after apply)
      - disable_api_termination      = false -> null
      - ebs_optimized                = false -> null
        get_password_data            = false
      - hibernation                  = false -> null
      + host_id                      = (known after apply)
      ~ id                           = "i-0999997457adc75d0" -> (known after apply)
      ~ instance_state               = "running" -> (known after apply)
        instance_type                = "t2.micro"
      ~ ipv6_address_count           = 0 -> (known after apply)
      ~ ipv6_addresses               = [] -> (known after apply)
      + key_name                     = (known after apply)
      - monitoring                   = false -> null
      + network_interface_id         = (known after apply)
      + outpost_arn                  = (known after apply)
      + password_data                = (known after apply)
      + placement_group              = (known after apply)
      ~ primary_network_interface_id = "eni-00001c25ed185ca9e" -> (known after apply)
      ~ private_dns                  = "ip-172-31-39-147.ap-northeast-1.compute.internal" -> (known after apply)
      ~ private_ip                   = "172.31.39.147" -> (known after apply)
      ~ public_dns                   = "ec2-18-179-46-244.ap-northeast-1.compute.amazonaws.com" -> (known after apply)
      ~ public_ip                    = "18.179.46.244" -> (known after apply)
      ~ security_groups              = [
          - "default",
        ] -> (known after apply)
        source_dest_check            = true
      ~ subnet_id                    = "subnet-979e4bdf" -> (known after apply)
        tags                         = {
            "Name" = "created by terraform "
        }
      ~ tenancy                      = "default" -> (known after apply)
      + user_data                    = "f9024a43d51455cc0ac11736f26b8a7c7779888e" # forces replacement
      ~ volume_tags                  = {} -> (known after apply)
      ~ vpc_security_group_ids       = [
          - "sg-e3560994",
        ] -> (known after apply)

      - credit_specification {
          - cpu_credits = "standard" -> null
        }

      + ebs_block_device {
          + delete_on_termination = (known after apply)
          + device_name           = (known after apply)
          + encrypted             = (known after apply)
          + iops                  = (known after apply)
          + kms_key_id            = (known after apply)
          + snapshot_id           = (known after apply)
          + volume_id             = (known after apply)
          + volume_size           = (known after apply)
          + volume_type           = (known after apply)
        }

      + ephemeral_block_device {
          + device_name  = (known after apply)
          + no_device    = (known after apply)
          + virtual_name = (known after apply)
        }

      ~ metadata_options {
          ~ http_endpoint               = "enabled" -> (known after apply)
          ~ http_put_response_hop_limit = 1 -> (known after apply)
          ~ http_tokens                 = "optional" -> (known after apply)
        }

      + network_interface {
          + delete_on_termination = (known after apply)
          + device_index          = (known after apply)
          + network_interface_id  = (known after apply)
        }

      ~ root_block_device {
          ~ delete_on_termination = true -> (known after apply)
          ~ device_name           = "/dev/xvda" -> (known after apply)
          ~ encrypted             = false -> (known after apply)
          ~ iops                  = 100 -> (known after apply)
          + kms_key_id            = (known after apply)
          ~ volume_id             = "vol-0a3060ad172667412" -> (known after apply)
          ~ volume_size           = 8 -> (known after apply)
          ~ volume_type           = "gp2" -> (known after apply)
        }
    }

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

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: Destroying... [id=i-0999997457adc75d0]
aws_instance.example: Still destroying... [id=i-0999997457adc75d0, 10s elapsed]
aws_instance.example: Still destroying... [id=i-0999997457adc75d0, 20s elapsed]
aws_instance.example: Destruction complete after 30s
aws_instance.example: Creating...
aws_instance.example: Still creating... [10s elapsed]
aws_instance.example: Still creating... [20s elapsed]
aws_instance.example: Creation complete after 21s [id=i-0b62a529fc8347569]

Apply complete! Resources: 1 added, 0 changed, 1 destroyed.
$
```
マネジメントコンソールで確認。
![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/651099/a8275444-fd2c-20a4-bf48-ac5f7ddedaf1.png)
⇒画面キャプチャを取り忘れたが、インスタンス状態は shutting-down ⇒ terminated ⇒ pending ⇒ starting ⇒ running と遷移していった

##EC2インスタンス終了
作成したEC2インスタンスを削除してみる。

```sh:terraform_destroy
$ terraform destroy
aws_instance.example: Refreshing state... [id=i-0b62a529fc8347569]

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.example will be destroyed
  - resource "aws_instance" "example" {
      - ami                          = "ami-06ad9296e6cf1e3cf" -> null
      - arn                          = "arn:aws:ec2:ap-northeast-1:056789090539:instance/i-0b62a529fc8347569" -> null
      - associate_public_ip_address  = true -> null
      - availability_zone            = "ap-northeast-1a" -> null
      - cpu_core_count               = 1 -> null
      - cpu_threads_per_core         = 1 -> null
      - disable_api_termination      = false -> null
      - ebs_optimized                = false -> null
      - get_password_data            = false -> null
      - hibernation                  = false -> null
      - id                           = "i-0b62a529fc8347569" -> null
      - instance_state               = "running" -> null
      - instance_type                = "t2.micro" -> null
      - ipv6_address_count           = 0 -> null
      - ipv6_addresses               = [] -> null
      - monitoring                   = false -> null
      - primary_network_interface_id = "eni-06c4304655b07eb67" -> null
      - private_dns                  = "ip-172-31-33-105.ap-northeast-1.compute.internal" -> null
      - private_ip                   = "172.31.33.105" -> null
      - public_dns                   = "ec2-54-250-94-159.ap-northeast-1.compute.amazonaws.com" -> null
      - public_ip                    = "54.250.94.159" -> null
      - security_groups              = [
          - "default",
        ] -> null
      - source_dest_check            = true -> null
      - subnet_id                    = "subnet-979e4bdf" -> null
      - tags                         = {
          - "Name" = "created by terraform "
        } -> null
      - tenancy                      = "default" -> null
      - user_data                    = "f9024a43d51455cc0ac11736f26b8a7c7779888e" -> null
      - volume_tags                  = {} -> null
      - vpc_security_group_ids       = [
          - "sg-e3560994",
        ] -> null

      - credit_specification {
          - cpu_credits = "standard" -> null
        }

      - metadata_options {
          - http_endpoint               = "enabled" -> null
          - http_put_response_hop_limit = 1 -> null
          - http_tokens                 = "optional" -> null
        }

      - root_block_device {
          - delete_on_termination = true -> null
          - device_name           = "/dev/xvda" -> null
          - encrypted             = false -> null
          - iops                  = 100 -> null
          - volume_id             = "vol-0dc6ebcd3b9ab498e" -> null
          - volume_size           = 8 -> null
          - volume_type           = "gp2" -> null
        }
    }

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-0b62a529fc8347569]
aws_instance.example: Still destroying... [id=i-0b62a529fc8347569, 10s elapsed]
aws_instance.example: Still destroying... [id=i-0b62a529fc8347569, 20s elapsed]
aws_instance.example: Destruction complete after 29s

Destroy complete! Resources: 1 destroyed.
$ 
```
マネジメントコンソールで確認
![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/651099/02eb2315-25dd-6224-421b-07055d0db303.png)
![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/651099/de7598ff-af48-c68a-4322-48b3df86b9b9.png)