Terraform으로 Mysql DB Instance 생성 시도. 그러나 계속해서 에러 발생.

⚠️

Error Message

aws_db_instance.example: Creating… │ Error: creating RDS DB Instance (terraform-db20240505074947525100000001): InvalidVPCNetworkStateFault: The VPC vpc-05819890763cddf88 associated with the default subnet group does not exist. Please delete the default subnet group or specify another subnet group. │ status code: 400, request id: 84afb05a-bd40-422c-9e62-958154a568c0 │ │ with aws_db_instance.example, │ on main.tf line 25, in resource “aws_db_instance” “example”: │ 25: resource “aws_db_instance” “example” {

몇번이고 잘 돌아가던 코드였으나 오늘은 저렇게 에러를 뱉고 있다. 일단 로그에서 확인된 VPC는 존재하지 않는 VPC라는 점. 아마도 로그에 잡힌 VPC ID는 팀원 중 한분이 삭제했을 기존의 Default VPC로 추측되고, 오늘보니 Default VPC가 없길래 내가 직접 생성했었는데 아마 이 때 부터 존재하지 않는 VPC를 참조하고 있는 것으로 보여진다.

아무튼 테라폼이 이를 인지하지 못하고 state와 꼬여버린 문제인가 싶어 모든 리소스 destroy 진행, state 파일 삭제. 그래도 해결이 안돼서 “.terraform” 디렉터리 삭제, 백엔드 상태파일 저장소였던 S3 버킷까지 삭제 등 더 이상 할 수 있는 조치가 없었음에도 apply 결과는 동일했다.

찾아보니 나와 동일한 문제를 겪은 사람들이 여럿 보이긴 했다. 그러나 그 글들에도 명쾌한 해답이 없었다. 기나긴 삽질 결과 결국 혼자 해결한 방법은 매개변수 db_subnet_group_name를 명시적으로 설정하는 것이었다. 자꾸만 존재하지 않는 Default VPC를 참조하던 현상은 여전히 이해가 되지 않았지만, 아마도 이것이 사람들이 말하는 테라폼의 미흡한 부분이 아닐까하는 생각이 들었다.

전체적인 방법을 간략하게 기록해두자면 다음과 같다.

data "aws_vpc" "default" {
  default = true
}

data "aws_subnets" "default" {
  filter {
    name   = "vpc-id"
    values = [data.aws_vpc.default.id]
  }
}

resource "aws_db_subnet_group" "example" {
  name        = "example-subnet-group"
  subnet_ids  = data.aws_subnets.default.ids # 예제 서브넷 ID들

  tags = {
    Name = "My DB subnet group"
  }
}

resource "aws_db_instance" "example" {
  db_subnet_group_name = aws_db_subnet_group.example.name
  identifier_prefix   = "terraform-db"
  engine              = "mysql"
  allocated_storage   = 10            # 스토리지 10 GB
  instance_class      = "db.t3.micro" # 1 CPU, 1 GB Memory
  db_name             = "example_database"
  username            = "admin"
  ...
}

📌 문제 해결 후 기록을 위해 정리하다보니 나와 같은 증상, 나와 동일한 문제를 겪는 포스팅이 추가로 확인 되었는데, 여기서 말하고있는 해결방법은 내가 한 방법과 동일했다. 지금으로써는 이 방법이 최선이긴 한가보다. https://github.com/hashicorp/terraform-provider-aws/issues/4318

https://github.com/hashicorp/terraform-provider-aws/issues/4318