TerraformでAWS VPCを作成する

TerraformでAWS VPCを作成するコード

## 実行環境
- Windows 10 Home (1919)
- Git Bash (git version 2.25.1.windows.1)
- AWS CLI (aws-cli/2.0.3 Python/3.7.5 Windows/10 botocore/2.0.0dev7)
- Terraform (v0.12.26)

## 作成する構成

まっさらな環境にVPCを1つ作成

![20200623.PNG](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/660929/44f3c342-a8b0-f543-7378-309fdf02600d.png)


## main.tf

``` main.tf
provider "aws" {
  profile = "prj01-profile"
  region = "us-west-2"
}

resource "aws_vpc" "prj01VPC" {
  cidr_block = "10.10.0.0/16"
  instance_tenancy = "default"
  tags = {
    Name = "prj01VPC"
    CostGroup = "prj01"
  }
}
```

公式サイトのマニュアルはこちら
[AWS: aws_vpc - Terraform by HashiCorp](https://www.terraform.io/docs/providers/aws/r/vpc.html)


## 実行

### 実行前の状態確認

```
$ aws ec2 describe-vpcs  --region=us-west-2
{
    "Vpcs": []
}
```
VPCは1つも存在していないことを確認。

#### 前提

```
$ aws configure list --profile prj01-profile
      Name                    Value             Type    Location
      ----                    -----             ----    --------
   profile            prj01-profile           manual    --profile
access_key     ****************FCES shared-credentials-file
secret_key     ****************4Idw shared-credentials-file
    region                us-west-2      config-file    ~/.aws/config
```

前提としてaws cliのprofileは作成済み。

#### まずinit

```
$ ../terraform.exe init

Initializing the backend...

Initializing provider plugins...
- Checking for available provider plugins...
- Downloading plugin for provider "aws" (hashicorp/aws) 2.67.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.67"

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

```
$ ../terraform.exe plan
Refreshing Terraform state in-memory prior to plan...
The refreshed state will be used to calculate this plan, but will not be
persisted to local or remote state storage.


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

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_vpc.prj01VPC will be created
  + resource "aws_vpc" "prj01VPC" {
      + arn                              = (known after apply)
      + assign_generated_ipv6_cidr_block = false
      + cidr_block                       = "10.10.0.0/16"
      + default_network_acl_id           = (known after apply)
      + default_route_table_id           = (known after apply)
      + default_security_group_id        = (known after apply)
      + dhcp_options_id                  = (known after apply)
      + enable_classiclink               = (known after apply)
      + enable_classiclink_dns_support   = (known after apply)
      + enable_dns_hostnames             = (known after apply)
      + enable_dns_support               = true
      + id                               = (known after apply)
      + instance_tenancy                 = "default"
      + ipv6_association_id              = (known after apply)
      + ipv6_cidr_block                  = (known after apply)
      + main_route_table_id              = (known after apply)
      + owner_id                         = (known after apply)
      + tags                             = {
          + "CostGroup" = "prj01"
          + "Name"      = "prj01VPC"
        }
    }

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.

```

確認ポイント
- 今回は新規作成なので、全て「+」になっていること
- changeとdestroyが「0」になっていること
- その他エラーや警告が発生していないこと

#### 確認できたのでapply

```
$ ../terraform.exe 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_vpc.prj01VPC will be created
  + resource "aws_vpc" "prj01VPC" {
      + arn                              = (known after apply)
      + assign_generated_ipv6_cidr_block = false
      + cidr_block                       = "10.10.0.0/16"
      + default_network_acl_id           = (known after apply)
      + default_route_table_id           = (known after apply)
      + default_security_group_id        = (known after apply)
      + dhcp_options_id                  = (known after apply)
      + enable_classiclink               = (known after apply)
      + enable_classiclink_dns_support   = (known after apply)
      + enable_dns_hostnames             = (known after apply)
      + enable_dns_support               = true
      + id                               = (known after apply)
      + instance_tenancy                 = "default"
      + ipv6_association_id              = (known after apply)
      + ipv6_cidr_block                  = (known after apply)
      + main_route_table_id              = (known after apply)
      + owner_id                         = (known after apply)
      + tags                             = {
          + "CostGroup" = "prj01"
          + "Name"      = "prj01VPC"
        }
    }

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_vpc.prj01VPC: Creating...
aws_vpc.prj01VPC: Still creating... [10s elapsed]
aws_vpc.prj01VPC: Creation complete after 13s [id=vpc-085c4a097408d438d]

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

確認ポイント
- Apply complete!と表示されること
- added, changed, destroyedが想定通りであること(今回は1,0,0であること)

#### 実行後の確認

```
$ aws ec2 describe-vpcs  --region=us-west-2
{
    "Vpcs": [
        {
            "CidrBlock": "10.10.0.0/16",
            "DhcpOptionsId": "dopt-0ebee8b328487036e",
            "State": "available",
            "VpcId": "vpc-085c4a097408d438d",
            "OwnerId": "679788997248",
            "InstanceTenancy": "default",
            "CidrBlockAssociationSet": [
                {
                    "AssociationId": "vpc-cidr-assoc-05db0b29ba54e1edc",
                    "CidrBlock": "10.10.0.0/16",
                    "CidrBlockState": {
                        "State": "associated"
                    }
                }
            ],
            "IsDefault": false,
            "Tags": [
                {
                    "Key": "CostGroup",
                    "Value": "prj01"
                },
                {
                    "Key": "Name",
                    "Value": "prj01VPC"
                }
            ]
        }
    ]
}
```

成功！


## 失敗パターン

#### providerにregionを指定しないと

``` main.tf
provider "aws" {
  profile = "prj01-profile"
}
```

```
$ ../terraform.exe plan
provider.aws.region
  The region where AWS operations will take place. Examples
  are us-east-1, us-west-2, etc.

  Enter a value: 
```

上記のようにリージョンの指定を求められてしまうため、main.tf等に記載しておく方が良い。