29. Terraform을 사용하여 S3에서 백업 삭제

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

Source: Dev.to

S3에서 Terraform을 사용해 백업 삭제하기 (29) 커버 이미지

Thu Kha Kyawe

Source:

실험실 정보

Nautilus DevOps 팀은 현재 정리 작업을 진행 중이며, AWS 계정에서 불필요한 데이터와 서비스를 제거하는 데 집중하고 있습니다. 마이그레이션 과정에서 일회성으로 사용하기 위해 여러 리소스를 생성했으며, 이를 정리하여 AWS 환경을 최적화하려고 합니다.

  • nautilus-bck-29479 라는 이름의 S3 버킷이 이미 존재합니다.

작업

  1. nautilus-bck-29479 S3 버킷의 내용을 terraform-client 호스트(이 실험실을 로드하면 접속되는 랜딩 호스트)의 /opt/s3-backup/ 디렉터리로 복사합니다.
  2. S3 버킷 nautilus-bck-29479 를 삭제합니다.
  3. Terraform를 통해 AWS CLI 를 사용하여 위 작업을 수행합니다(예: Terraform 안에서 AWS CLI 명령을 실행).
    • Terraform 작업 디렉터리는 /home/bob/terraform 입니다.
    • main.tf 파일을 업데이트 합니다(별도의 .tf 파일을 만들지 않습니다).

참고: VS Code의 EXPLORER 섹션에서 마우스 오른쪽 버튼을 클릭하고 Open in Integrated Terminal을 선택하여 터미널을 실행합니다.

Lab Solutions

Step 1 – Create Main Terraform Configuration

# main.tf

# Execute AWS CLI commands to copy and delete the S3 bucket
resource "null_resource" "s3_cleanup" {
  provisioner "local-exec" {
    command = <<EOT
      echo "Creating backup directory..."
      mkdir -p /opt/s3-backup/

      echo "Copying contents from S3 bucket to local directory..."
      aws s3 cp s3://nautilus-bck-29479 /opt/s3-backup/ --recursive

      echo "Deleting the S3 bucket..."
      aws s3 rb s3://nautilus-bck-29479 --force
    EOT
  }
}

Step 2 – Deploy the Configuration

2.1 Terraform 디렉터리로 이동

cd /home/bob/terraform

2.2 Terraform 초기화

terraform init

Output

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.

2.3 배포 계획을 실행해 구성 확인

terraform plan

Output

bob@iac-server ~/terraform via 💠 default ➜  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:

  # null_resource.s3_cleanup will be created
  + resource "null_resource" "s3_cleanup" {
      + id = (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.4 구성 적용

terraform apply

프롬프트가 나타나면 yes 를 입력하여 확인합니다.

Output

bob@iac-server ~/terraform via 💠 default ➜  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:

  # null_resource.s3_cleanup will be created
  + resource "null_resource" "s3_cleanup" {
      + id = (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

null_resource.s3_cleanup: Creating...
null_resource.s3_cleanup: Provisioning with 'local-exec'...
null_resource.s3_cleanup (local-exec): Executing: ["/bin/sh" "-c" "      echo \"Creating backup directory...\"\n      mkdir -p /opt/s3-backup/\n\n      echo \"Copying contents from S3 bucket to local directory...\"\n      aws s3 cp s3://nautilus-bck-29479 /opt/s3-backup/ --recursive\n\n      echo \"Deleting the S3 bucket...\"\n      aws s3 rb s3://nautilus-bck-29479 --force\n"]
null_resource.s3_cleanup (local-exec): Creating backup directory...
null_resource.s3_cleanup (local-exec): Copying contents from S3 bucket to local directory...
null_resource.s3_cleanup (local-exec): Deleting the S3 bucket...
null_resource.s3_cleanup: Creation complete after 3s [id=123456]

7890]

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

**Result:** The S3 bucket `nautilus-bck-29479` has been backed up to `/opt/s3-backup/` and then removed, all orchestrated via Terraform.
_cleanup (local-exec): Completed 27 Bytes/27 Bytes (2.7 KiB/s) with 1 file(s) remaining
null_resource.s3_cleanup (local-exec): download: s3://nautilus-bck-29479/nautilus.txt to ../../../opt/s3-backup/nautilus.txt
null_resource.s3_cleanup (local-exec): Deleting the S3 bucket...
null_resource.s3_cleanup (local-exec): delete: s3://nautilus-bck-29479/nautilus.txt
null_resource.s3_cleanup (local-exec): remove_bucket: nautilus-bck-29479
null_resource.s3_cleanup: Creation complete after 1s [id=4571548781870379384]

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

리소스 및 다음 단계

크레딧

  • 모든 실습은 다음에서 제공됩니다: KodeKloud
  • 이 귀중한 자료들을 제공해 주셔서 진심으로 감사드립니다.
Back to Blog

관련 글

더 보기 »

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

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