コンマ

メモ代わりにアウトプットしています。何か不備がありましたら、お気軽にコメント頂けると有り難いです。

【Terraform】TerraformでVPC/Subnet/EC2インスタンスを作ってみる

TL;DR

TerraformでVPC/Subnet/EC2インスタンスを作る方法を記載しています。

先日、コンテナ時代のWebサービスの作り方 - 楽描商店 - BOOTHを技術書店で入手したので、これを元にやってみますmm

関連情報

booth.pm

前提条件

  • Terraformをインストールしていること。
  • AWS CLIをインストールしていること。(AWS CLIで使用できる状態になっていること、ポリシー等)
  • .aws/credentialsにアクセスキー/シークレットキーを定義していること。

やってみます。

まず今回の作業ディレクトリを適当に作成しました。

$ mkdir ~/terraform_ec2/
$ cd ~/terraform_ec2/

Terraformは、.tfという拡張子のファイルに記述していくそうです。

では、実際にVPC/Subnet/EC2インスタンスを作成するコードを記述していきます。

# ~/terraform_ec2/sample.tf
provider "aws" {
  region = "ap-northeast-1"
}
resource "aws_instance" "sandbox" {
  ami  = "ami-785c491f"
  instance_type = "t2.micro"
  subnet_id = "${aws_subnet.public_subnet.id}"
}
resource "aws_vpc" "vpc" {
  cidr_block = "10.0.0.0/16"
  instance_tenancy = "default"
}
resource "aws_subnet" "public_subnet" {
  vpc_id = "${aws_vpc.vpc.id}"
  cidr_block = "10.0.16.0/20"
  availability_zone = "ap-northeast-1a"
}

では、早速、terraform initをして、初期化してプラグインをインストールします。

$ terraform init

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

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.

成功ぽいです。

続いて、terraoform planで、コードがただしいかどうか確認してみます。 プランは.tfファイルの適用差分とかもみれるので、applyする前に必ずするようにします。

$ 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.sandbox
      id:                               <computed>
      ami:                              "ami-785c491f"
      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"
      host_id:                          <computed>
      instance_state:                   <computed>
      instance_type:                    "t2.micro"
      ipv6_address_count:               <computed>
      ipv6_addresses.#:                 <computed>
      key_name:                         <computed>
      network_interface.#:              <computed>
      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>
      source_dest_check:                "true"
      subnet_id:                        "${aws_subnet.public_subnet.id}"
      tenancy:                          <computed>
      volume_tags.%:                    <computed>
      vpc_security_group_ids.#:         <computed>

  + aws_subnet.public_subnet
      id:                               <computed>
      arn:                              <computed>
      assign_ipv6_address_on_creation:  "false"
      availability_zone:                "ap-northeast-1a"
      availability_zone_id:             <computed>
      cidr_block:                       "10.0.16.0/20"
      ipv6_cidr_block:                  <computed>
      ipv6_cidr_block_association_id:   <computed>
      map_public_ip_on_launch:          "false"
      owner_id:                         <computed>
      vpc_id:                           "${aws_vpc.vpc.id}"

  + aws_vpc.vpc
      id:                               <computed>
      arn:                              <computed>
      assign_generated_ipv6_cidr_block: "false"
      cidr_block:                       "10.0.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>
      owner_id:                         <computed>


Plan: 3 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.

vpc/subnet/ec2のリソースが作られることが確認できました。

次にEC2の状態をを確認してみます。

$ aws ec2 describe-instances
{
    "Reservations": []
}

何もない状態です。

では、最後にterraform applyをしてコードを反映してみます。

$ 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.sandbox
      id:                               <computed>
      ami:                              "ami-785c491f"
      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"
      host_id:                          <computed>
      instance_state:                   <computed>
      instance_type:                    "t2.micro"
      ipv6_address_count:               <computed>
      ipv6_addresses.#:                 <computed>
      key_name:                         <computed>
      network_interface.#:              <computed>
      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>
      source_dest_check:                "true"
      subnet_id:                        "${aws_subnet.public_subnet.id}"
      tenancy:                          <computed>
      volume_tags.%:                    <computed>
      vpc_security_group_ids.#:         <computed>

  + aws_subnet.public_subnet
      id:                               <computed>
      arn:                              <computed>
      assign_ipv6_address_on_creation:  "false"
      availability_zone:                "ap-northeast-1a"
      availability_zone_id:             <computed>
      cidr_block:                       "10.0.16.0/20"
      ipv6_cidr_block:                  <computed>
      ipv6_cidr_block_association_id:   <computed>
      map_public_ip_on_launch:          "false"
      owner_id:                         <computed>
      vpc_id:                           "${aws_vpc.vpc.id}"

  + aws_vpc.vpc
      id:                               <computed>
      arn:                              <computed>
      assign_generated_ipv6_cidr_block: "false"
      cidr_block:                       "10.0.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>
      owner_id:                         <computed>


Plan: 3 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.vpc: Creating...
  arn:                              "" => "<computed>"
  assign_generated_ipv6_cidr_block: "" => "false"
  cidr_block:                       "" => "10.0.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>"
  owner_id:                         "" => "<computed>"
aws_vpc.vpc: Creation complete after 3s (ID: vpc-058127339ddcbb085)
aws_subnet.public_subnet: Creating...
  arn:                             "" => "<computed>"
  assign_ipv6_address_on_creation: "" => "false"
  availability_zone:               "" => "ap-northeast-1a"
  availability_zone_id:            "" => "<computed>"
  cidr_block:                      "" => "10.0.16.0/20"
  ipv6_cidr_block:                 "" => "<computed>"
  ipv6_cidr_block_association_id:  "" => "<computed>"
  map_public_ip_on_launch:         "" => "false"
  owner_id:                        "" => "<computed>"
  vpc_id:                          "" => "vpc-058127339ddcbb085"
aws_subnet.public_subnet: Creation complete after 1s (ID: subnet-032cb10c161c0bbb0)
aws_instance.sandbox: Creating...
  ami:                          "" => "ami-785c491f"
  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"
  host_id:                      "" => "<computed>"
  instance_state:               "" => "<computed>"
  instance_type:                "" => "t2.micro"
  ipv6_address_count:           "" => "<computed>"
  ipv6_addresses.#:             "" => "<computed>"
  key_name:                     "" => "<computed>"
  network_interface.#:          "" => "<computed>"
  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>"
  source_dest_check:            "" => "true"
  subnet_id:                    "" => "subnet-032cb10c161c0bbb0"
  tenancy:                      "" => "<computed>"
  volume_tags.%:                "" => "<computed>"
  vpc_security_group_ids.#:     "" => "<computed>"
aws_instance.sandbox: Still creating... (10s elapsed)
aws_instance.sandbox: Still creating... (20s elapsed)
aws_instance.sandbox: Still creating... (30s elapsed)
aws_instance.sandbox: Creation complete after 33s (ID: i-0348f4fd93bf66a85)

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

成功しました! EC2を確認してみると

$ aws ec2 describe-instances
{
    "Reservations": [
        {
            "Instances": [
                {
                    "Monitoring": {
                        "State": "disabled"
                    }, 
                    "PublicDnsName": "", 
                    "State": {
                        "Code": 16, 
                        "Name": "running"
                    }, 
                    "EbsOptimized": false, 
                    "LaunchTime": "2019-04-25T14:12:03.000Z", 
                    "PrivateIpAddress": "10.0.29.37", 
                    "ProductCodes": [], 
                    "VpcId": "vpc-058127339ddcbb085", 
                    "CpuOptions": {
                        "CoreCount": 1, 
                        "ThreadsPerCore": 1
                    }, 
                    "StateTransitionReason": "", 
                    "InstanceId": "i-0348f4fd93bf66a85", 
                    "EnaSupport": true, 
                    "ImageId": "ami-785c491f", 
                    "PrivateDnsName": "ip-10-0-29-37.ap-northeast-1.compute.internal", 
                    "SecurityGroups": [
                        {
                            "GroupName": "default", 
                            "GroupId": "sg-0f2ce45530720ae5b"
                        }
                    ], 
                    "ClientToken": "", 
                    "SubnetId": "subnet-032cb10c161c0bbb0", 
                    "InstanceType": "t2.micro", 
                    "CapacityReservationSpecification": {
                        "CapacityReservationPreference": "open"
                    }, 
                    "NetworkInterfaces": [
                        {
                            "Status": "in-use", 
                            "MacAddress": "06:5c:7f:5f:64:9a", 
                            "SourceDestCheck": true, 
                            "VpcId": "vpc-058127339ddcbb085", 
                            "Description": "", 
                            "NetworkInterfaceId": "eni-010e14e0518faffd9", 
                            "PrivateIpAddresses": [
                                {
                                    "Primary": true, 
                                    "PrivateIpAddress": "10.0.29.37"
                                }
                            ], 
                            "SubnetId": "subnet-032cb10c161c0bbb0", 
                            "Attachment": {
                                "Status": "attached", 
                                "DeviceIndex": 0, 
                                "DeleteOnTermination": true, 
                                "AttachmentId": "eni-attach-045910b4d5eee5a68", 
                                "AttachTime": "2019-04-25T14:12:03.000Z"
                            }, 
                            "Groups": [
                                {
                                    "GroupName": "default", 
                                    "GroupId": "sg-0f2ce45530720ae5b"
                                }
                            ], 
                            "Ipv6Addresses": [], 
                            "OwnerId": "636993573019", 
                            "PrivateIpAddress": "10.0.29.37"
                        }
                    ], 
                    "SourceDestCheck": true, 
                    "Placement": {
                        "Tenancy": "default", 
                        "GroupName": "", 
                        "AvailabilityZone": "ap-northeast-1a"
                    }, 
                    "Hypervisor": "xen", 
                    "BlockDeviceMappings": [
                        {
                            "DeviceName": "/dev/sda1", 
                            "Ebs": {
                                "Status": "attached", 
                                "DeleteOnTermination": true, 
                                "VolumeId": "vol-038a0eaa1391cf959", 
                                "AttachTime": "2019-04-25T14:12:03.000Z"
                            }
                        }
                    ], 
                    "Architecture": "x86_64", 
                    "RootDeviceType": "ebs", 
                    "RootDeviceName": "/dev/sda1", 
                    "VirtualizationType": "hvm", 
                    "HibernationOptions": {
                        "Configured": false
                    }, 
                    "AmiLaunchIndex": 0
                }
            ], 
            "ReservationId": "r-0d56d4e822f7ac81c", 
            "Groups": [], 
            "OwnerId": "636993573019"
        }
    ]
}

正常に作られていることが確認できました。 こんなに簡単に作れるとは思っていなかったので、驚きです。。。