TerraformでRDSを構築する作業のメモ

# terraformのインストール

```
$ brew install terraform
==> Downloading https://homebrew.bintray.com/bottles/terraform-0.6.8.el_capitan.
######################################################################## 100.0%
==> Pouring terraform-0.6.8.el_capitan.bottle.tar.gz
🍺  /usr/local/Cellar/terraform/0.6.8: 29 files, 455M
```

# 作業用ディレクトリを作成

```
$ mkdir aws_terraform
$ cd aws_terraform/
$ pwd
/Users/labeneko/Projects/aws_terraform
```

# AWSにアクセスするための設定ファイルを作成
- 適当なIAMユーザを作成し、 とりあえず `AdministratorAccess` ポリシーをアタッチしておきます(本当は必要な権限のみ割り振るのが良い)

```variable.tf
provider "aws" {
  region     = "ap-northeast-1"
  access_key = "******"
  secret_key = "******"
}
```

# VPC の作成
- 自分専用のプライベート空間

```vpc.tf
resource "aws_vpc" "tf_vpc" {
    cidr_block           = "10.0.0.0/16"
    instance_tenancy     = "default"
    enable_dns_support   = true
    enable_dns_hostnames = true
    tags {
        Name = "tf_vpc"
    }
}
```

- 実行されたらどうなるかを確認するために、 `terraform plan` を実行します

```
$ terraform plan
Refreshing Terraform state prior to plan...


The Terraform execution plan has been generated and is shown below.
Resources are shown in alphabetical order for quick scanning. Green resources
will be created (or destroyed and then created if an existing resource
exists), yellow resources are being changed in-place, and red resources
will be destroyed.

Note: You didn't specify an "-out" parameter to save this plan, so when
"apply" is called, Terraform can't guarantee this is what will execute.

+ aws_vpc.tf_vpc
    cidr_block:                "" => "10.0.0.0/16"
    default_network_acl_id:    "" => "<computed>"
    default_security_group_id: "" => "<computed>"
    dhcp_options_id:           "" => "<computed>"
    enable_dns_hostnames:      "" => "1"
    enable_dns_support:        "" => "1"
    instance_tenancy:          "" => "default"
    main_route_table_id:       "" => "<computed>"
    tags.#:                    "" => "1"
    tags.Name:                 "" => "tf_vpc"


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

- うまくできそうです。 `terraform apply` で実行します

```
$ terraform apply
aws_vpc.tf_vpc: Creating...
  cidr_block:                "" => "10.0.0.0/16"
  default_network_acl_id:    "" => "<computed>"
  default_security_group_id: "" => "<computed>"
  dhcp_options_id:           "" => "<computed>"
  enable_dns_hostnames:      "" => "1"
  enable_dns_support:        "" => "1"
  instance_tenancy:          "" => "default"
  main_route_table_id:       "" => "<computed>"
  tags.#:                    "" => "1"
  tags.Name:                 "" => "tf_vpc"
aws_vpc.tf_vpc: Creation complete

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

The state of your infrastructure has been saved to the path
below. This state is required to modify and destroy your
infrastructure, so keep it safe. To inspect the complete state
use the `terraform show` command.

State path: terraform.tfstate
```

- 無事実行できました

# subnetの作成

- vpc_idには `${aws_vpc.tf_vpc.id}` のように書いておくと、いろいろと解決して値を入れてくれるとのこと

```subnet.tf
resource "aws_subnet" "private_db1" {
    vpc_id            = "${aws_vpc.tf_vpc.id}"
    cidr_block        = "10.0.1.0/24"
    availability_zone = "ap-northeast-1a"
    tags {
        Name = "tf_private_db1"
    }
}

resource "aws_subnet" "private_db2" {
    vpc_id            = "${aws_vpc.tf_vpc.id}"
    cidr_block        = "10.0.2.0/24"
    availability_zone = "ap-northeast-1c"
    tags {
        Name = "tf_private_db2"
    }
}
```
- そして `terraform apply` で実行します


# セキュリティグループの作成
- インバウンドトラフィックとアウトバウンドトラフィックを管理します

```security_group.tf
resource "aws_security_group" "db" {
    name        = "db_server"
    description = "It is a security group on db of tf_vpc."
    vpc_id      = "${aws_vpc.tf_vpc.id}"
    tags {
        Name = "tf_db"
    }
}

resource "aws_security_group_rule" "db" {
    type                     = "ingress"
    from_port                = 3306
    to_port                  = 3306
    protocol                 = "tcp"
    cidr_blocks              = ["0.0.0.0/0"]
    security_group_id        = "${aws_security_group.db.id}"
}
```

- 実行します

# DBサブネットグループの設定

- RDS から VPC を利用するために設定するとのこと

```db_subnet_group.tf
resource "aws_db_subnet_group" "main" {
    name        = "tf_dbsubnet"
    description = "It is a DB subnet group on tf_vpc."
    subnet_ids  = ["${aws_subnet.private_db1.id}", "${aws_subnet.private_db2.id}"]
    tags {
        Name = "tf_dbsubnet"
    }
}
```

- 実行します

# DBのデフォルトパラメータを指定
- タイムゾーンとか

```db_parameter_group.tf
resource "aws_db_parameter_group" "default" {
    name = "rds-pg"
    family = "mysql5.7"
    description = "Managed by Terraform"

    parameter {
      name = "time_zone"
      value = "Asia/Tokyo"
    }
}
```

# DBインスタンスの作成

```
resource "aws_db_instance" "db" {
    identifier              = "dbinstance"
    allocated_storage       = 5
    engine                  = "mysql"
    engine_version          = "5.7.11"
    instance_class          = "db.t2.micro"
    storage_type            = "gp2"
    username                = "***"
    password                = "***"
    publicly_accessible     = true
    backup_retention_period = 1
    vpc_security_group_ids  = ["${aws_security_group.db.id}"]
    db_subnet_group_name    = "${aws_db_subnet_group.main.name}"
}
```

- 実行します

# 修正予定
- useridとpasswordを直に書きすぎなので設定ファイルに移動

# 参考
- https://tech.recruit-mp.co.jp/infrastructure/post-10665/