Home

[Terraform] Terraform AWS Tutorial 따라하기

Terraform logo

쿠버네티스 강의를 듣는데 mac에서는 환경 구축을 AWS를 통해서 해야 한다. 근데 이게 프리티어로 제공하는 서비스로는 불가능해서 돈을 아끼려고 강의 들을 때 마다 설정을 하는데 이게 영 귀찮아서 테라폼을 통해서 테스트 환경을 한번에 구현해보고자 잠깐 학습을 해보았다

테라폼 AWS 인프라 구축 튜토리얼을 해보면서 일단 기록을 남긴다.

테라폼 AWS 튜토리얼

1. 준비

테스트를 진행하기 위해서는 aws-cli가 설치되어 있어야 한다. ( 당연히 테라폼도 설치 되어있어야 한다. 없다면 튜토리얼을 따라해보자.)

나 같은 경우 사내 계정이 default로 설정되어 있어서 개인계정 생성 후 profile을 따로 설정하였다. 프로필 설정은 Novemberde’s Blog - # AWS Configure 여러 계정으로 스위칭하며 사용하기 참조하였다.

또한 해당 iam에는 AmazonEC2FullAccess권한만 주었다.

2. main.tf 작성

일단 main.tf를 작성해야 하는데, 일단 무엇인지 모르니 튜토리얼에 있는 사항을 복붙 하였고, 일부 항목만 수정해주었다. 수정한 항목은 다음과 같다.

  • provider 항목

    • profile

      • 회사 맥북으로 학습을 하다보니 aws default profile이 사내 계정으로 되어 있기 때문에 개인 계정을 이용하도록 수정하였다.
      • aws configure --profile을 통해서 생성한 프로필명을 넣어주었다.
    • region

      • aws profileregion을 내가 사용하는 region으로 넣어주었다.
      • region이 설정이 안되있으면 profile에 설정이 되어 있다 하더라도 apply할 때 다시 묻는다고 한다.
  • resource 항목

    • ami

      • region이 달라져서 그런지 튜토리얼에 있는 ami를 찾을수 없다고 뜨는데, AWS Console에 들어가서 ami를 찾아서 수정해주었다.
# 테라폼 최종 결과물.. codeblock 지원이 안되서 일단 bash로 설정..
terraform {
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 4.16"
    }
  }

  required_version = ">= 1.2.0"
}

provider "aws" {
  profile = "{profileName}"  # 위에서 설정한 프로필명으로 수정 필요.
  region  = "ap-northeast-2" # profile에 region이 설정되어 있어도 명시적으로 설정해줘야 한다. 안그러면 apply할때 region을 입력해줘야 한다.
}

resource "aws_instance" "app_server" {
  ami           = "ami-09eba584c30b7299f" # 튜토리얼에 있는 ami가 존재하지 않아서 AWS에 있는 프리티어용 ami로 변경.
  instance_type = "t2.micro"

  tags = {
    Name = "ExampleAppServerInstance"
  }
}

3. Terraform init

main.tf를 다 작성하였다면 init을 해보자.

➜  learn-terraform-aws-instance git:(main) ✗ terraform init

Initializing the backend...

Initializing provider plugins...
- Finding hashicorp/aws versions matching "~> 4.16"...
- Installing hashicorp/aws v4.52.0...
- Installed hashicorp/aws v4.52.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.

4. Terraform apply

이제 실제 변경된 내용을 적용해보는 차례이다.

중간에 보면 aws2에서 인스턴스를 생성하다가 InvalidAMIID.NotFound라고 에러가 뜨는 것을 볼 수 있는데 맨 처음 튜토리얼에 있는 ami id를 이용해서 발생한 에러이다. 이 때문에 ami id를 수정하고 다시 apply를 적용 하였다.

➜  learn-terraform-aws-instance git:(main) ✗ 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.app_server will be created
  + resource "aws_instance" "app_server" {
      + ami                                  = "ami-830c94e3"
      + 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_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                             = (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                            = (known after apply)
      + tags                                 = {
          + "Name" = "ExampleAppServerInstance"
        }
      + tags_all                             = {
          + "Name" = "ExampleAppServerInstance"
        }
      + 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)

      + capacity_reservation_specification {
          + capacity_reservation_preference = (known after apply)

          + capacity_reservation_target {
              + capacity_reservation_id                 = (known after apply)
              + capacity_reservation_resource_group_arn = (known after apply)
            }
        }

      + ebs_block_device {
          + delete_on_termination = (known after apply)
          + device_name           = (known after apply)
          + encrypted             = (known after apply)
          + iops                  = (known after apply)
          + kms_key_id            = (known after apply)
          + snapshot_id           = (known after apply)
          + tags                  = (known after apply)
          + throughput            = (known after apply)
          + volume_id             = (known after apply)
          + volume_size           = (known after apply)
          + volume_type           = (known after apply)
        }

      + enclave_options {
          + enabled = (known after apply)
        }

      + ephemeral_block_device {
          + device_name  = (known after apply)
          + no_device    = (known after apply)
          + virtual_name = (known after apply)
        }

      + maintenance_options {
          + auto_recovery = (known after apply)
        }

      + metadata_options {
          + http_endpoint               = (known after apply)
          + http_put_response_hop_limit = (known after apply)
          + http_tokens                 = (known after apply)
          + instance_metadata_tags      = (known after apply)
        }

      + network_interface {
          + delete_on_termination = (known after apply)
          + device_index          = (known after apply)
          + network_card_index    = (known after apply)
          + network_interface_id  = (known after apply)
        }

      + private_dns_name_options {
          + enable_resource_name_dns_a_record    = (known after apply)
          + enable_resource_name_dns_aaaa_record = (known after apply)
          + hostname_type                        = (known after apply)
        }

      + root_block_device {
          + delete_on_termination = (known after apply)
          + device_name           = (known after apply)
          + encrypted             = (known after apply)
          + iops                  = (known after apply)
          + kms_key_id            = (known after apply)
          + tags                  = (known after apply)
          + throughput            = (known after apply)
          + volume_id             = (known after apply)
          + volume_size           = (known after apply)
          + volume_type           = (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.app_server: Creating...
╷
│ Error: creating EC2 Instance: InvalidAMIID.NotFound: The image id '[ami-830c94e3]' does not exist
│       status code: 400, request id: 736c2f50-e798-4d06-9088-3c095048bdd6
│ 
│   with aws_instance.app_server,
│   on main.tf line 17, in resource "aws_instance" "app_server":17: resource "aws_instance" "app_server" {
│ 
╵
➜  learn-terraform-aws-instance git:(main) ✗ 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.app_server will be created
  + resource "aws_instance" "app_server" {
      + ami                                  = "ami-013218fccb68a90d4"
      + 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_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                             = (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                            = (known after apply)
      + tags                                 = {
          + "Name" = "ExampleAppServerInstance"
        }
      + tags_all                             = {
          + "Name" = "ExampleAppServerInstance"
        }
      + 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)

      + capacity_reservation_specification {
          + capacity_reservation_preference = (known after apply)

          + capacity_reservation_target {
              + capacity_reservation_id                 = (known after apply)
              + capacity_reservation_resource_group_arn = (known after apply)
            }
        }

      + ebs_block_device {
          + delete_on_termination = (known after apply)
          + device_name           = (known after apply)
          + encrypted             = (known after apply)
          + iops                  = (known after apply)
          + kms_key_id            = (known after apply)
          + snapshot_id           = (known after apply)
          + tags                  = (known after apply)
          + throughput            = (known after apply)
          + volume_id             = (known after apply)
          + volume_size           = (known after apply)
          + volume_type           = (known after apply)
        }

      + enclave_options {
          + enabled = (known after apply)
        }

      + ephemeral_block_device {
          + device_name  = (known after apply)
          + no_device    = (known after apply)
          + virtual_name = (known after apply)
        }

      + maintenance_options {
          + auto_recovery = (known after apply)
        }

      + metadata_options {
          + http_endpoint               = (known after apply)
          + http_put_response_hop_limit = (known after apply)
          + http_tokens                 = (known after apply)
          + instance_metadata_tags      = (known after apply)
        }

      + network_interface {
          + delete_on_termination = (known after apply)
          + device_index          = (known after apply)
          + network_card_index    = (known after apply)
          + network_interface_id  = (known after apply)
        }

      + private_dns_name_options {
          + enable_resource_name_dns_a_record    = (known after apply)
          + enable_resource_name_dns_aaaa_record = (known after apply)
          + hostname_type                        = (known after apply)
        }

      + root_block_device {
          + delete_on_termination = (known after apply)
          + device_name           = (known after apply)
          + encrypted             = (known after apply)
          + iops                  = (known after apply)
          + kms_key_id            = (known after apply)
          + tags                  = (known after apply)
          + throughput            = (known after apply)
          + volume_id             = (known after apply)
          + volume_size           = (known after apply)
          + volume_type           = (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.app_server: Creating...
aws_instance.app_server: Still creating... [10s elapsed]
aws_instance.app_server: Still creating... [20s elapsed]
aws_instance.app_server: Creation complete after 21s [id=i-091f7a9dd8fddad20]

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

로그를 보면 각종 설정이 출력되는 것을 볼 수 있는데, 해당 설정을 따로 설정을 안해줬기에 (known after apply)로 출력되는 것을 볼 수 있다. 해당 항목들은 apply가 완료된 이후에 확인할 수 있으며, 설정을 한 항목들의 경우 설정 내용대로 출력되는 것을 볼 수 있다.

apply를 하는게 맞는지 확인하는 입력창이 나오면 yes를 입력하면 log를 통해서 인스턴스가 생성과정을 알려준다.

5. 인스턴스 생성 확인

apply 명령이 완료되면 이제 인스턴스가 실제로 떳는지 확인해보자. AWS Console에 들어가서 확인해보니 인스턴스가 정상적으로 뜨는 것을 확인하였다.

아니면 아래 명령어로 확인할 수 있다. 이 경우 (known after apply) 항목들이 설정되어 출력되는 것을 확인할 수 있다.

➜  learn-terraform-aws-instance git:(main) ✗ terraform show 
# aws_instance.app_server:
resource "aws_instance" "app_server" {
    ami                                  = "ami-013218fccb68a90d4"
    arn                                  = "arn:aws:ec2:ap-northeast-2:821547069268:instance/i-091f7a9dd8fddad20"
    associate_public_ip_address          = true
    availability_zone                    = "ap-northeast-2c"
    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-091f7a9dd8fddad20"
    instance_initiated_shutdown_behavior = "stop"
    instance_state                       = "running"
    instance_type                        = "t2.micro"
    ipv6_address_count                   = 0
    ipv6_addresses                       = []
    monitoring                           = false
    placement_partition_number           = 0
    primary_network_interface_id         = "eni-0b9b0de4e474365c0"
    private_dns                          = "ip-172-31-37-180.ap-northeast-2.compute.internal"
    private_ip                           = "172.31.37.180"
    public_dns                           = "ec2-43-200-182-88.ap-northeast-2.compute.amazonaws.com"
    public_ip                            = "43.200.182.88"
    secondary_private_ips                = []
    security_groups                      = [
        "default",
    ]
    source_dest_check                    = true
    subnet_id                            = "subnet-0a6e5d68d5704959a"
    tags                                 = {
        "Name" = "ExampleAppServerInstance"
    }
    tags_all                             = {
        "Name" = "ExampleAppServerInstance"
    }
    tenancy                              = "default"
    user_data_replace_on_change          = false
    vpc_security_group_ids               = [
        "sg-035ada28839083a01",
    ]

    capacity_reservation_specification {
        capacity_reservation_preference = "open"
    }

    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-0a020bc737e42d120"
        volume_size           = 8
        volume_type           = "gp2"
    }
}

6. 테라폼 설정 수정 및 적용

튜토리얼에서는 설정을 수정해서 적용 하는 방법도 나오는데 ami를 수정한뒤 다시 apply를 하면 된다. 나 같은 경우 ami-013218fccb68a90d4(AWS Linux) -> ami-09eba584c30b7299f(Ubunt)로 변경해서 테스트를 진행하였다.

➜  learn-terraform-aws-instance git:(main) ✗ terraform apply   
aws_instance.app_server: Refreshing state... [id=i-091f7a9dd8fddad20]

Terraform used the selected providers to generate the following execution plan. Resource actions are indicated with the following symbols:
-/+ destroy and then create replacement

Terraform will perform the following actions:

  # aws_instance.app_server must be replaced
-/+ resource "aws_instance" "app_server" {
      ~ ami                                  = "ami-013218fccb68a90d4" -> "ami-09eba584c30b7299f" # forces replacement
      ~ arn                                  = "arn:aws:ec2:ap-northeast-2:821547069268:instance/i-091f7a9dd8fddad20" -> (known after apply)
      ~ associate_public_ip_address          = true -> (known after apply)
      ~ availability_zone                    = "ap-northeast-2c" -> (known after apply)
      ~ cpu_core_count                       = 1 -> (known after apply)
      ~ cpu_threads_per_core                 = 1 -> (known after apply)
      ~ disable_api_stop                     = false -> (known after apply)
      ~ disable_api_termination              = false -> (known after apply)
      ~ ebs_optimized                        = false -> (known after apply)
      - hibernation                          = false -> null
      + host_id                              = (known after apply)
      + host_resource_group_arn              = (known after apply)
      + iam_instance_profile                 = (known after apply)
      ~ id                                   = "i-091f7a9dd8fddad20" -> (known after apply)
      ~ instance_initiated_shutdown_behavior = "stop" -> (known after apply)
      ~ instance_state                       = "running" -> (known after apply)
      ~ ipv6_address_count                   = 0 -> (known after apply)
      ~ ipv6_addresses                       = [] -> (known after apply)
      + key_name                             = (known after apply)
      ~ monitoring                           = false -> (known after apply)
      + outpost_arn                          = (known after apply)
      + password_data                        = (known after apply)
      + placement_group                      = (known after apply)
      ~ placement_partition_number           = 0 -> (known after apply)
      ~ primary_network_interface_id         = "eni-0b9b0de4e474365c0" -> (known after apply)
      ~ private_dns                          = "ip-172-31-37-180.ap-northeast-2.compute.internal" -> (known after apply)
      ~ private_ip                           = "172.31.37.180" -> (known after apply)
      ~ public_dns                           = "ec2-43-200-182-88.ap-northeast-2.compute.amazonaws.com" -> (known after apply)
      ~ public_ip                            = "43.200.182.88" -> (known after apply)
      ~ secondary_private_ips                = [] -> (known after apply)
      ~ security_groups                      = [
          - "default",
        ] -> (known after apply)
      ~ subnet_id                            = "subnet-0a6e5d68d5704959a" -> (known after apply)
        tags                                 = {
            "Name" = "ExampleAppServerInstance"
        }
      ~ tenancy                              = "default" -> (known after apply)
      + user_data                            = (known after apply)
      + user_data_base64                     = (known after apply)
      ~ vpc_security_group_ids               = [
          - "sg-035ada28839083a01",
        ] -> (known after apply)
        # (5 unchanged attributes hidden)

      ~ capacity_reservation_specification {
          ~ capacity_reservation_preference = "open" -> (known after apply)

          + capacity_reservation_target {
              + capacity_reservation_id                 = (known after apply)
              + capacity_reservation_resource_group_arn = (known after apply)
            }
        }

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

      + ebs_block_device {
          + delete_on_termination = (known after apply)
          + device_name           = (known after apply)
          + encrypted             = (known after apply)
          + iops                  = (known after apply)
          + kms_key_id            = (known after apply)
          + snapshot_id           = (known after apply)
          + tags                  = (known after apply)
          + throughput            = (known after apply)
          + volume_id             = (known after apply)
          + volume_size           = (known after apply)
          + volume_type           = (known after apply)
        }

      ~ enclave_options {
          ~ enabled = false -> (known after apply)
        }

      + ephemeral_block_device {
          + device_name  = (known after apply)
          + no_device    = (known after apply)
          + virtual_name = (known after apply)
        }

      ~ maintenance_options {
          ~ auto_recovery = "default" -> (known after apply)
        }

      ~ metadata_options {
          ~ http_endpoint               = "enabled" -> (known after apply)
          ~ http_put_response_hop_limit = 1 -> (known after apply)
          ~ http_tokens                 = "optional" -> (known after apply)
          ~ instance_metadata_tags      = "disabled" -> (known after apply)
        }

      + network_interface {
          + delete_on_termination = (known after apply)
          + device_index          = (known after apply)
          + network_card_index    = (known after apply)
          + network_interface_id  = (known after apply)
        }

      ~ private_dns_name_options {
          ~ enable_resource_name_dns_a_record    = false -> (known after apply)
          ~ enable_resource_name_dns_aaaa_record = false -> (known after apply)
          ~ hostname_type                        = "ip-name" -> (known after apply)
        }

      ~ root_block_device {
          ~ delete_on_termination = true -> (known after apply)
          ~ device_name           = "/dev/xvda" -> (known after apply)
          ~ encrypted             = false -> (known after apply)
          ~ iops                  = 100 -> (known after apply)
          + kms_key_id            = (known after apply)
          ~ tags                  = {} -> (known after apply)
          ~ throughput            = 0 -> (known after apply)
          ~ volume_id             = "vol-0a020bc737e42d120" -> (known after apply)
          ~ volume_size           = 8 -> (known after apply)
          ~ volume_type           = "gp2" -> (known after apply)
        }
    }

Plan: 1 to add, 0 to change, 1 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.app_server: Destroying... [id=i-091f7a9dd8fddad20]
aws_instance.app_server: Still destroying... [id=i-091f7a9dd8fddad20, 10s elapsed]
aws_instance.app_server: Still destroying... [id=i-091f7a9dd8fddad20, 20s elapsed]
aws_instance.app_server: Destruction complete after 29s
aws_instance.app_server: Creating...
aws_instance.app_server: Still creating... [10s elapsed]
aws_instance.app_server: Still creating... [20s elapsed]
aws_instance.app_server: Still creating... [30s elapsed]
aws_instance.app_server: Creation complete after 32s [id=i-05630624735e59ceb]

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

다시 apply를 하게 되면 기존 인스턴스가 삭제 된 이후 새로운 인스턴스가 생성되는 것을 확인할 수 있다. (🤔 롤링으로 배포해야 하는 경우에는 어떻게 해야하지..?)

7. 변경 확인

새로운 ami로 적용되서 잘 배포가 되었는지 확인하자. AWS Console에서도 확인하고 아래 명령어로도 다시 확인하였다.

➜  learn-terraform-aws-instance git:(main) ✗ terraform show      
# aws_instance.app_server:
resource "aws_instance" "app_server" {
    ami                                  = "ami-09eba584c30b7299f"
    arn                                  = "arn:aws:ec2:ap-northeast-2:821547069268:instance/i-05630624735e59ceb"
    associate_public_ip_address          = true
    availability_zone                    = "ap-northeast-2c"
    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-05630624735e59ceb"
    instance_initiated_shutdown_behavior = "stop"
    instance_state                       = "running"
    instance_type                        = "t2.micro"
    ipv6_address_count                   = 0
    ipv6_addresses                       = []
    monitoring                           = false
    placement_partition_number           = 0
    primary_network_interface_id         = "eni-0a87b1e13f84f37f0"
    private_dns                          = "ip-172-31-38-248.ap-northeast-2.compute.internal"
    private_ip                           = "172.31.38.248"
    public_dns                           = "ec2-43-201-98-26.ap-northeast-2.compute.amazonaws.com"
    public_ip                            = "43.201.98.26"
    secondary_private_ips                = []
    security_groups                      = [
        "default",
    ]
    source_dest_check                    = true
    subnet_id                            = "subnet-0a6e5d68d5704959a"
    tags                                 = {
        "Name" = "ExampleAppServerInstance"
    }
    tags_all                             = {
        "Name" = "ExampleAppServerInstance"
    }
    tenancy                              = "default"
    user_data_replace_on_change          = false
    vpc_security_group_ids               = [
        "sg-035ada28839083a01",
    ]

    capacity_reservation_specification {
        capacity_reservation_preference = "open"
    }

    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/sda1"
        encrypted             = false
        iops                  = 100
        tags                  = {}
        throughput            = 0
        volume_id             = "vol-0089c96189ac3bfe3"
        volume_size           = 8
        volume_type           = "gp2"
    }
}
➜  learn-terraform-aws-instance git:(main) ✗ terraform apply   
aws_instance.app_server: Refreshing state... [id=i-05630624735e59ceb]

No changes. Your infrastructure matches the configuration.

Terraform has compared your real infrastructure against your configuration and found no differences, so no changes are needed.

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

8. 테라폼 환경 파괴하기

해당 환경을 삭제하고자 한다면 다음 명령어로 파괴를 하면된다.

➜  learn-terraform-aws-instance git:(main) ✗ terraform destroy
aws_instance.app_server: Refreshing state... [id=i-05630624735e59ceb]

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.app_server will be destroyed
  - resource "aws_instance" "app_server" {
      - ami                                  = "ami-09eba584c30b7299f" -> null
      - arn                                  = "arn:aws:ec2:ap-northeast-2:821547069268:instance/i-05630624735e59ceb" -> null
      - associate_public_ip_address          = true -> null
      - availability_zone                    = "ap-northeast-2c" -> 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-05630624735e59ceb" -> 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
      - placement_partition_number           = 0 -> null
      - primary_network_interface_id         = "eni-0a87b1e13f84f37f0" -> null
      - private_dns                          = "ip-172-31-38-248.ap-northeast-2.compute.internal" -> null
      - private_ip                           = "172.31.38.248" -> null
      - public_dns                           = "ec2-43-201-98-26.ap-northeast-2.compute.amazonaws.com" -> null
      - public_ip                            = "43.201.98.26" -> null
      - secondary_private_ips                = [] -> null
      - security_groups                      = [
          - "default",
        ] -> null
      - source_dest_check                    = true -> null
      - subnet_id                            = "subnet-0a6e5d68d5704959a" -> null
      - tags                                 = {
          - "Name" = "ExampleAppServerInstance"
        } -> null
      - tags_all                             = {
          - "Name" = "ExampleAppServerInstance"
        } -> null
      - tenancy                              = "default" -> null
      - user_data_replace_on_change          = false -> null
      - vpc_security_group_ids               = [
          - "sg-035ada28839083a01",
        ] -> null

      - capacity_reservation_specification {
          - capacity_reservation_preference = "open" -> 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/sda1" -> null
          - encrypted             = false -> null
          - iops                  = 100 -> null
          - tags                  = {} -> null
          - throughput            = 0 -> null
          - volume_id             = "vol-0089c96189ac3bfe3" -> 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.app_server: Destroying... [id=i-05630624735e59ceb]
aws_instance.app_server: Still destroying... [id=i-05630624735e59ceb, 10s elapsed]
aws_instance.app_server: Still destroying... [id=i-05630624735e59ceb, 20s elapsed]
aws_instance.app_server: Destruction complete after 30s

Destroy complete! Resources: 1 destroyed.

마찬가지로 리소스를 파괴하는게 맞는지 확인하고 yes를 입력하면 실제 인스턴스들이 삭제 되는 것을 볼 수 있다.

이것으로 테라폼을 이용한 AWS 튜톨리얼을 완료하였다. 정말 간단하게 AWS 인스턴스를 띄우고 삭제할 수 있는것 같다.

이제 배운것을 바탕으로 쿠버네티스 학습 환경을 구성하면 될것 같다. 튜토리얼이라 코드는 필요 없을것 같지만.. 혹시나 필요한 사람들을 위해서 레포도 공유해본다.

참조

Loading script...