TerraformでEC2インスタンス起動


## 環境準備
### VS Codeプラグインインストール
プラグイン名: HashiCorp Terraform
機能: 下記
- シンタックスハイライト
- コード補完
![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/59015/a90f00f2-5e00-c6f7-7ac2-5d65919b2752.png)

### デフォルトターミナルの変更(Windowsのみ)

```settings.json
{
# 中略
  "terminal.integrated.shell.windows": "C:/Program Files/Git/bin/bash.exe",
# 中略  
}
```
VS Codeで「ファイル」->「ユーザー設定」->「設定」
![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/59015/c7eeb460-f735-d247-4024-edfff4ba944f.png)

検索エリアに「terminal integrated shell windows」と入力する
![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/59015/06ca88ed-a201-b6e9-ce62-1373aba0f92f.png)
画像のプルダウンからGit Bashを選択する

## デフォルトVPCにEC2を起動する
### 1. main.tfファイルの作成
```main.tf
provider "aws" {
    profile = "terraform"
    region = "ap-northeast-1"
}

resource "aws_instance" "hello-world" {
    ami = "ami-0f9fe1d9214628296"
    instance_type = "t2.micro"
}
```
amiに指定するものは下記画像のAMI IDに記載のあるもの
![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/59015/a734b2c8-b8a1-2198-234a-c4011c801b0a.png)

### 2. terraformの初期化を行う
ターミナルで以下を実行する
```
terraform init
```
![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/59015/b188c8ce-337a-cf78-169b-97f5fe0d4219.png)

### 3. EC2を起動する
ターミナルで以下を実行する
```
terraform apply
```
![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/59015/ebc15da2-032e-406f-aee4-bbd019d2e4d9.png)
「yes」と入力してエンター
![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/59015/eddca2a1-b3b0-b533-132c-ecd7b2fef379.png)
下記画像の通りEC2インスタンスが起動している
![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/59015/8107a6a6-264b-f497-361a-b35f00b6a526.png)

## tfstateファイル
terraform applyを実行すると「terraform.tfstate」というファイルが作成される
これはterraformを使って構築した「クラウドの状態情報」
```
{
  "version": 4,
  "terraform_version": "1.8.3",
  "serial": 1,
  "lineage": "d144699d-5068-649c-ff20-0008839ab20b",
  "outputs": {},
  "resources": [
    {
      "mode": "managed",
      "type": "aws_instance",
      "name": "hello-world",
      "provider": "provider[\"registry.terraform.io/hashicorp/aws\"]",
      "instances": [
        {
          "schema_version": 1,
          "attributes": {
            "ami": "ami-0f9fe1d9214628296",
            "arn": "arn:aws:ec2:ap-northeast-1:851483725168:instance/i-0be20e10e79ca72e5",
            "associate_public_ip_address": true,
            "availability_zone": "ap-northeast-1c",
            "capacity_reservation_specification": [
              {
                "capacity_reservation_preference": "open",
                "capacity_reservation_target": []
              }
            ],
            "cpu_core_count": 1,
            "cpu_options": [
              {
                "amd_sev_snp": "",
                "core_count": 1,
                "threads_per_core": 1
              }
            ],
            "cpu_threads_per_core": 1,
            "credit_specification": [
              {
                "cpu_credits": "standard"
              }
            ],
            "disable_api_stop": false,
            "disable_api_termination": false,
            "ebs_block_device": [],
            "ebs_optimized": false,
            "enclave_options": [
              {
                "enabled": false
              }
            ],
            "ephemeral_block_device": [],
            "get_password_data": false,
            "hibernation": false,
            "host_id": "",
            "host_resource_group_arn": null,
            "iam_instance_profile": "",
            "id": "i-0be20e10e79ca72e5",
            "instance_initiated_shutdown_behavior": "stop",
            "instance_lifecycle": "",
            "instance_market_options": [],
            "instance_state": "running",
            "instance_type": "t2.micro",
            "ipv6_address_count": 0,
            "ipv6_addresses": [],
            "key_name": "",
            "launch_template": [],
            "maintenance_options": [
              {
                "auto_recovery": "default"
              }
            ],
            "metadata_options": [
              {
                "http_endpoint": "enabled",
                "http_protocol_ipv6": "disabled",
                "http_put_response_hop_limit": 2,
                "http_tokens": "required",
                "instance_metadata_tags": "disabled"
              }
            ],
            "monitoring": false,
            "network_interface": [],
            "outpost_arn": "",
            "password_data": "",
            "placement_group": "",
            "placement_partition_number": 0,
            "primary_network_interface_id": "eni-00672203b59619f45",
            "private_dns": "ip-172-31-5-54.ap-northeast-1.compute.internal",
            "private_dns_name_options": [
              {
                "enable_resource_name_dns_a_record": false,
                "enable_resource_name_dns_aaaa_record": false,
                "hostname_type": "ip-name"
              }
            ],
            "private_ip": "172.31.5.54",
            "public_dns": "ec2-35-78-87-18.ap-northeast-1.compute.amazonaws.com",
            "public_ip": "35.78.87.18",
            "root_block_device": [
              {
                "delete_on_termination": true,
                "device_name": "/dev/xvda",
                "encrypted": false,
                "iops": 3000,
                "kms_key_id": "",
                "tags": {},
                "tags_all": {},
                "throughput": 125,
                "volume_id": "vol-0904cf56740c825e9",
                "volume_size": 8,
                "volume_type": "gp3"
              }
            ],
            "secondary_private_ips": [],
            "security_groups": [
              "default"
            ],
            "source_dest_check": true,
            "spot_instance_request_id": "",
            "subnet_id": "subnet-6780513c",
            "tags": null,
            "tags_all": {},
            "tenancy": "default",
            "timeouts": null,
            "user_data": null,
            "user_data_base64": null,
            "user_data_replace_on_change": false,
            "volume_tags": null,
            "vpc_security_group_ids": [
              "sg-ab914fd2"
            ]
          },
          "sensitive_attributes": [],
          "private": "eyJlMmJmYjczMC1lY2FhLTExZTYtOGY4OC0zNDM2M2JjN2M0YzAiOnsiY3JlYXRlIjo2MDAwMDAwMDAwMDAsImRlbGV0ZSI6MTIwMDAwMDAwMDAwMCwicmVhZCI6OTAwMDAwMDAwMDAwLCJ1cGRhdGUiOjYwMDAwMDAwMDAwMH0sInNjaGVtYV92ZXJzaW9uIjoiMSJ9"
        }
      ]
    }
  ],
  "check_results": null
}
```
terraform.tfstateファイルの中に`"id": "i-0be20e10e79ca72e5",`という箇所があり、EC2インスタンスのIDです。
AWS Console上のEC2インスタンスのIDと一致しているか確認する
![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/59015/44e1fdce-689f-7471-c30c-8b400ebd98b0.png)

## EC2にタグを追加
main.tfにtagsを追加する
```
provider "aws" {
    profile = "terraform"
    region = "ap-northeast-1"
}

resource "aws_instance" "hello-world" {
    ami = "ami-0f9fe1d9214628296"
    instance_type = "t2.micro"

    tags = {
      Name = "HelloWorld"
    }
}
```
`terraform aplly`を実行する
![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/59015/e181ea6a-6528-aef0-9b69-ff409d6a2617.png)
`Enter a value:`に`yes`と入力する
![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/59015/d6891348-1a8c-852d-c170-e33c5659d33d.png)


## EC2にNginxをインストール
main.tfに`user_data`部分を追記する

```main.tf
provider "aws" {
    profile = "terraform"
    region = "ap-northeast-1"
}

resource "aws_instance" "hello-world" {
    ami = "ami-0f9fe1d9214628296"
    instance_type = "t2.micro"

    tags = {
      Name = "HelloWorld"
    }

    user_data = <<EOF
#!/bin/bash
amazon-linux-extras install -y nginx1.12
systemctl start nginx
EOF
}
```
`terraform apply`を実行する

## EC2削除
ターミナル上で下記コマンドを実行する
```
terraform destroy
```
`Enter a value:`に`yes`と入力する