[Terraform] s3 버킷 강제 삭제

KKK·2023년 4월 26일
0

테라폼

목록 보기
12/12
post-thumbnail

s3에 파일이 있어 테라폼으로 삭제가 안되는 경우, s3를 수작업으로 비우지 않고 테라폼만으로 버킷을 비우고 강제 삭제하는 방법

강제 삭제된 버킷은 다시 복구할 수 없으니 신중하게 삭제해야 합니다.

현재 버킷 내에 테라폼 상태 파일이 있어 테라폼으로 삭제를 하려고하면 되지 않습니다.

$ terraform destroy
...
aws_s3_bucket.tfstate_s3: Destroying... [id=terraform-hb-backend]
╷
│ Error: deleting Amazon S3 (Simple Storage) Bucket (terraform-hb-backend): BucketNotEmpty: The bucket you tried to delete is not empty. You must delete all versions in the bucket.
│       status code: 409, request id: Q0Z80G8CEHTH7DK2, host id: 4PUlf5hhUDKLxsQzUdelyxMVCY8FUcJJGpONW7mkVveq7A0KqG9OtjKyoINfBKcFEhy5moobZ+k=

삭제

파일이 존재하는 버킷은 테라폼 파일을 수정하여 삭제할 수 있습니다.

  1. 강제 삭제 옵션을 false에서 true로 변경
  2. 변경 사항을 apply 하여 .tfstate 파일에 반영
  3. terraform destroy

현재 s3.tf 파일입니다.

resource "aws_s3_bucket" "tfstate_s3" {
    bucket = "terraform-hb-backend"
    force_destroy = true  // 추가
}

resource "aws_s3_bucket_versioning" "tfstate_s3_versioning" {
    bucket = aws_s3_bucket.tfstate_s3.id
    
    versioning_configuration {
      status = "Enabled"
    }
}

force_destroy 값을 false에서 true(기본 false)로 변경하고 apply 후 destroy 해줍니다.

$ terraform destroy
...
aws_s3_bucket_versioning.tfstate_s3_versioning: Destroying... [id=terraform-hb-backend]
aws_s3_bucket_versioning.tfstate_s3_versioning: Destruction complete after 1s
aws_s3_bucket.tfstate_s3: Destroying... [id=terraform-hb-backend]
aws_s3_bucket.tfstate_s3: Destruction complete after 1s

Destroy complete! Resources: 2 destroyed.

destroy로 삭제되지 않던 버킷이 삭제되어 없어진 걸 확인할 수 있습니다.

AWS 콘솔에서도 없어진 걸 확인할 수 있습니다.

0개의 댓글