Cloud SQL Infrastructure as Code
Cloud SQL resources can be provisioned and managed using Terraform and other IaC tools.
Terraform
The Google Cloud Terraform provider supports Cloud SQL instances, databases, and users.
Cloud SQL Instance Example
resource "google_sql_database_instance" "default" {
name = "master-instance"
region = "us-central1"
database_version = "POSTGRES_18"
deletion_protection = false # Set to true for production to prevent accidental destruction
settings {
tier = "db-custom-1-3840"
edition = "ENTERPRISE"
# Required database flag to enable IAM database authentication
database_flags {
name = "cloudsql.iam_authentication"
value = "on"
}
backup_configuration {
enabled = true
point_in_time_recovery_enabled = true
}
}
}
resource "google_sql_database" "database" {
name = "my-database"
instance = google_sql_database_instance.default.name
}
# IAM Database Authentication (Requires cloudsql.iam_authentication = "on" database flag)
resource "google_sql_user" "iam_user" {
name = "user-email@example.com"
instance = google_sql_database_instance.default.name
type = "CLOUD_IAM_USER"
}Key Terraform Configuration Notes
- IAM Database Authentication Flag: Enabling IAM Database Authentication
requires setting the database flag
cloudsql.iam_authentication = "on"(for PostgreSQL) orcloudsql_iam_authentication = "on"(for MySQL) inside thesettings.database_flagsblock. The user or service account must also be granted theroles/cloudsql.instanceUserIAM role. - Deletion Protection: By default, the Terraform Google provider sets
deletion_protection = true. Setdeletion_protection = falsein dev/test environments if you intend to runterraform destroy. - Point-in-Time Recovery (PITR): Setting
enabled = trueinbackup_configurationenables automated daily backups. Explicitly setpoint_in_time_recovery_enabled = trueto enable continuous WAL archiving for PITR. - Edition Selection: Explicitly declare
edition = "ENTERPRISE"oredition = "ENTERPRISE_PLUS"insidesettingsto define the feature set and SLA level.