30. Terraform을 사용하여 EC2 인스턴스 삭제

발행: (2026년 1월 31일 오후 03:30 GMT+9)
7 min read
원문: Dev.to

Source: Dev.to

30. Terraform을 사용하여 EC2 인스턴스 삭제하기 커버 이미지

Thu Kha Kyawe

Lab Information

마이그레이션 과정에서 AWS 계정 아래에 여러 리소스가 생성되었습니다. 현재는 더 이상 필요하지 않은 테스트 리소스가 일부 있으므로 일시적으로 정리해야 합니다. 그 중 사용되지 않는 인스턴스가 하나 있어 삭제해야 합니다.

  1. Terraform을 사용하여 us-east-1 리전에서 datacenter-ec2 라는 이름의 EC2 인스턴스를 삭제합니다. 프로비저닝 코드는 보관해 두세요. 나중에 이 인스턴스를 다시 프로비저닝해야 할 수도 있습니다.
  2. 작업을 제출하기 전에 인스턴스가 terminated 상태인지 확인하세요.

Terraform 작업 디렉터리는 /home/bob/terraform 입니다.

Note: VS Code의 EXPLORER 섹션에서 오른쪽 클릭 후 Open in Integrated Terminal을 선택하여 터미널을 실행합니다.

실험실 솔루션

단계 1 – 메인 Terraform 구성 확인

# main.tf

# Provision EC2 instance
resource "aws_instance" "ec2" {
  ami           = "ami-0c101f26f147fa7fd"
  instance_type = "t2.micro"
  vpc_security_group_ids = [
    "sg-4e8e273eca9981051"
  ]

  tags = {
    Name = "datacenter-ec2"
  }
}

단계 2 – 이 구성 배포

Terraform 디렉터리로 이동

cd /home/bob/terraform

Terraform 초기화

terraform init

출력

bob@iac-server ~/terraform via 💠 default ➜  terraform init
Initializing the backend...
Initializing provider plugins...
- Finding hashicorp/aws versions matching "5.91.0"...
- Installing hashicorp/aws v5.91.0...
- Installed hashicorp/aws v5.91.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.

구성 파괴

terraform destroy

프롬프트가 표시되면, 파괴를 확인하기 위해 yes를 입력하세요.

출력

bob@iac-server ~/terraform via 💠 default ➜  terraform destroy
aws_instance.ec2: Refreshing state... [id=i-5e6bb7fd83c9f0057]

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.ec2 will be destroyed
  - resource "aws_instance" "ec2" {
      - ami                                  = "ami-0c101f26f147fa7fd" -> null
      - arn                                  = "arn:aws:ec2:us-east-1::instance/i-5e6bb7fd83c9f0057" -> null
      - associate_public_ip_address          = true -> null
      - availability_zone                    = "us-east-1a" -> 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-5e6bb7fd83c9f0057" -> 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-c31c4e92a1acbff85" -> null
      - private_dns                          = "ip-10-53-157-57.ec2.internal" -> null
      - private_ip                           = "10.53.157.57" -> null
      - public_dns                           = "ec2-54-214-90-237.compute-1.amazonaws.com" -> null
      - public_ip                            = "54.214.90.237" -> null
      - secondary_private_ips                = [] -> null
      - security_groups                      = [
          - "default",
        ] -> null
      - source_dest_check                    = true -> null
      - subnet_id                            = "subnet-41298989f52a321cc" -> null
      - tags                                 = {
          - "Name" = "datacenter-ec2"
        } -> null
      - tags_all                             = 
{
          - "Name" = "datacenter-ec2"
        } -> null
      - tenancy                              = "default" -> null
      - user_data_replace_on_change          = false -> null
      - vpc_security_group_ids               = [
          - "sg-4e8e273eca9981051"
        ] -> null
    }

Plan: 삭제 1개, 추가 0개, 변경 0개.

Do you really want to destroy all resources?
  Terraform은 위에 표시된 대로 관리되는 모든 인프라를 삭제합니다.
  복구할 수 없습니다. 확인하려면 'yes'만 입력할 수 있습니다.

  Enter a value: yes

aws_instance.ec2: Destroying... [id=i-5e6bb7fd83c9f0057]
aws_instance.ec2: Destruction complete after 1s

Destroy complete! 리소스: 1개 삭제됨.

EC2 인스턴스 datacenter-ec2가 이제 종료되었으며, Terraform 구성 파일은 향후 프로비저닝을 위해 그대로 유지됩니다.

  = [
    - "sg-4e8e273eca9981051",
  ] -> null
  # (8 unchanged attributes hidden)

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

  - root_block_device {
      - delete_on_termination = true -> null
      - device_name           = "/dev/sda1" -> null
      - encrypted             = false -> null
      - iops                  = 0 -> null
      - tags                  = {} -> null
      - tags_all              = {} -> null
      - throughput            = 0 -> null
      - volume_id             = "vol-aecbbe533be995fe4" -> null
      - volume_size           = 8 -> null
      - volume_type           = "gp2" -> null
        # (1 unchanged attribute hidden)
    }
}

계획: 추가 0개, 변경 0개, 삭제 1개.

Do you really want to destroy all resources?
Terraform은 위에 표시된 대로 관리되는 모든 인프라를 삭제합니다.
복구할 수 없습니다. 확인하려면 'yes'만 입력할 수 있습니다.

Enter a value: yes
aws_instance.ec2: Destroying... [id=i-5e6bb7fd83c9f0057]
aws_instance.ec2: Still destroying... [id=i-5e6bb7fd83c9f0057, 10s elapsed]
aws_instance.ec2: Destruction complete after 10s

Destroy complete! 리소스: 1개 삭제됨.

리소스 및 다음 단계

크레딧

  • 모든 실습은 다음에서 제공: KodeKloud
  • 이 귀중한 리소스를 제공해 주셔서 진심으로 감사드립니다.
Back to Blog

관련 글

더 보기 »

34. Terraform을 사용하여 S3에 데이터 복사

Lab Information 나우틸러스 DevOps 팀은 현재 데이터 마이그레이션을 수행하고 있으며, 온프레미스 스토리지 시스템에서 AWS S3 버킷으로 데이터를 이동하고 있습니다. They have rece...