【入門】Terraformプロジェクトのセットアップ

AWSコンソールでぽちぽちではなく、コードでインフラを管理する方法を学びたいと思い、学習を始めました。
今回は実際に Terraform のプロジェクトの作成、公式のチュートリアルにあるEC2インスタンスの作成までをまとめます。

### 準備

- 公式ページ
  - AWS、GCPなど、プロバイダーごとにチュートリアルが用意されてます。

https://learn.hashicorp.com/collections/terraform/aws-get-started

- Terraformの実行環境
  - homebrewなどで入れることが出来ます。
  - 公式の Docker コンテナがあるので、今回はこちらを使います。

https://hub.docker.com/r/hashicorp/terraform/

### プロジェクトの作成

いったんシンプルに試すため、下記構成で作ります。

```
work_dir/
　├ .env
　├ docker-compose.yml
　└ src/
　 　└ main.tf
```

ファイルはそれぞれ下記です。

```.env
// AWS credential info
AWS_ACCESS_KEY_ID =
AWS_SECRET_ACCESS_KEY =
```

```yml:docker-compose.yml
version: "3.8"
services:
  terraform:
    env_file:
      - .env
    image: hashicorp/terraform:light
    volumes:
      - ./src:/app/terraform
    working_dir: /app/terraform
```

```tf:src/main.tf
terraform {
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 3.44.0"
    }
  }
}

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

resource "aws_instance" "example" {
  ami           = "ami-830c94e3"
  instance_type = "t3.micro"

  tags = {
    Name = "ExampleInstance"
  }
}
```

`src/main.tf` のリージョン、インスタンスタイプなどはお好みで。
今回は、`ami-830c94e3`をt3.microサイズのインスタンスで、東京リージョンで立ち上げるように書きました。

### コマンドの実行

プロジェクトを作成、tfファイルを作成後に一度 `init` を実行します。

```sh
docker-compose run --rm terraform init
Creating network "mochimochi-terraform_default" with the default driver
Creating mochimochi-terraform_terraform_run ... done

Initializing the backend...

Initializing provider plugins...

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

`plan` を実行することで、定義した内容を確認できます。

```sh
$ docker-compose run --rm terraform plan
Creating mochimochi-terraform_terraform_run ... done

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-830c94e3"
      + 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                = "t3.micro"
      + ipv6_address_count           = (known after apply)
      + ipv6_addresses               = (known after apply)
      + key_name                     = (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)
      + secondary_private_ips        = (known after apply)
      + security_groups              = (known after apply)
      + source_dest_check            = true
      + subnet_id                    = (known after apply)
      + tags                         = {
          + "Name" = "ExampleInstance"
        }
      + tenancy                      = (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)
          + tags                  = (known after apply)
          + throughput            = (known after apply)
          + volume_id             = (known after apply)
          + volume_size           = (known after apply)
          + volume_type           = (known after apply)
        }

      + enclave_options {
          + enabled = (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)
          + tags                  = (known after apply)
          + throughput            = (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.

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

Note: You didn't specify an "-out" parameter to save this plan, so Terraform
can't guarantee that exactly these actions will be performed if
"terraform apply" is subsequently run.
```

`apply` を実行することで、定義した内容が適用されます。

```sh
$ docker-compose run --rm terraform apply

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: Creation complete after 13s [id=i-056f8b4b8de00beda]

Apply complete! Resources: 1 added, 0 changed, 0 destroyed.
```

completeと表示されましたね、実際にAWSコンソールを見に行って見ると、インスタンスが生成されていると思います。

![apply実行後、インスタンスが生成されたことが確認できる](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/166596/22fa4bb3-031c-f108-a195-7eba546ca13f.png)

Terraformを使って、AMIから無事インスタンスを作ることができました。
他のAWSリソースの場合どうやるのか、また学んで投稿していこうと思います。