Setup private IP's for Cloud SQL instances

The other day we wanted to set up private IP’s for all our GCP Cloud SQL instances. The Terraform Google documentation explains to you how you can set this up quickly. However, it doesn’t mention how to handle the situation when you have two flavors of Cloud SQL instances running (MySQL and Postgresql). So when I started to provision the IP’s, it worked out perfectly for all our Postgresql instances. But by the time I wanted to provision private IP’s for our MySQL instances, we ran into errors.

Even when trying to assign a private IP through the GCP console interface, I ran into issues. Luckily it gave me a more decent error message than the one I received from Terraform

Image of the error we received in GCloud Console

I couldn’t understand this issue at first since we’ve used a /24 prefix we should have more than plenty of available IP’s left. It was until I read the documentation of setting up private service access documentation on GCP until it starts making more sense to me why this couldn’t be working.

Having a better understanding of Google’s private service access, I figured out the MySQL instances are probably running on a different dedicated VPC and not together with the Postgresql instances. Hence we need another IP range to assign IP’s from to the MySQL VPC Peering connection.

So we did create a new IP range:

resource "google_compute_global_address" "cloud-sql-mysql-private-ip-address" {
  provider = "google-beta"
  project = google_project.project_name.project_id
  name = "cloud-sql-mysql-private-ip-address"
  purpose = "VPC_PEERING"
  address_type = "INTERNAL"
  prefix_length = 24
  network = google_compute_network.network.self_link
}

And finally add the new range to the google_service_networking_connection which I’ve created before to use with the Postgresql instances like explained in the example of the Terraform documentation

resource "google_service_networking_connection" "private_cloud_sql_vpc_connection" {
  provider = "google-beta"

  network = google_compute_network.network.self_link
  service = "servicenetworking.googleapis.com"
  reserved_peering_ranges = [google_compute_global_address.cloud-sql-private-ip-address.name]
  network = google_compute_network.network.self_link
  service = "servicenetworking.googleapis.com"
  reserved_peering_ranges = [
    google_compute_global_address.cloud-sql-private-ip-address.name,
    google_compute_global_address.cloud-sql-mysql-private-ip-address.name
  ]
}

Once you configured these changes with Terraform you will see the private service connection cloudsql-mysql-googleapis-com when you examine your VPC network under the Private service connection tab.

Example how the final peering connections look like