Setting Up a Google Cloud SQL Instance with Terraform
When deploying a Google Cloud SQL instance, especially in a multi-project environment, you may encounter networking issues. This article provides a Terraform configuration example and troubleshooting steps for the SERVICE_NETWORKING_NOT_ENABLED error.
Overview
In this scenario, you are trying to replicate a SQL instance in Google Cloud Platform (GCP) that is associated with a secondary project's network. The active instance has a public IP, and the subnets from the secondary project are shared with the project hosting the SQL instance.
Common Error
While configuring your SQL instance, you might face the following error:
Error: Error, failed to create instance xxxx: googleapi: Error 400: Invalid request: Incorrect Service Networking config for instance: xxxx:xxxxx:SERVICE_NETWORKING_NOT_ENABLED., invalid
This error typically indicates that the Service Networking API is not enabled for your project.
Terraform Configuration Example
Here’s a sample Terraform configuration for creating a Google Cloud SQL instance:
resource "google_sql_database_instance" "cloudsql-instance-qa" {
depends_on = [google_project_service.project_apis]
database_version = "MYSQL_5_7"
name = "${var.env_shorthand}-${var.resource_name}"
project = var.project_id
region = var.region
settings {
activation_policy = "ALWAYS"
availability_type = "ZONAL"
backup_configuration {
binary_log_enabled = true
enabled = true
point_in_time_recovery_enabled = false
start_time = "15:00"
}
crash_safe_replication = false
disk_autoresize = true
disk_size = 5003
disk_type = "PD_SSD"
ip_configuration {
ipv4_enabled = true
private_network = "projects/gcp-backend/global/networks/default"
require_ssl = false
}
location_preference {
zone = var.zone
}
maintenance_window {
day = "7"
hour = "4"
}
pricing_plan = "PER_USE"
replication_type = "SYNCHRONOUS"
tier = "db-n1-standard-1"
}
}
Important Notes
Enable Service Networking API: Ensure that the Service Networking API is enabled for your project. You can do this using the Google Cloud Console, the
gcloudcommand-line tool, or through Terraform.- Using gcloud CLI:
gcloud services enable servicenetworking.googleapis.com --project=<gcp_project_id> - Using Terraform:
resource "google_project_service" "enable_google_apis" { project = var.project_id service = "servicenetworking.googleapis.com" }
- Using gcloud CLI:
Check Network Configuration: Verify that the
private_networksetting in yourip_configurationblock is correctly pointing to the shared network.
Conclusion
By following the above configuration and ensuring that the necessary APIs are enabled, you should be able to successfully create a Google Cloud SQL instance without encountering the SERVICE_NETWORKING_NOT_ENABLED error. If issues persist, consider reviewing your project permissions and network settings.