Search code examples
mysqlamazon-web-servicesamazon-route53rdsterraform

Creating a Route53 entry for RDS using Terraform


I am attempting to create a Route53 entry for a MySQL RDS instance but having issues with the :3306 at the end of the RDS endpoint returned from Terraform.

    resource "aws_db_instance" "mydb" {
     allocated_storage    = 10
     engine               = "mysql"
     engine_version       = "5.6.17"
     instance_class       = "db.t2.micro"
     name                 = "mydb"
     username             = "foo"
     password             = "bar"
     db_subnet_group_name = "my_database_subnet_group"
     parameter_group_name = "default.mysql5.6"
   }

   resource "aws_route53_record" "database" {
      zone_id = "${aws_route53_zone.primary.zone_id}"
      name = "database.example.com"
      type = "CNAME"
      ttl = "300"
      records = ["${aws_db_instance.default.endpoint}"]
   }

Terraform puts a :3306 at the end of the endpoint and that gets entered into the Route53 Value of the CNAME.

When I then try to connect to the CNAME database.example.com with the MySQL client I get:

    ERROR 2005 (HY000): Unknown MySQL server host 'database.example.com' (0)

Once I remove the :3306 via the AWS route53 console It seems work just fine.

Question is: How do I strip the :3306 from the Terraform RDS endpoint


Solution

  • As well as an endpoint output, Terraform's aws_db_instance resource also outputs address that provides the FQDN of the instance.

    So all you need to do is change your aws_route53_record resource to use address instead:

    resource "aws_db_instance" "mydb" {
      allocated_storage    = 10
      engine               = "mysql"
      engine_version       = "5.6.17"
      instance_class       = "db.t2.micro"
      name                 = "mydb"
      username             = "foo"
      password             = "bar"
      db_subnet_group_name = "my_database_subnet_group"
      parameter_group_name = "default.mysql5.6"
    }
    
    resource "aws_route53_record" "database" {
      zone_id = "${aws_route53_zone.primary.zone_id}"
      name = "database.example.com"
      type = "CNAME"
      ttl = "300"
      records = ["${aws_db_instance.mydb.address}"]
    }