🐈

【Terraform】AWS上にEC2インスタンス作成(入門)

2021/12/07に公開

はじめに

Terraformを触り始めたので、早速入門としてAWS上にEC2インスタンスを作成するコードをアウトプットしたいと思います。
EC2インスタンスを削除する方法もついでに載せておきます。

前提

  • Windows10のPCにてTerraformのコードを実行
  • 既にWindows10にTerraform環境構築済み
  • AWSのデフォルトVPCを一度削除しているため、サブネットIDを指定してコードを実行
  • SSHは試してない状態になります。コードでEC2インスタンスを作成することが目的です。

※今度、Windows10にTerraform環境を構築する記事をアウトプットしたいと思います。

構成図

  • EC2作成前

  • EC2作成後

実行するコード

EC2インスタンス作成コード
provider "aws" {
    profile = "terraform"
    region = "ap-northeast-1"
}

resource "aws_instance" "hello-world" {
    ami = "ami-0218d08a1f9dac831"
    instance_type = "t2.micro"
    subnet_id = "subnet-00dcd4caf121aac0a"

    tags = {
        Name = "HelloWorld"
    }

}

作成するEC2の情報

項目 設定 備考
リージョン ap-northeast-1 東京リージョン
AMI ami-0218d08a1f9dac831 AmazonLinux2のAMI
インスタンスタイプ t2.micro 最小サイズ
subnet_id subnet-00dcd4caf121aac0a EC2インスタンスを所属させるサブネット

EC2インスタンス作成手順

1.コードを配置しているフォルダ内で以下コマンドを実行する。

コマンド
terraform apply

2.確認画面が表示される。

確認画面にて以下設定が反映されていることを確認する。

項目 設定 備考
ami ami-0218d08a1f9dac831 AmazonLinux2のAMI
instance_type t2.micro
subnet_id subnet-00dcd4caf121aac0a

確認後、yesと入力し「Enter」を押下する。

コマンド
$ terraform apply

Terraform used the selected providers to generate the following execution plan. Resource actions are indicated with the following symbols:
  + create

Terraform will perform the following actions:

  # aws_instance.hello-world will be created
  + resource "aws_instance" "hello-world" {
      + ami                                  = "ami-0218d08a1f9dac831"
      + 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)
      + disable_api_termination              = (known after apply)
      + ebs_optimized                        = (known after apply)
      + get_password_data                    = false
      + host_id                              = (known after apply)
      + id                                   = (known after apply)
      + instance_initiated_shutdown_behavior = (known after apply)
      + instance_state                       = (known after apply)
      + instance_type                        = "t2.micro"
      + ipv6_address_count                   = (known after apply)
      + ipv6_addresses                       = (known after apply)
      + key_name                             = (known after apply)
      + monitoring                           = (known after apply)
      + outpost_arn                          = (known after apply)
      + password_data                        = (known after apply)
      + placement_group                      = (known after apply)
      + placement_partition_number           = (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                            = "subnet-00dcd4caf121aac0a"
      + tags                                 = {
          + "Name" = "HelloWorld"
        }
      + tags_all                             = {
          + "Name" = "HelloWorld"
        }
      + tenancy                              = (known after apply)
      + user_data                            = (known after apply)
      + user_data_base64                     = (known after apply)
      + vpc_security_group_ids               = (known after apply)
      
      ~~~~~長いため一部省略~~~~
      
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 ←こちらで「yes」を入力

aws_instance.hello-world: Creating...
aws_instance.hello-world: Still creating... [10s elapsed]
aws_instance.hello-world: Still creating... [20s elapsed]
aws_instance.hello-world: Still creating... [30s elapsed]
aws_instance.hello-world: Creation complete after 33s [id=i-0fd7736d35957b3f6]

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

3.AWSマネジメントコンソール上にEC2インスタンスが作成されていることを確認。

タグも付与されていることを確認

EC2インスタンス削除手順

1.以下コマンドを実行する。

コマンド
terraform destroy

2.削除するEC2インスタンスの情報が表示される。

削除するEC2インスタンスの情報に相違がなければ、yesを入力し「Enter」を押下する。

実行例
$ terraform destroy
aws_instance.hello-world: Refreshing state... [id=i-0fd7736d35957b3f6]

Terraform used the selected providers to generate the following execution plan. Resource actions are indicated with the following symbols:
  - destroy

Terraform will perform the following actions:

  # aws_instance.hello-world will be destroyed
  - resource "aws_instance" "hello-world" {
      - ami                                  = "ami-0218d08a1f9dac831" -> null
      - arn                                  = "arn:aws:ec2:ap-northeast-1:555xxxxxxxxx443:instance/i-0fd7736d35957b3f6" -> null
      - associate_public_ip_address          = false -> null
      - availability_zone                    = "ap-northeast-1a" -> null
      - cpu_core_count                       = 1 -> null
      - cpu_threads_per_core                 = 1 -> null
      - disable_api_termination              = false -> null
      - ebs_optimized                        = false -> null
      - get_password_data                    = false -> null
      - hibernation                          = false -> null
      - id                                   = "i-0fd7736d35957b3f6" -> null
      - instance_initiated_shutdown_behavior = "stop" -> null
      - instance_state                       = "running" -> null
      - instance_type                        = "t2.micro" -> null
      - ipv6_address_count                   = 0 -> null
      - ipv6_addresses                       = [] -> null
      - monitoring                           = false -> null
      - primary_network_interface_id         = "eni-0e7f5e4b853737072" -> null
      - private_dns                          = "ip-172-31-0-78.ap-northeast-1.compute.internal" -> null
      - private_ip                           = "172.31.0.78" -> null
      - secondary_private_ips                = [] -> null
      - security_groups                      = [
          - "default",
        ] -> null
      - source_dest_check                    = true -> null
      - subnet_id                            = "subnet-00dcd4caf121aac0a" -> null
      - tags                                 = {
          - "Name" = "HelloWorld"
        } -> null
      - tags_all                             = {
          - "Name" = "HelloWorld"
        } -> null
      - tenancy                              = "default" -> null
      - vpc_security_group_ids               = [
          - "sg-05c7b7a191f925c74",
        ] -> null

      - capacity_reservation_specification {
          - capacity_reservation_preference = "open" -> null
        }

      - credit_specification {
          - cpu_credits = "standard" -> null
        }

      - enclave_options {
          - enabled = false -> null
        }

      - metadata_options {
          - http_endpoint               = "enabled" -> null
          - http_put_response_hop_limit = 1 -> null
          - http_tokens                 = "optional" -> null
        }

      - root_block_device {
          - delete_on_termination = true -> null
          - device_name           = "/dev/xvda" -> null
          - encrypted             = false -> null
          - iops                  = 100 -> null
          - tags                  = {} -> null
          - throughput            = 0 -> null
          - volume_id             = "vol-0c6eb52efc39d32f3" -> null
          - volume_size           = 8 -> null
          - volume_type           = "gp2" -> 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_instance.hello-world: Destroying... [id=i-0fd7736d35957b3f6]
aws_instance.hello-world: Still destroying... [id=i-0fd7736d35957b3f6, 10s elapsed]
aws_instance.hello-world: Still destroying... [id=i-0fd7736d35957b3f6, 20s elapsed]
aws_instance.hello-world: Still destroying... [id=i-0fd7736d35957b3f6, 30s elapsed]
aws_instance.hello-world: Still destroying... [id=i-0fd7736d35957b3f6, 40s elapsed]
aws_instance.hello-world: Destruction complete after 40s

Destroy complete! Resources: 1 destroyed.

3.AWSマネジメントコンソールにてEC2インスタンスが「終了済み」になっていることを確認する。

※終了済みのEC2インスタンスが3つ存在しますが、今回削除したインスタンスはi-0fd7736d35957b3f6になります。

さいごに

ざっくりアウトプットしましたが、まだまだ足りない部分はあると思います。
僕自身が経験不足のため、勉強しながらアウトプットを増やしていければと思います。

参考

AWS と Terraformで実現するInfrastructure as Code

Discussion