Ja Kwa
Ja Kwa

Reputation: 41

RDS not reachable when created with terraform

I've been trying to create RDS instance using terraform. The problem that I've been strugling with is that every time I create new instance, it's not reachable. I'm creating it in subnets group containing public and private subnets, security group has rule allowing access from my IP, there is internet gateway in this vpc. The strangest thing is that to fix that, I just need to change instance class using AWS console to any other, f.e. from db.t2.small to db.t2.micro and it suddenly starts working. Here is fragment of my code:

resource "aws_db_subnet_group" "dbSubnetGroup" {
  name       = "${var.prefix}-db-subnet-group"
  subnet_ids = concat(aws_subnet.publicSubnet.*.id, aws_subnet.privateSubnet.*.id)

  tags = var.defaultTags
}

resource "aws_security_group" "rdsSecurityGroup" {
  name   = "${var.prefix}-rds-sg"
  vpc_id = aws_vpc.vpc.id

  ingress {
    from_port       = 1433
    to_port         = 1433
    protocol        = "tcp"
    security_groups = [aws_eks_cluster.eksCluster.vpc_config[0].cluster_security_group_id]
  }
  ingress {
    from_port        = 1433
    to_port          = 1433
    protocol         = "tcp"
    cidr_blocks      = [var.myIP]
  }

  egress {
    from_port        = 0
    to_port          = 0
    protocol         = "-1"
    cidr_blocks      = ["0.0.0.0/0"]
    ipv6_cidr_blocks = ["::/0"]
  }
  tags = var.defaultTags
}

resource "random_password" "rdsPassword" {
  length           = 32
  special          = true
  override_special = "!#$%&*()-_=+[]{}<>:?"
}

resource "aws_db_instance" "dbInstance" {
  allocated_storage               = 20
  storage_type                    = "gp2"
  engine                          = var.dbInstanceEngine
  license_model                   = "license-included"
  instance_class                  = var.dbInstanceType
  identifier                      = "${var.prefix}-db-instance"
  username                        = var.dbUserName
  password                        = random_password.rdsPassword.result
  tags                            = var.defaultTags
  db_subnet_group_name            = aws_db_subnet_group.dbSubnetGroup.name
  vpc_security_group_ids          = [aws_security_group.rdsSecurityGroup.id]
  skip_final_snapshot             = true
  allow_major_version_upgrade     = true
  copy_tags_to_snapshot           = true
  performance_insights_enabled    = true
  max_allocated_storage           = 1000
  enabled_cloudwatch_logs_exports = ["error"]
  publicly_accessible             = true
}

Am I doing something wrong or can it be a bug in aws provider?

Upvotes: 2

Views: 832

Answers (1)

Chris Williams
Chris Williams

Reputation: 35146

If you want RDS to be connectable, the DB subnet group must be in public subnets only

Upvotes: 1

Related Questions