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つだけある状態で、そのVPCを削除

![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"
  }
}
```

VPC作成時のmain.tfと同じ。[こちら](https://qiita.com/TG1050/items/202862069c0b89544275)。

## 実行

### 実行前の状態確認

```
$ 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"
                }
            ]
        }
    ]
}
```
削除対象のVPCが存在していることを確認。

#### 前提

```
$ 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は作成済み。

#### まずplan

```
$ ../terraform.exe plan -destroy
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.

aws_vpc.prj01VPC: Refreshing state... [id=vpc-085c4a097408d438d]

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

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_vpc.prj01VPC will be destroyed
  - resource "aws_vpc" "prj01VPC" {
      - arn                              = "arn:aws:ec2:us-west-2:679788997248:vpc/vpc-085c4a097408d438d" -> null
      - assign_generated_ipv6_cidr_block = false -> null
      - cidr_block                       = "10.10.0.0/16" -> null
      - default_network_acl_id           = "acl-005cda038798e1246" -> null
      - default_route_table_id           = "rtb-0ef695f3a63eff9a7" -> null
      - default_security_group_id        = "sg-0a7fa0eabf509911d" -> null
      - dhcp_options_id                  = "dopt-0ebee8b328487036e" -> null
      - enable_classiclink               = false -> null
      - enable_classiclink_dns_support   = false -> null
      - enable_dns_hostnames             = false -> null
      - enable_dns_support               = true -> null
      - id                               = "vpc-085c4a097408d438d" -> null
      - instance_tenancy                 = "default" -> null
      - main_route_table_id              = "rtb-0ef695f3a63eff9a7" -> null
      - owner_id                         = "679788997248" -> null
      - tags                             = {
          - "CostGroup" = "prj01"
          - "Name"      = "prj01VPC"
        } -> null
    }

Plan: 0 to add, 0 to change, 1 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.
```

消したいVPCだけが、destroyになっていることを確認。

#### 確認できたのでdestroy

```
$ ../terraform.exe destroy
aws_vpc.prj01VPC: Refreshing state... [id=vpc-085c4a097408d438d]

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_vpc.prj01VPC will be destroyed
  - resource "aws_vpc" "prj01VPC" {
      - arn                              = "arn:aws:ec2:us-west-2:679788997248:vpc/vpc-085c4a097408d438d" -> null
      - assign_generated_ipv6_cidr_block = false -> null
      - cidr_block                       = "10.10.0.0/16" -> null
      - default_network_acl_id           = "acl-005cda038798e1246" -> null
      - default_route_table_id           = "rtb-0ef695f3a63eff9a7" -> null
      - default_security_group_id        = "sg-0a7fa0eabf509911d" -> null
      - dhcp_options_id                  = "dopt-0ebee8b328487036e" -> null
      - enable_classiclink               = false -> null
      - enable_classiclink_dns_support   = false -> null
      - enable_dns_hostnames             = false -> null
      - enable_dns_support               = true -> null
      - id                               = "vpc-085c4a097408d438d" -> null
      - instance_tenancy                 = "default" -> null
      - main_route_table_id              = "rtb-0ef695f3a63eff9a7" -> null
      - owner_id                         = "679788997248" -> null
      - tags                             = {
          - "CostGroup" = "prj01"
          - "Name"      = "prj01VPC"
        } -> 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_vpc.prj01VPC: Destroying... [id=vpc-085c4a097408d438d]
aws_vpc.prj01VPC: Destruction complete after 1s

Destroy complete! Resources: 1 destroyed.
```

確認ポイント
- yesを入力する前に、消したいVPCだけが、destroyになっていること
- createとchangeが「0」になっていること
- その他エラーや警告が発生していないこと

#### 実行後の確認

```
$ aws ec2 describe-vpcs  --region=us-west-2
{
    "Vpcs": []
}
```

VPCが消えていることを確認。

## 消したい対象を明確に指定

#### 消すときはtargetを指定したい気分

```
$ ../terraform.exe plan -destroy -target=aws_vpc.prj01VPC
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.

aws_vpc.prj01VPC: Refreshing state... [id=vpc-0f54ed2c26b44b69f]

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

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_vpc.prj01VPC will be destroyed
  - resource "aws_vpc" "prj01VPC" {
      - arn                              = "arn:aws:ec2:us-west-2:679788997248:vpc/vpc-0f54ed2c26b44b69f" -> null
      - assign_generated_ipv6_cidr_block = false -> null
      - cidr_block                       = "10.10.0.0/16" -> null
      - default_network_acl_id           = "acl-06e41dd4dac36b4b0" -> null
      - default_route_table_id           = "rtb-0c683ac40dcdc13d0" -> null
      - default_security_group_id        = "sg-059f2992d43bd7002" -> null
      - dhcp_options_id                  = "dopt-0ebee8b328487036e" -> null
      - enable_classiclink               = false -> null
      - enable_classiclink_dns_support   = false -> null
      - enable_dns_hostnames             = false -> null
      - enable_dns_support               = true -> null
      - id                               = "vpc-0f54ed2c26b44b69f" -> null
      - instance_tenancy                 = "default" -> null
      - main_route_table_id              = "rtb-0c683ac40dcdc13d0" -> null
      - owner_id                         = "679788997248" -> null
      - tags                             = {
          - "CostGroup" = "prj01"
          - "Name"      = "prj01VPC"
        } -> null
    }

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

Warning: Resource targeting is in effect

You are creating a plan with the -target option, which means that the result
of this plan may not represent all of the changes requested by the current
configuration.

The -target option is not for routine use, and is provided only for
exceptional situations such as recovering from errors or mistakes, or when
Terraform specifically suggests to use it as part of an error message.


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

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

Warningが出た。

> 【google翻訳】
> -targetオプションは日常的に使用するためのものではなく、エラーやミスからの回復などの例外的な状況で、またはTerraformがエラーメッセージの一部として使用することを明確に提案した場合にのみ提供されます。

そうなのか。。。 まぁいいや！

```
$ ../terraform.exe destroy -target=aws_vpc.prj01VPC
aws_vpc.prj01VPC: Refreshing state... [id=vpc-0f54ed2c26b44b69f]

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_vpc.prj01VPC will be destroyed
  - resource "aws_vpc" "prj01VPC" {
      - arn                              = "arn:aws:ec2:us-west-2:679788997248:vpc/vpc-0f54ed2c26b44b69f" -> null
      - assign_generated_ipv6_cidr_block = false -> null
      - cidr_block                       = "10.10.0.0/16" -> null
      - default_network_acl_id           = "acl-06e41dd4dac36b4b0" -> null
      - default_route_table_id           = "rtb-0c683ac40dcdc13d0" -> null
      - default_security_group_id        = "sg-059f2992d43bd7002" -> null
      - dhcp_options_id                  = "dopt-0ebee8b328487036e" -> null
      - enable_classiclink               = false -> null
      - enable_classiclink_dns_support   = false -> null
      - enable_dns_hostnames             = false -> null
      - enable_dns_support               = true -> null
      - id                               = "vpc-0f54ed2c26b44b69f" -> null
      - instance_tenancy                 = "default" -> null
      - main_route_table_id              = "rtb-0c683ac40dcdc13d0" -> null
      - owner_id                         = "679788997248" -> null
      - tags                             = {
          - "CostGroup" = "prj01"
          - "Name"      = "prj01VPC"
        } -> null
    }

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


Warning: Resource targeting is in effect

You are creating a plan with the -target option, which means that the result
of this plan may not represent all of the changes requested by the current
configuration.

The -target option is not for routine use, and is provided only for
exceptional situations such as recovering from errors or mistakes, or when
Terraform specifically suggests to use it as part of an error message.

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_vpc.prj01VPC: Destroying... [id=vpc-0f54ed2c26b44b69f]
aws_vpc.prj01VPC: Destruction complete after 1s

Warning: Applied changes may be incomplete

The plan was created with the -target option in effect, so some changes
requested in the configuration may have been ignored and the output values may
not be fully updated. Run the following command to verify that no other
changes are pending:
    terraform plan

Note that the -target option is not suitable for routine use, and is provided
only for exceptional situations such as recovering from errors or mistakes, or
when Terraform specifically suggests to use it as part of an error message.


Destroy complete! Resources: 1 destroyed.
```


## 失敗パターン

#### targetの指定はtype.resource

```
$ ../terraform.exe plan -destroy -target=prj01VPC
Usage: terraform plan [options] [DIR]

  Generates an execution plan for Terraform.

  This execution plan can be reviewed prior to running apply to get a
  sense for what Terraform will do. Optionally, the plan can be saved to
  a Terraform plan file, and apply can take this plan file to execute
  this plan exactly.

Options:
  ：(略)
```

targateを指定する際にリソース名の前にtype(今回は"aws_vpc")を指定しないとエラーになる。
[マニュアル](https://www.terraform.io/docs/commands/plan.html)には

> -target=resource - A Resource Address to target. This flag can be used multiple times. See below for more information.

と書かれている。わかりにくいよ。。。

[こっち](https://www.terraform.io/docs/internals/resource-addressing.html)見るとちゃんと書いてある。

> Resource spec:
> A resource spec addresses a specific resource in the config. It takes the form:
> resource_type.resource_name[resource index]