あめがえるのITブログ

頑張りすぎない。ほどほどに頑張るブログ。

terraformでAmazon EC2インスタンスを作成してみた

眠い。眠すぎるのでterraformでAmazon EC2でも作ります((-_-)zzz

terraformとは

HashiCorp社によって作成されたオープンソースのIaC(Infrastracture as Code)ツール。

※as aじゃないみたいです。( ;∀;)

terraformの使い方

設定値を記載したtfファイルを作成し、terraformコマンドで各リソースの作成を行う。



やること

AWS CloudShellにterraformをインストールし、EC2インスタンスを作成する。

前提

  • 事前にAWS VPC、Subnet、SecurityGroup、KeyPairが作成されていること
    ※ CloudShellだとSecretKeyが不要なので少し楽♪

実践!

1.terraformインストール

$ TER_VER=`curl -s https://api.github.com/repos/hashicorp/terraform/releases/latest | grep tag_name | cut -d: -f2 | tr -d \"\,\v | awk '{$1=$1};1'` 
$ wget https://releases.hashicorp.com/terraform/${TER_VER}/terraform_${TER_VER}_linux_amd64.zip
$ unzip terraform_${TER_VER}_linux_amd64.zip
$ sudo mv terraform /usr/local/bin/
$ terraform --version
Terraform v1.4.6
on linux_amd64
+ provider registry.terraform.io/hashicorp/aws v5.0.0


2.EC2作成
 2-1.tfファイル作成

$ vi main.tf
provider "aws" {
  region = "ap-northeast-1"
}

resource "aws_instance" "sample" {
  ami                                         = "ami-07c2a88388bb80eb0"
  instance_type                          = "t2.micro"
  availability_zone                     = "ap-northeast-1a"
  subnet_id                                = "subnet-08ced1e54ca9c6451"
  key_name                                = "sample-key"
  associate_public_ip_address   = "true"

  tags = {
    Name = "sample-instance"
  }
}


 2-2.terraform初期化

$ terraform init
Initializing the backend...

Initializing provider plugins...
- Finding latest version of hashicorp/aws...
- Installing hashicorp/aws v5.0.0...
- Installed hashicorp/aws v5.0.0 (signed by HashiCorp)

Terraform has created a lock file .terraform.lock.hcl to record the provider
selections it made above. Include this file in your version control repository
so that Terraform can guarantee to make the same selections by default when
you run "terraform init" in the future.

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.


 2-3.tfファイル構文チェック

$ terraform validate
Success! The configuration is valid.


 2-4.plan実行

$ terraform plan
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.sample will be created
  + resource "aws_instance" "sample" {
      + ami                                  = "ami-07c2a88388bb80eb0"
      + arn                                  = (known after apply)
      + associate_public_ip_address          = true
      + availability_zone                    = "ap-northeast-1"
      + cpu_core_count                       = (known after apply)
      + cpu_threads_per_core                 = (known after apply)
      + disable_api_stop                     = (known after apply)
      + disable_api_termination              = (known after apply)
      + ebs_optimized                        = (known after apply)
      + get_password_data                    = false
      + host_id                              = (known after apply)
      + host_resource_group_arn              = (known after apply)
      + iam_instance_profile                 = (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                             = "20230415"
      + 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-08ced1e54ca9c6451"
      + tags                                 = {
          + "Name" = "sample-instance"
        }
      + tags_all                             = {
          + "Name" = "sample-instance"
        }
      + tenancy                              = (known after apply)
      + user_data                            = (known after apply)
      + user_data_base64                     = (known after apply)
      + user_data_replace_on_change          = false
      + vpc_security_group_ids               = (known after apply)
    }

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

────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────

Note: You didn't use the -out option to save this plan, so Terraform can't guarantee to take exactly these actions if you run "terraform apply" now.


 2-5.作成実行

$ 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.sample will be created
  + resource "aws_instance" "sample" {
      + ami                                  = "ami-07c2a88388bb80eb0"
      + arn                                  = (known after apply)
      + associate_public_ip_address          = true
      + availability_zone                    = "ap-northeast-1a"
      + cpu_core_count                       = (known after apply)
      + cpu_threads_per_core                 = (known after apply)
      + disable_api_stop                     = (known after apply)
      + disable_api_termination              = (known after apply)
      + ebs_optimized                        = (known after apply)
      + get_password_data                    = false
      + host_id                              = (known after apply)
      + host_resource_group_arn              = (known after apply)
      + iam_instance_profile                 = (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                             = "20230415"
      + 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-08ced1e54ca9c6451"
      + tags                                 = {
          + "Name" = "sample-instance"
        }
      + tags_all                             = {
          + "Name" = "sample-instance"
        }
      + tenancy                              = (known after apply)
      + user_data                            = (known after apply)
      + user_data_base64                     = (known after apply)
      + user_data_replace_on_change          = false
      + 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

aws_instance.sample: Creating...
aws_instance.sample: Still creating... [10s elapsed]
aws_instance.sample: Still creating... [20s elapsed]
aws_instance.sample: Still creating... [30s elapsed]
aws_instance.sample: Creation complete after 32s [id=i-089e05ecb75248a81]

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


 2-6.確認

$ terraform show

# aws_instance.sample:
resource "aws_instance" "sample" {
    ami                                  = "ami-07c2a88388bb80eb0"
    arn                                  = "arn:aws:ec2:ap-northeast-1:xxxxxxxxxxx:instance/i-089e05ecb75248a81"
    associate_public_ip_address          = true
    availability_zone                    = "ap-northeast-1a"
    cpu_core_count                       = 1
    cpu_threads_per_core                 = 1
    disable_api_stop                     = false
    disable_api_termination              = false
    ebs_optimized                        = false
    get_password_data                    = false
    hibernation                          = false
    id                                   = "i-089e05ecb75248a81"
    instance_initiated_shutdown_behavior = "stop"
    instance_state                       = "running"
    instance_type                        = "t2.micro"
    ipv6_address_count                   = 0
    ipv6_addresses                       = []
    key_name                             = "20230415"
    monitoring                           = false
    placement_partition_number           = 0
    primary_network_interface_id         = "eni-0b2ef805aa79892b5"
    private_dns                          = "ip-172-31-35-9.ap-northeast-1.compute.internal"
    private_ip                           = "172.31.35.9"
    public_dns                           = "ec2-18-182-64-188.ap-northeast-1.compute.amazonaws.com"
    public_ip                            = "18.182.64.188"
    secondary_private_ips                = []
    security_groups                      = [
        "default",
    ]
    source_dest_check                    = true
    subnet_id                            = "subnet-08ced1e54ca9c6451"
    tags                                 = {
        "Name" = "sample-instance"
    }
    tags_all                             = {
        "Name" = "sample-instance"
    }
    tenancy                              = "default"
    user_data_replace_on_change          = false
    vpc_security_group_ids               = [
        "sg-08591299bb5c05e63",
    ]

    capacity_reservation_specification {
        capacity_reservation_preference = "open"
    }

    cpu_options {
        core_count       = 1
        threads_per_core = 1
    }

    credit_specification {
        cpu_credits = "standard"
    }

    enclave_options {
        enabled = false
    }

    maintenance_options {
        auto_recovery = "default"
    }

    metadata_options {
        http_endpoint               = "enabled"
        http_put_response_hop_limit = 1
        http_tokens                 = "optional"
        instance_metadata_tags      = "disabled"
    }

    private_dns_name_options {
        enable_resource_name_dns_a_record    = false
        enable_resource_name_dns_aaaa_record = false
        hostname_type                        = "ip-name"
    }

    root_block_device {
        delete_on_termination = true
        device_name           = "/dev/xvda"
        encrypted             = false
        iops                  = 100
        tags                  = {}
        throughput            = 0
        volume_id             = "vol-0528030a6c085e51a"
        volume_size           = 8
        volume_type           = "gp2"
    }
}


3.EC2インスタンス削除

$ terraform destroy
aws_instance.sample: Refreshing state... [id=i-089e05ecb75248a81]

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.sample will be destroyed
  - resource "aws_instance" "sample" {
      - ami                                  = "ami-07c2a88388bb80eb0" -> null
      - arn                                  = "arn:aws:ec2:ap-northeast-1:xxxxxxxxxxx:instance/i-089e05ecb75248a81" -> null
      - associate_public_ip_address          = true -> null
      - availability_zone                    = "ap-northeast-1a" -> null
      - cpu_core_count                       = 1 -> null
      - cpu_threads_per_core                 = 1 -> null
      - disable_api_stop                     = false -> null
      - disable_api_termination              = false -> null
      - ebs_optimized                        = false -> null
      - get_password_data                    = false -> null
      - hibernation                          = false -> null
      - id                                   = "i-089e05ecb75248a81" -> null
      - instance_initiated_shutdown_behavior = "stop" -> null
      - instance_state                       = "running" -> null
      - instance_type                        = "t2.micro" -> null
      - ipv6_address_count                   = 0 -> null
      - ipv6_addresses                       = [] -> null
      - key_name                             = "20230415" -> null
      - monitoring                           = false -> null
      - placement_partition_number           = 0 -> null
      - primary_network_interface_id         = "eni-0b2ef805aa79892b5" -> null
      - private_dns                          = "ip-172-31-35-9.ap-northeast-1.compute.internal" -> null
      - private_ip                           = "172.31.35.9" -> null
      - public_dns                           = "ec2-18-182-64-188.ap-northeast-1.compute.amazonaws.com" -> null
      - public_ip                            = "18.182.64.188" -> null
      - secondary_private_ips                = [] -> null
      - security_groups                      = [
          - "default",
        ] -> null
      - source_dest_check                    = true -> null
      - subnet_id                            = "subnet-08ced1e54ca9c6451" -> null
      - tags                                 = {
          - "Name" = "sample-instance"
        } -> null
      - tags_all                             = {
          - "Name" = "sample-instance"
        } -> null
      - tenancy                              = "default" -> null
      - user_data_replace_on_change          = false -> null
      - vpc_security_group_ids               = [
          - "sg-08591299bb5c05e63",
        ] -> null

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

      - cpu_options {
          - core_count       = 1 -> null
          - threads_per_core = 1 -> null
        }

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

      - enclave_options {
          - enabled = false -> null
        }

      - maintenance_options {
          - auto_recovery = "default" -> null
        }

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

      - private_dns_name_options {
          - enable_resource_name_dns_a_record    = false -> null
          - enable_resource_name_dns_aaaa_record = false -> null
          - hostname_type                        = "ip-name" -> 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-0528030a6c085e51a" -> 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.sample: Destroying... [id=i-089e05ecb75248a81]
aws_instance.sample: Still destroying... [id=i-089e05ecb75248a81, 10s elapsed]
aws_instance.sample: Still destroying... [id=i-089e05ecb75248a81, 20s elapsed]
aws_instance.sample: Destruction complete after 30s

Destroy complete! Resources: 1 destroyed.
$ terraform show
The state file is empty. No resources are represented.



感想

CloudFormationとどっちが楽だろう。あんまり変わらない気がするから好みかな。