Terraform で EC2 のサーバをさくっと立ち上げてみる

# Terraform で EC2 のサーバをさくっと立ち上げてみる

Terraform は、ワンバイナリでできた Hashicorp のお手軽な DevOps 向けのアプリです。

[Terraform](https://www.terraform.io/)

特にインストールとか必要なく、ダウンロードして設定すれば使えるというのがいいと思います。

## Terraform をダウンロード

[Terraform Download](https://www.terraform.io/downloads.html)

自分のプラットホームのやつをダウンロードしてきましょう。

## 解凍

unzip でさくっと解凍します。
※linux 64bit 版での例です。

```
> unzip terraform_0.11.10_linux_amd64.zip
```

`terraform` というバイナリが一個解凍されます。

## 叩いてみる

```
> ./terraform
Usage: terraform [-version] [-help] <command> [args]

The available commands for execution are listed below.
The most common, useful commands are shown first, followed by
less common or more advanced commands. If you're just getting
started with Terraform, stick with the common commands. For the
other commands, please read the help and docs before usage.

Common commands:
    apply              Builds or changes infrastructure
    console            Interactive console for Terraform interpolations
    destroy            Destroy Terraform-managed infrastructure
    env                Workspace management
    fmt                Rewrites config files to canonical format
    get                Download and install modules for the configuration
    graph              Create a visual graph of Terraform resources
    import             Import existing infrastructure into Terraform
    init               Initialize a Terraform working directory
    output             Read an output from a state file
    plan               Generate and show an execution plan
    providers          Prints a tree of the providers used in the configuration
    push               Upload this Terraform module to Atlas to run
    refresh            Update local state file against real resources
    show               Inspect Terraform state or plan
    taint              Manually mark a resource for recreation
    untaint            Manually unmark a resource as tainted
    validate           Validates the Terraform files
    version            Prints the Terraform version
    workspace          Workspace management

All other commands:
    debug              Debug output management (experimental)
    force-unlock       Manually unlock the terraform state
    state              Advanced state management
```

何も指定しなかったので、ヘルプが表示されますね。

## とりあえず初期化

最初に初期化します。

```
> ./terraform init

Initializing provider plugins...
- Checking for available provider plugins on https://releases.hashicorp.com...
- Downloading plugin for provider "aws" (1.50.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 = "~> 1.50"

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

## tf ファイルの作成

`access key` と `secret key` は ユーザを `EC2 Full Access` とかの権限をつけて作成してやつのキーを使ってください。

```aws.tf
provider "aws" {
  region     = "ap-northeast-1"
  access_key = "<access key>"
  secret_key = "<secret key>"
}

resource "aws_vpc" "test_vpc" {
  cidr_block = "172.16.0.0/16"

  tags {
    Name = "tf-test"
  }
}

resource "aws_subnet" "test_subnet" {
  vpc_id            = "${aws_vpc.test_vpc.id}"
  cidr_block        = "172.16.10.0/24"
  availability_zone = "us-west-2a"

  tags {
    Name = "tf-test"
  }
}

resource "aws_network_interface" "test" {
  subnet_id   = "${aws_subnet.test_subnet.id}"
  private_ips = ["172.16.10.100"]

  tags {
    Name = "test_network_interface"
  }
}

resource "aws_instance" "test" {
  ami           = "ami-0fd02119f1653c976"
  instance_type = "t2.micro"

  network_interface {
    network_interface_id = "${aws_network_interface.test.id}"
    device_index         = 0
  }

  credit_specification {
    cpu_credits = "unlimited"
  }
}
```

ネットワークとかの設定も入れていますが、とりあえずこんなもんだと思ってやってみましょう。

## plan 実行

```
> ./terraform 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_instance.test
      id:                                                 <computed>
      ami:                                                "ami-0fd02119f1653c976"
      arn:                                                <computed>
      associate_public_ip_address:                        <computed>
      availability_zone:                                  <computed>
      cpu_core_count:                                     <computed>
      cpu_threads_per_core:                               <computed>
      credit_specification.#:                             "1"
      credit_specification.0.cpu_credits:                 "unlimited"
      ebs_block_device.#:                                 <computed>
      ephemeral_block_device.#:                           <computed>
      get_password_data:                                  "false"
      instance_state:                                     <computed>
      instance_type:                                      "t2.micro"
      ipv6_address_count:                                 <computed>
      ipv6_addresses.#:                                   <computed>
      key_name:                                           <computed>
      network_interface.#:                                "1"
      network_interface.~301229195.delete_on_termination: "false"
      network_interface.~301229195.device_index:          "0"
      network_interface.~301229195.network_interface_id:  "${aws_network_interface.test.id}"
      network_interface_id:                               <computed>
      password_data:                                      <computed>
      placement_group:                                    <computed>
      primary_network_interface_id:                       <computed>
      private_dns:                                        <computed>
      private_ip:                                         <computed>
      public_dns:                                         <computed>
      public_ip:                                          <computed>
      root_block_device.#:                                <computed>
      security_groups.#:                                  <computed>
      subnet_id:                                          <computed>
      tenancy:                                            <computed>
      volume_tags.%:                                      <computed>
      vpc_security_group_ids.#:                           <computed>

  + aws_network_interface.test
      id:                                                 <computed>
      attachment.#:                                       <computed>
      private_dns_name:                                   <computed>
      private_ip:                                         <computed>
      private_ips.#:                                      "1"
      private_ips.2198773196:                             "172.16.10.100"
      private_ips_count:                                  <computed>
      security_groups.#:                                  <computed>
      source_dest_check:                                  "true"
      subnet_id:                                          "${aws_subnet.test_subnet.id}"
      tags.%:                                             "1"
      tags.Name:                                          "test_network_interface"

  + aws_subnet.test_subnet
      id:                                                 <computed>
      arn:                                                <computed>
      assign_ipv6_address_on_creation:                    "false"
      availability_zone:                                  "us-west-2a"
      cidr_block:                                         "172.16.10.0/24"
      ipv6_cidr_block:                                    <computed>
      ipv6_cidr_block_association_id:                     <computed>
      map_public_ip_on_launch:                            "false"
      tags.%:                                             "1"
      tags.Name:                                          "tf-test"
      vpc_id:                                             "${aws_vpc.test_vpc.id}"

  + aws_vpc.test_vpc
      id:                                                 <computed>
      arn:                                                <computed>
      assign_generated_ipv6_cidr_block:                   "false"
      cidr_block:                                         "172.16.0.0/16"
      default_network_acl_id:                             <computed>
      default_route_table_id:                             <computed>
      default_security_group_id:                          <computed>
      dhcp_options_id:                                    <computed>
      enable_classiclink:                                 <computed>
      enable_classiclink_dns_support:                     <computed>
      enable_dns_hostnames:                               <computed>
      enable_dns_support:                                 "true"
      instance_tenancy:                                   "default"
      ipv6_association_id:                                <computed>
      ipv6_cidr_block:                                    <computed>
      main_route_table_id:                                <computed>
      tags.%:                                             "1"
      tags.Name:                                          "tf-test"


Plan: 4 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.
```

Error 出ないんで大丈夫そうですね。

## 実行しちゃいましょう

```
> ./terraform 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_instance.test
      id:                                                 <computed>
      ami:                                                "ami-0fd02119f1653c976"
      arn:                                                <computed>
      associate_public_ip_address:                        <computed>
      availability_zone:                                  <computed>
      cpu_core_count:                                     <computed>
      cpu_threads_per_core:                               <computed>
      ebs_block_device.#:                                 <computed>
      ephemeral_block_device.#:                           <computed>
      get_password_data:                                  "false"
      instance_state:                                     <computed>
      instance_type:                                      "t2.micro"
      ipv6_address_count:                                 <computed>
      ipv6_addresses.#:                                   <computed>
      key_name:                                           <computed>
      network_interface.#:                                "1"
      network_interface.~301229195.delete_on_termination: "false"
      network_interface.~301229195.device_index:          "0"
      network_interface.~301229195.network_interface_id:  "${aws_network_interface.test.id}"
      network_interface_id:                               <computed>
      password_data:                                      <computed>
      placement_group:                                    <computed>
      primary_network_interface_id:                       <computed>
      private_dns:                                        <computed>
      private_ip:                                         <computed>
      public_dns:                                         <computed>
      public_ip:                                          <computed>
      root_block_device.#:                                <computed>
      security_groups.#:                                  <computed>
      subnet_id:                                          <computed>
      tenancy:                                            <computed>
      volume_tags.%:                                      <computed>
      vpc_security_group_ids.#:                           <computed>

  + aws_network_interface.test
      id:                                                 <computed>
      attachment.#:                                       <computed>
      private_dns_name:                                   <computed>
      private_ip:                                         <computed>
      private_ips.#:                                      "1"
      private_ips.2198773196:                             "172.16.10.100"
      private_ips_count:                                  <computed>
      security_groups.#:                                  <computed>
      source_dest_check:                                  "true"
      subnet_id:                                          "${aws_subnet.test_subnet.id}"
      tags.%:                                             "1"
      tags.Name:                                          "test_network_interface"

  + aws_subnet.test_subnet
      id:                                                 <computed>
      arn:                                                <computed>
      assign_ipv6_address_on_creation:                    "false"
      availability_zone:                                  "ap-northeast-1a"
      cidr_block:                                         "172.16.10.0/24"
      ipv6_cidr_block:                                    <computed>
      ipv6_cidr_block_association_id:                     <computed>
      map_public_ip_on_launch:                            "false"
      tags.%:                                             "1"
      tags.Name:                                          "tf-test"
      vpc_id:                                             "${aws_vpc.test_vpc.id}"

  + aws_vpc.test_vpc
      id:                                                 <computed>
      arn:                                                <computed>
      assign_generated_ipv6_cidr_block:                   "false"
      cidr_block:                                         "172.16.0.0/16"
      default_network_acl_id:                             <computed>
      default_route_table_id:                             <computed>
      default_security_group_id:                          <computed>
      dhcp_options_id:                                    <computed>
      enable_classiclink:                                 <computed>
      enable_classiclink_dns_support:                     <computed>
      enable_dns_hostnames:                               <computed>
      enable_dns_support:                                 "true"
      instance_tenancy:                                   "default"
      ipv6_association_id:                                <computed>
      ipv6_cidr_block:                                    <computed>
      main_route_table_id:                                <computed>
      tags.%:                                             "1"
      tags.Name:                                          "tf-test"


Plan: 4 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:
```

`Enter a value:` と言われるので、 `yes` と打ちこみましょう。

```
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.test_vpc: Creating...
  arn:                              "" => "<computed>"
  assign_generated_ipv6_cidr_block: "" => "false"
  cidr_block:                       "" => "172.16.0.0/16"
  default_network_acl_id:           "" => "<computed>"
  default_route_table_id:           "" => "<computed>"
  default_security_group_id:        "" => "<computed>"
  dhcp_options_id:                  "" => "<computed>"
  enable_classiclink:               "" => "<computed>"
  enable_classiclink_dns_support:   "" => "<computed>"
  enable_dns_hostnames:             "" => "<computed>"
  enable_dns_support:               "" => "true"
  instance_tenancy:                 "" => "default"
  ipv6_association_id:              "" => "<computed>"
  ipv6_cidr_block:                  "" => "<computed>"
  main_route_table_id:              "" => "<computed>"
  tags.%:                           "" => "1"
  tags.Name:                        "" => "tf-test"
aws_vpc.test_vpc: Creation complete after 1s (ID: vpc-0df7f37f86984c9f8)
aws_subnet.test_subnet: Creating...
  arn:                             "" => "<computed>"
  assign_ipv6_address_on_creation: "" => "false"
  availability_zone:               "" => "ap-northeast-1a"
  cidr_block:                      "" => "172.16.10.0/24"
  ipv6_cidr_block:                 "" => "<computed>"
  ipv6_cidr_block_association_id:  "" => "<computed>"
  map_public_ip_on_launch:         "" => "false"
  tags.%:                          "" => "1"
  tags.Name:                       "" => "tf-test"
  vpc_id:                          "" => "vpc-0df7f37f86984c9f8"
aws_subnet.test_subnet: Creation complete after 1s (ID: subnet-0f14f7121fdcf032d)
aws_network_interface.test: Creating...
  attachment.#:           "" => "<computed>"
  private_dns_name:       "" => "<computed>"
  private_ip:             "" => "<computed>"
  private_ips.#:          "" => "1"
  private_ips.2198773196: "" => "172.16.10.100"
  private_ips_count:      "" => "<computed>"
  security_groups.#:      "" => "<computed>"
  source_dest_check:      "" => "true"
  subnet_id:              "" => "subnet-0f14f7121fdcf032d"
  tags.%:                 "" => "1"
  tags.Name:              "" => "test_network_interface"
aws_network_interface.test: Creation complete after 1s (ID: eni-054ea6740c399a320)
aws_instance.test: Creating...
  ami:                                                "" => "ami-0fd02119f1653c976"
  arn:                                                "" => "<computed>"
  associate_public_ip_address:                        "" => "<computed>"
  availability_zone:                                  "" => "<computed>"
  cpu_core_count:                                     "" => "<computed>"
  cpu_threads_per_core:                               "" => "<computed>"
  ebs_block_device.#:                                 "" => "<computed>"
  ephemeral_block_device.#:                           "" => "<computed>"
  get_password_data:                                  "" => "false"
  instance_state:                                     "" => "<computed>"
  instance_type:                                      "" => "t2.micro"
  ipv6_address_count:                                 "" => "<computed>"
  ipv6_addresses.#:                                   "" => "<computed>"
  key_name:                                           "" => "<computed>"
  network_interface.#:                                "" => "1"
  network_interface.1941974005.delete_on_termination: "" => "false"
  network_interface.1941974005.device_index:          "" => "0"
  network_interface.1941974005.network_interface_id:  "" => "eni-054ea6740c399a320"
  network_interface_id:                               "" => "<computed>"
  password_data:                                      "" => "<computed>"
  placement_group:                                    "" => "<computed>"
  primary_network_interface_id:                       "" => "<computed>"
  private_dns:                                        "" => "<computed>"
  private_ip:                                         "" => "<computed>"
  public_dns:                                         "" => "<computed>"
  public_ip:                                          "" => "<computed>"
  root_block_device.#:                                "" => "<computed>"
  security_groups.#:                                  "" => "<computed>"
  subnet_id:                                          "" => "<computed>"
  tenancy:                                            "" => "<computed>"
  volume_tags.%:                                      "" => "<computed>"
  vpc_security_group_ids.#:                           "" => "<computed>"
aws_instance.test: Still creating... (10s elapsed)
aws_instance.test: Still creating... (20s elapsed)
aws_instance.test: Still creating... (30s elapsed)
aws_instance.test: Creation complete after 32s (ID: i-056a2a87f6e5da3c6)

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

なんか、できたっぽいですね。 `ID: i-056a2a87f6e5da3c6` があるか AWS の EC2 インスタンス一覧で見てみます。

![ec2_001.png](https://qiita-image-store.s3.amazonaws.com/0/318450/c35cb3e5-529b-7bf4-7528-48ebcd6fed03.png)

ありますね。

## ついでなので、デストロイもしてみます。

```
> ./terraform destroy
aws_vpc.test_vpc: Refreshing state... (ID: vpc-0df7f37f86984c9f8)
aws_subnet.test_subnet: Refreshing state... (ID: subnet-0f14f7121fdcf032d)
aws_network_interface.test: Refreshing state... (ID: eni-054ea6740c399a320)
aws_instance.test: Refreshing state... (ID: i-056a2a87f6e5da3c6)

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_instance.test

  - aws_network_interface.test

  - aws_subnet.test_subnet

  - aws_vpc.test_vpc


Plan: 0 to add, 0 to change, 4 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` と打ち込みます。

```
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_instance.test: Destroying... (ID: i-056a2a87f6e5da3c6)
aws_instance.test: Still destroying... (ID: i-056a2a87f6e5da3c6, 10s elapsed)
aws_instance.test: Still destroying... (ID: i-056a2a87f6e5da3c6, 20s elapsed)
aws_instance.test: Still destroying... (ID: i-056a2a87f6e5da3c6, 30s elapsed)
aws_instance.test: Still destroying... (ID: i-056a2a87f6e5da3c6, 40s elapsed)
aws_instance.test: Still destroying... (ID: i-056a2a87f6e5da3c6, 50s elapsed)
aws_instance.test: Still destroying... (ID: i-056a2a87f6e5da3c6, 1m0s elapsed)
aws_instance.test: Destruction complete after 1m0s
aws_network_interface.test: Destroying... (ID: eni-054ea6740c399a320)
aws_network_interface.test: Destruction complete after 1s
aws_subnet.test_subnet: Destroying... (ID: subnet-0f14f7121fdcf032d)
aws_subnet.test_subnet: Destruction complete after 1s
aws_vpc.test_vpc: Destroying... (ID: vpc-0df7f37f86984c9f8)
aws_vpc.test_vpc: Destruction complete after 0s

Destroy complete! Resources: 4 destroyed.
```

見事デストロイされましたね。
インスタンス一覧で見ると、`terminated` になってますね。

## 終わりに

今回は、EC2 をネットワークごとさくっと立ち上げて、ついでにぶっ壊すとこまでやってみました。
Terraform がどんな感じで動くか、体感できましたでしょうかね。

## 参照

[AWS Provider](https://www.terraform.io/docs/providers/aws/index.html)