| subcategory | description |
|---|---|
Cloud SQL |
Creates a new SQL database instance in Google Cloud SQL. |
Creates a new Google SQL Database Instance. For more information, see the official documentation, or the JSON API.
~> NOTE on google_sql_database_instance: - Second-generation instances include a
default 'root'@'%' user with no password. This user will be deleted by Terraform on
instance creation. You should use google_sql_user to define a custom user with
a restricted host and strong password.
-> Note: On newer versions of the provider, you must explicitly set deletion_protection=false
(and run terraform apply to write the field to state) in order to destroy an instance.
It is recommended to not set this field (or set it to true) until you're ready to destroy the instance and its databases.
resource "google_sql_database_instance" "main" {
name = "main-instance"
database_version = "POSTGRES_15"
region = "us-central1"
settings {
# Second-generation instance tiers are based on the machine
# type. See argument reference below.
tier = "db-f1-micro"
}
}resource "google_compute_instance" "apps" {
count = 8
name = "apps-${count.index + 1}"
machine_type = "f1-micro"
boot_disk {
initialize_params {
image = "ubuntu-os-cloud/ubuntu-1804-lts"
}
}
network_interface {
network = "default"
access_config {
// Ephemeral IP
}
}
}
resource "random_id" "db_name_suffix" {
byte_length = 4
}
locals {
onprem = ["192.168.1.2", "192.168.2.3"]
}
resource "google_sql_database_instance" "postgres" {
name = "postgres-instance-${random_id.db_name_suffix.hex}"
database_version = "POSTGRES_15"
settings {
tier = "db-f1-micro"
ip_configuration {
dynamic "authorized_networks" {
for_each = google_compute_instance.apps
iterator = apps
content {
name = apps.value.name
value = apps.value.network_interface.0.access_config.0.nat_ip
}
}
dynamic "authorized_networks" {
for_each = local.onprem
iterator = onprem
content {
name = "onprem-${onprem.key}"
value = onprem.value
}
}
}
}
}~> NOTE: For private IP instance setup, note that the google_sql_database_instance does not actually interpolate values from google_service_networking_connection. You must explicitly add a depends_onreference as shown below.
resource "google_compute_network" "private_network" {
provider = google-beta
name = "private-network"
}
resource "google_compute_global_address" "private_ip_address" {
provider = google-beta
name = "private-ip-address"
purpose = "VPC_PEERING"
address_type = "INTERNAL"
prefix_length = 16
network = google_compute_network.private_network.id
}
resource "google_service_networking_connection" "private_vpc_connection" {
provider = google-beta
network = google_compute_network.private_network.id
service = "servicenetworking.googleapis.com"
reserved_peering_ranges = [google_compute_global_address.private_ip_address.name]
}
resource "random_id" "db_name_suffix" {
byte_length = 4
}
resource "google_sql_database_instance" "instance" {
provider = google-beta
name = "private-instance-${random_id.db_name_suffix.hex}"
region = "us-central1"
database_version = "MYSQL_5_7"
depends_on = [google_service_networking_connection.private_vpc_connection]
settings {
tier = "db-f1-micro"
ip_configuration {
ipv4_enabled = false
private_network = google_compute_network.private_network.self_link
enable_private_path_for_google_cloud_services = true
}
}
}
provider "google-beta" {
region = "us-central1"
zone = "us-central1-a"
}resource "google_sql_database_instance" "main" {
name = "enterprise-plus-main-instance"
database_version = "MYSQL_8_0_31"
settings {
tier = "db-perf-optimized-N-2"
edition = "ENTERPRISE_PLUS"
data_cache_config {
data_cache_enabled = true
}
}
}resource "google_sql_database_instance" "instance" {
name = "mcp-enabled-main-instance"
region = "us-central1"
database_version = "POSTGRES_16"
settings {
tier = "db-perf-optimized-N-2"
edition = "ENTERPRISE_PLUS"
connection_pool_config {
connection_pooling_enabled = true
flags {
name = "max_client_connections"
value = "1980"
}
}
}
}resource "google_sql_database_instance" "main" {
name = "psc-enabled-main-instance"
database_version = "MYSQL_8_0"
settings {
tier = "db-f1-micro"
ip_configuration {
psc_config {
psc_enabled = true
allowed_consumer_projects = ["allowed-consumer-project-name"]
}
ipv4_enabled = false
}
backup_configuration {
enabled = true
binary_log_enabled = true
}
availability_type = "REGIONAL"
}
}resource "google_sql_database_instance" "main" {
name = "psc-enabled-main-instance"
database_version = "MYSQL_8_0"
settings {
tier = "db-f1-micro"
ip_configuration {
psc_config {
psc_enabled = true
allowed_consumer_projects = ["allowed-consumer-project-name"]
psc_auto_connections {
consumer_network = "network-name"
consumer_service_project_id = "project-id"
}
}
ipv4_enabled = false
}
backup_configuration {
enabled = true
binary_log_enabled = true
}
availability_type = "REGIONAL"
}
}resource "google_sql_database_instance" "main" {
name = "psc-enabled-main-instance"
database_version = "MYSQL_8_0"
settings {
tier = "db-f1-micro"
ip_configuration {
psc_config {
psc_enabled = true
allowed_consumer_projects = ["allowed-consumer-project-name"]
network_attachment_uri = "network-attachment-uri"
}
ipv4_enabled = false
}
backup_configuration {
enabled = true
binary_log_enabled = true
}
availability_type = "REGIONAL"
}
}~> NOTE: For restoring from a backupdr_backup, note that the backup must be in active state. List down the backups using google_backup_dr_backup. Replace backupdr_backup_full_path with the backup name.
resource "google_sql_database_instance" "instance" {
name = "main-instance"
database_version = "MYSQL_8_0"
settings {
tier = "db-f1-micro"
backup_configuration {
enabled = true
binary_log_enabled = true
}
}
backupdr_backup = "backupdr_backup_full_path"
}~> NOTE: Replace backupdr_datasource with the full datasource path, time_stamp should be in the format of YYYY-MM-DDTHH:MM:SSZ.
resource "google_sql_database_instance" "instance" {
name = "main-instance"
database_version = "MYSQL_8_0"
settings {
tier = "db-f1-micro"
backup_configuration {
enabled = true
binary_log_enabled = true
}
}
point_in_time_restore_context {
datasource = "backupdr_datasource"
target_instance = "target_instance_name"
point_in_time = "time_stamp"
}
}The following arguments are supported:
region- (Optional) The region the instance will sit in. If a region is not provided in the resource definition, the provider region will be used instead.
-
settings- (Optional) The settings to use for the database. The configuration is detailed below. Required ifcloneis not set. -
database_version- (Required) The MySQL, PostgreSQL or SQL Server version to use. Supported values includeMYSQL_5_6,MYSQL_5_7,MYSQL_8_0,MYSQL_8_4,POSTGRES_9_6,POSTGRES_10,POSTGRES_11,POSTGRES_12,POSTGRES_13,POSTGRES_14,POSTGRES_15,POSTGRES_16,POSTGRES_17,SQLSERVER_2017_STANDARD,SQLSERVER_2017_ENTERPRISE,SQLSERVER_2017_EXPRESS,SQLSERVER_2017_WEB.SQLSERVER_2019_STANDARD,SQLSERVER_2019_ENTERPRISE,SQLSERVER_2019_EXPRESS,SQLSERVER_2019_WEB. Database Version Policies includes an up-to-date reference of supported versions. -
name- (Optional, Computed) The name of the instance. If the name is left blank, Terraform will randomly generate one when the instance is first created. This is done because after a name is used, it cannot be reused for up to one week. -
maintenance_version- (Optional) The current software version on the instance. This attribute can not be set during creation. Refer toavailable_maintenance_versionsattribute to see whatmaintenance_versionare available for upgrade. When this attribute gets updated, it will cause an instance restart. Setting amaintenance_versionvalue that is older than the current one on the instance will be ignored. -
master_instance_name- (Optional) The name of the existing instance that will act as the master in the replication setup. Note, this requires the master to havebinary_log_enabledset, as well as existing backups. -
project- (Optional) The ID of the project in which the resource belongs. If it is not provided, the provider project is used. -
replica_configuration- (Optional) The configuration for replication. The configuration is detailed below. -
replica_names- (Optional, Computed) List of replica names. Can be updated. -
root_password- (Optional) Initial root password. Can be updated. Required for MS SQL Server. -
root_password_wo- (Optional) Initial root password. Can be updated. Required for MS SQL Server. Note: This property is write-only and will not be read from the API.~> Note: One of
root_passwordorroot_password_wocan only be set. -
root_password_wo_version- Triggers update ofroot_password_wowrite-only. Increment this value when an update toroot_password_wois needed. For more info see updating write-only arguments -
encryption_key_name- (Optional) The full path to the encryption key used for the CMEK disk encryption. Setting up disk encryption currently requires manual steps outside of Terraform. The provided key must be in the same region as the SQL instance. In order to use this feature, a special kind of service account must be created and granted permission on this key. This step can currently only be done manually, please see this step. That service account needs theCloud KMS > Cloud KMS CryptoKey Encrypter/Decrypterrole on your key - please see this step. -
deletion_protection- (Optional) Whether Terraform will be prevented from destroying the instance. When the field is set to true or unset in Terraform state, aterraform applyorterraform destroythat would delete the instance will fail. When the field is set to false, deleting the instance is allowed.~> NOTE: This flag only protects instances from deletion within Terraform. To protect your instances from accidental deletion across all surfaces (API, gcloud, Cloud Console and Terraform), use the API flag
settings.deletion_protection_enabled. -
final_backup_description- (Optional) The description of final backup. Only set this field whenfinal_backup_config.enabledis true. -
restore_backup_context- (optional) The context needed to restore the database to a backup run. This field will cause Terraform to trigger the database to restore from the backup run indicated. The configuration is detailed below. NOTE: Restoring from a backup is an imperative action and not recommended via Terraform. Adding or modifying this block during resource creation/update will trigger the restore action after the resource is created/updated. -
backupdr_backup- (optional) The backupdr_backup needed to restore the database to a backup run. This field will cause Terraform to trigger the database to restore from the backup run indicated. The configuration is detailed below. NOTE: Restoring from a backup is an imperative action and not recommended via Terraform. Adding or modifying this block during resource creation/update will trigger the restore action after the resource is created/updated. -
clone- (Optional) The context needed to create this instance as a clone of another instance. When this field is set during resource creation, Terraform will attempt to clone another instance as indicated in the context. The configuration is detailed below. -
point_in_time_restore_context- (Optional) The point_in_time_restore_context needed for performing a point-in-time recovery of an instance managed by Google Cloud Backup and Disaster Recovery. This field will cause Terraform to trigger the database to restore to a point in time indicated. The configuration is detailed below. NOTE: Restoring from a backup is an imperative action and not recommended via Terraform. Adding or modifying this block during resource creation/update will trigger the restore action after the resource is created/updated.
The settings block supports:
-
tier- (Required) The machine type to use. See tiers for more details and supported versions. Postgres supports only shared-core machine types, and custom machine types such asdb-custom-2-13312. See the Custom Machine Type Documentation to learn about specifying custom machine types. -
edition- (Optional) The edition of the instance, can beENTERPRISEorENTERPRISE_PLUS. -
user_labels- (Optional) A set of key/value user label pairs to assign to the instance. -
activation_policy- (Optional) This specifies when the instance should be active. Can be eitherALWAYS,NEVERorON_DEMAND. -
availability_type- (Optional) The availability type of the Cloud SQL instance, high availability (REGIONAL) or single zone (ZONAL). For all instances, ensure thatsettings.backup_configuration.enabledis set totrue. For MySQL instances, ensure thatsettings.backup_configuration.binary_log_enabledis set totrue. For Postgres and SQL Server instances, ensure thatsettings.backup_configuration.point_in_time_recovery_enabledis set totrue. Defaults toZONAL. For read pool instances, this field is read-only. The availability type is changed by specifying the number of nodes (node_count). -
collation- (Optional) The name of server instance collation. -
connector_enforcement- (Optional) Control the enforcement of Cloud SQL Auth Proxy or Cloud SQL connectors for all the connections, can beREQUIREDorNOT_REQUIRED. If enabled, all the direct connections are rejected. -
deletion_protection_enabled- (Optional) Enables deletion protection of an instance at the GCP level. Enabling this protection will guard against accidental deletion across all surfaces (API, gcloud, Cloud Console and Terraform) by enabling the GCP Cloud SQL instance deletion protection. Terraform provider support was introduced in version 4.48.0. Defaults tofalse. -
enable_google_ml_integration- (Optional) Enables Cloud SQL instances to connect to Vertex AI and pass requests for real-time predictions and insights. Defaults tofalse. -
enable_dataplex_integration- (Optional) Enables Cloud SQL instance integration with Dataplex. MySQL, Postgres and SQL Server instances are supported for this feature. Defaults tofalse. -
disk_autoresize- (Optional) Enables auto-resizing of the storage size. Defaults totrue. Note that ifdisk_sizeis set, futureterraform applycalls will attempt to delete the instance in order to resize the disk to the value specified in disk_size if it has been resized. To avoid this, ensure thatlifecycle.ignore_changesis applied todisk_size. -
disk_autoresize_limit- (Optional) The maximum size to which storage capacity can be automatically increased. The default value is 0, which specifies that there is no limit. -
disk_size- (Optional) The size of data disk, in GB. Size of a running instance cannot be reduced but can be increased. The minimum value is 10GB forPD_SSD,PD_HDDand 20GB forHYPERDISK_BALANCED. Note that this value will override the resizing fromdisk_autoresizeif that feature is enabled. To avoid this, setlifecycle.ignore_changeson this field. -
disk_type- (Optional) The type of data disk:PD_SSD,PD_HDD, orHYPERDISK_BALANCED. Defaults toPD_SSD.HYPERDISK_BALANCEDis preview. -
data_disk_provisioned_iops- (Optional, Beta) Provisioned number of I/O operations per second for the data disk. This field is only used forHYPERDISK_BALANCEDdisk types. -
data_disk_provisioned_throughput- (Optional, Beta) Provisioned throughput measured in MiB per second for the data disk. This field is only used forHYPERDISK_BALANCEDdisk types. -
node_count- For a read pool instance, the number of nodes in the read pool. For read pools with auto scaling enabled, this field is read only. -
pricing_plan- (Optional) Pricing plan for this instance, can only bePER_USE. -
time_zone- (Optional) The time_zone to be used by the database engine (supported only for SQL Server), in SQL Server timezone format. -
retain_backups_on_delete- (Optional) When this parameter is set to true, Cloud SQL retains backups of the instance even after the instance is deleted. TheON_DEMANDbackup will be retained until customer deletes the backup or the project. TheAUTOMATEDbackup will be retained based on the backups retention setting.
The optional final_backup_config subblock supports:
-
enabled- (Optional) True if enabled final backup. -
retention_days- (Optional) The number of days we retain the final backup after instance deletion. The valid range is between 1 and 365. For instances managed by BackupDR, the valid range is between 1 day and 99 years.
The optional settings.advanced_machine_features subblock supports:
threads_per_core- (Optional) The number of threads per core. The value of this flag can be 1 or 2. To disable SMT, set this flag to 1. Only available in Cloud SQL for SQL Server instances. See smt for more details.
The optional settings.database_flags sublist supports:
-
name- (Required) Name of the flag. -
value- (Required) Value of the flag.
The optional settings.active_directory_config subblock supports:
domain- (Required) The domain name for the active directory (e.g., mydomain.com). Can only be used with SQL Server.
The optional settings.data_cache_config subblock supports:
data_cache_enabled- (Optional) Whether data cache is enabled for the instance. Defaults totruefor MYSQL Enterprise Plus and PostgreSQL Enterprise Plus instances only. For SQL Server Enterprise Plus instances it defaults tofalse.
The optional settings.deny_maintenance_period subblock supports:
-
end_date- (Required) "deny maintenance period" end date. If the year of the end date is empty, the year of the start date also must be empty. In this case, it means the no maintenance interval recurs every year. The date is in format yyyy-m-dd (the month is without leading zeros)i.e., 2020-1-01, or 2020-11-01, or mm-dd, i.e., 11-01 -
start_date- (Required) "deny maintenance period" start date. If the year of the start date is empty, the year of the end date also must be empty. In this case, it means the deny maintenance period recurs every year. The date is in format yyyy-m-dd (the month is without leading zeros)i.e., 2020-1-01, or 2020-11-01, or mm-dd, i.e., 11-01 -
time- (Required) Time in UTC when the "deny maintenance period" starts on startDate and ends on endDate. The time is in format: HH:mm:SS, i.e., 00:00:00
The optional settings.sql_server_audit_config subblock supports:
-
bucket- (Optional) The name of the destination bucket (e.g., gs://mybucket). -
upload_interval- (Optional) How often to upload generated audit files. A duration in seconds with up to nine fractional digits, terminated by 's'. Example: "3.5s". -
retention_interval- (Optional) How long to keep generated audit files. A duration in seconds with up to nine fractional digits, terminated by 's'. Example: "3.5s".
The optional settings.backup_configuration subblock supports:
-
binary_log_enabled- (Optional) True if binary logging is enabled. Can only be used with MySQL. -
enabled- (Optional) True if backup configuration is enabled. -
backup_tier- (Computed) The backup tier that manages the backups for the instance. -
start_time- (Optional)HH:MMformat time indicating when backup configuration starts. -
point_in_time_recovery_enabled- (Optional) True if Point-in-time recovery is enabled. Will restart database if enabled after instance creation. Valid only for PostgreSQL and SQL Server instances. Enabled by default for PostgreSQL Enterprise Plus and SQL Server Enterprise Plus instances. -
location- (Optional) The region where the backup will be stored -
transaction_log_retention_days- (Optional) The number of days of transaction logs we retain for point in time restore, from 1-7. For PostgreSQL Enterprise Plus and SQL Server Enterprise Plus instances, the number of days of retained transaction logs can be set from 1 to 35. -
backup_retention_settings- (Optional) Backup retention settings. The configuration is detailed below.
The optional settings.backup_configuration.backup_retention_settings subblock supports:
-
retained_backups- (Optional) Depending on the value of retention_unit, this is used to determine if a backup needs to be deleted. If retention_unit is 'COUNT', we will retain this many backups. -
retention_unit- (Optional) The unit that 'retained_backups' represents. Defaults toCOUNT.
The optional settings.ip_configuration subblock supports:
-
ipv4_enabled- (Optional) Whether this Cloud SQL instance should be assigned a public IPV4 address. At leastipv4_enabledmust be enabled or aprivate_networkmust be configured. -
private_network- (Optional) The VPC network from which the Cloud SQL instance is accessible for private IP. For example, projects/myProject/global/networks/default. Specifying a network enables private IP. At leastipv4_enabledmust be enabled or aprivate_networkmust be configured. This setting can be updated, but it cannot be removed after it is set. -
ssl_mode- (Optional) Specify how SSL connection should be enforced in DB connections. Supported values areALLOW_UNENCRYPTED_AND_ENCRYPTED,ENCRYPTED_ONLY, andTRUSTED_CLIENT_CERTIFICATE_REQUIRED(not supported for SQL Server). See API reference doc for details. -
server_ca_mode- (Optional) Specify how the server certificate's Certificate Authority is hosted. Supported values areGOOGLE_MANAGED_INTERNAL_CAandGOOGLE_MANAGED_CAS_CA. -
server_ca_pool- (Optional) The resource name of the server CA pool for an instance withCUSTOMER_MANAGED_CAS_CAas theserver_ca_mode. -
custom_subject_alternative_names- (Optional) The custom subject alternative names for an instance withCUSTOMER_MANAGED_CAS_CAas theserver_ca_mode. -
allocated_ip_range- (Optional) The name of the allocated ip range for the private ip CloudSQL instance. For example: "google-managed-services-default". If set, the instance ip will be created in the allocated range. The range name must comply with RFC 1035. Specifically, the name must be 1-63 characters long and match the regular expression a-z?. -
enable_private_path_for_google_cloud_services- (Optional) Whether Google Cloud services such as BigQuery are allowed to access data in this Cloud SQL instance over a private IP connection. SQLSERVER database type is not supported.
The optional settings.ip_configuration.authorized_networks[] sublist supports:
-
expiration_time- (Optional) The RFC 3339 formatted date time string indicating when this whitelist expires. -
name- (Optional) A name for this whitelist entry. -
value- (Required) A CIDR notation IPv4 or IPv6 address that is allowed to access this instance. Must be set even if other two attributes are not for the whitelist to become active.
The optional settings.ip_configuration.psc_config sublist supports:
-
psc_enabled- (Optional) Whether PSC connectivity is enabled for this instance. -
allowed_consumer_projects- (Optional) List of consumer projects that are allow-listed for PSC connections to this instance. This instance can be connected to with PSC from any network in these projects. Each consumer project in this list may be represented by a project number (numeric) or by a project id (alphanumeric). -
The optional
psc_config.psc_auto_connectionssubblock - (Optional) A comma-separated list of networks or a comma-separated list of network-project pairs. Each project in this list is represented by a project number (numeric) or by a project ID (alphanumeric). This allows Private Service Connect connections to be created automatically for the specified networks. -
consumer_network- "The consumer network of this consumer endpoint. This must be a resource path that includes both the host project and the network name. For example,projects/project1/global/networks/network1. The consumer host project of this network might be different from the consumer service project." -
network_attachment_uri- (Optional) Network Attachment URI in the formatprojects/project1/regions/region1/networkAttachments/networkAttachment1to enable outbound connectivity on PSC instance. -
consumer_service_project_id- (Optional) The project ID of consumer service project of this consumer endpoint.
The optional settings.read_pool_auto_scale_config subblock supports:
-
enabled- True if Read Pool Auto Scale is enabled. -
max_node_count- Maximum number of nodes in the read pool. If set to lower than current node count, node count will be updated. -
min_node_count- Minimum number of nodes in the read pool. If set to higher than current node count, node count will be updated. -
disable_scale_in- True if auto scale in is disabled. -
scale_in_cooldown_seconds- The cooldown period for scale in operations. -
scale_out_cooldown_seconds- The cooldown period for scale out operations. -
target_metrics- Target metrics for Read Pool Auto Scale. Must specifytarget_metrics.metricandtarget_metrics.target_valuein subblock. -
metric- Metric name for Read Pool Auto Scale. -
target_value- Target value for Read Pool Auto Scale.
The optional settings.location_preference subblock supports:
-
follow_gae_application- (Optional) A GAE application whose zone to remain in. Must be in the same region as this instance. -
zone- (Optional) The preferred compute engine zone. -
secondary_zone- (Optional) The preferred Compute Engine zone for the secondary/failover.
The optional settings.maintenance_window subblock for instances declares a one-hour
maintenance window
when an Instance can automatically restart to apply updates. The maintenance window is specified in UTC time. It supports:
-
day- (Optional) Day of week (1-7), starting on Monday -
hour- (Optional) Hour of day (0-23), ignored ifdaynot set -
update_track- (Optional) Receive updates after one week (canary) or after two weeks (stable) or after five weeks (week5) of notification.
The optional settings.insights_config subblock for instances declares Query Insights(MySQL, PostgreSQL) configuration. It contains:
-
query_insights_enabled- True if Query Insights feature is enabled. -
query_string_length- Maximum query length stored in bytes. Between 256 and 4500. Default to 1024. Higher query lengths are more useful for analytical queries, but they also require more memory. Changing the query length requires you to restart the instance. You can still add tags to queries that exceed the length limit. -
record_application_tags- True if Query Insights will record application tags from query when enabled. -
record_client_address- True if Query Insights will record client address when enabled. -
query_plans_per_minute- Number of query execution plans captured by Insights per minute for all queries combined. Between 0 and 20. Default to 5.
The optional settings.password_validation_policy subblock for instances declares Password Validation Policy configuration. It contains:
-
min_length- Specifies the minimum number of characters that the password must have. -
complexity- Checks if the password is a combination of lowercase, uppercase, numeric, and non-alphanumeric characters. -
reuse_interval- Specifies the number of previous passwords that you can't reuse. -
disallow_username_substring- Prevents the use of the username in the password. -
password_change_interval- Specifies the minimum duration after which you can change the password. -
enable_password_policy- Enables or disable the password validation policy.
The optional replica_configuration block must have master_instance_name set
to work, cannot be updated and supports:
~> Note: replica_configuration field is not meant to be used if the master
instance is a source representation instance. The configuration provided by this
field can be set on the source representation instance directly. If this field
is present when the master instance is a source representation instance, dump_file_path must be provided.
-
cascadable_replica- (Optional) Specifies if the replica is a cascadable replica. If true, instance must be in different region from primary.~> NOTE: Only supported for SQL Server database.
-
ca_certificate- (Optional) PEM representation of the trusted CA's x509 certificate. -
client_certificate- (Optional) PEM representation of the replica's x509 certificate. -
client_key- (Optional) PEM representation of the replica's private key. The corresponding public key in encoded in theclient_certificate. -
connect_retry_interval- (Optional) The number of seconds between connect retries. MySQL's default is 60 seconds. -
dump_file_path- (Optional) Path to a SQL file in GCS from which replica instances are created. Format isgs://bucket/filename. Note, if the master instance is a source representation instance this field must be present. -
failover_target- (Optional) Specifies if the replica is the failover target. If the field is set to true the replica will be designated as a failover replica. If the master instance fails, the replica instance will be promoted as the new master instance. ~> NOTE: Not supported for Postgres database. -
master_heartbeat_period- (Optional) Time in ms between replication heartbeats. -
password- (Optional) Password for the replication connection. -
ssl_cipher- (Optional) Permissible ciphers for use in SSL encryption. -
username- (Optional) Username for replication connection. -
verify_server_certificate- (Optional) True if the master's common name value is checked during the SSL handshake.
The optional point_in_time_restore_context block supports:
-
datasource- The Google Cloud Backup and Disaster Recovery Datasource URI. -
point_in_time- The timestamp of the point in time that should be restored.A timestamp in RFC3339 UTC "Zulu" format, with nanosecond resolution and up to nine fractional digits. Examples: "2014-10-02T15:01:23Z" and "2014-10-02T15:01:23.045123456Z".
-
target_instance- The name of the target instance. -
private_network- (Optional) The resource link for the VPC network from which the Cloud SQL instance is accessible for private IP. For example, "/projects/myProject/global/networks/default". -
preferred_zone- (Optional) Point-in-time recovery of an instance to the specified zone. If no zone is specified, then clone to the same primary zone as the source instance. -
allocated_ip_range- (Optional) The name of the allocated ip range for the private ip CloudSQL instance. For example: "google-managed-services-default". If set, the cloned instance ip will be created in the allocated range. The range name must comply with RFC 1035. Specifically, the name must be 1-63 characters long and match the regular expression a-z?. -
source_instance_deletion_time- (Optional) The timestamp of when the source instance was deleted for a clone from a deleted instance.A timestamp in RFC3339 UTC "Zulu" format, with nanosecond resolution and up to nine fractional digits. Examples: "2014-10-02T15:01:23Z" and "2014-10-02T15:01:23.045123456Z".
-
database_names- (Optional) (SQL Server only, use withpoint_in_time) Clone only the specified databases from the source instance. Clone all databases if empty.
The optional clone block supports:
-
source_instance_name- (Required) Name of the source instance which will be cloned. -
point_in_time- (Optional) The timestamp of the point in time that should be restored.A timestamp in RFC3339 UTC "Zulu" format, with nanosecond resolution and up to nine fractional digits. Examples: "2014-10-02T15:01:23Z" and "2014-10-02T15:01:23.045123456Z".
-
preferred_zone- (Optional) (Point-in-time recovery for PostgreSQL only) Clone to an instance in the specified zone. If no zone is specified, clone to the same zone as the source instance. clone-unavailable-instance -
database_names- (Optional) (SQL Server only, use withpoint_in_time) Clone only the specified databases from the source instance. Clone all databases if empty. -
allocated_ip_range- (Optional) The name of the allocated ip range for the private ip CloudSQL instance. For example: "google-managed-services-default". If set, the cloned instance ip will be created in the allocated range. The range name must comply with RFC 1035. Specifically, the name must be 1-63 characters long and match the regular expression a-z?. -
source_instance_deletion_time- (Optional) The timestamp of when the source instance was deleted for a clone from a deleted instance.A timestamp in RFC3339 UTC "Zulu" format, with nanosecond resolution and up to nine fractional digits. Examples: "2014-10-02T15:01:23Z" and "2014-10-02T15:01:23.045123456Z".
The optional restore_backup_context block supports:
NOTE: Restoring from a backup is an imperative action and not recommended via Terraform. Adding or modifying this
block during resource creation/update will trigger the restore action after the resource is created/updated.
-
backup_run_id- (Required) The ID of the backup run to restore from. -
instance_id- (Optional) The ID of the instance that the backup was taken from. If left empty, this instance's ID will be used. -
project- (Optional) The full project ID of the source instance.`
The optional, computed replication_cluster block represents a primary instance and disaster recovery replica pair. Applicable to MySQL and PostgreSQL. This field can be set if the primary has psa_write_endpoint set or both the primary and replica are created. This block supports:
-
psa_write_endpoint: Read-only field which if set, indicates this instance has a private service access (PSA) DNS endpoint that is pointing to the primary instance of the cluster. If this instance is the primary, then the DNS endpoint points to this instance. After a switchover or replica failover operation, this DNS endpoint points to the promoted instance. This is a read-only field, returned to the user as information. This field can exist even if a standalone instance doesn't have a DR replica yet or the DR replica is deleted. -
failover_dr_replica_name: (Optional) If the instance is a primary instance, then this field identifies the disaster recovery (DR) replica. The standard format of this field is "your-project:your-instance". You can also set this field to "your-instance", but cloud SQL backend will convert it to the aforementioned standard format. -
dr_replica: Read-only field that indicates whether the replica is a DR replica.
The optional settings.connection_pool_config subblock supports:
connection_pooling_enabled: (Optional) True if the manager connection pooling configuration is enabled.
The optional settings.connection_pool_config.flags sublist supports:
-
name- (Required) Name of the flag. -
value- (Required) Value of the flag.
In addition to the arguments listed above, the following computed attributes are exported:
-
self_link- The URI of the created resource. -
connection_name- The connection name of the instance to be used in connection strings. For example, when connecting with Cloud SQL Proxy. -
dns_name- The DNS name of the instance. See Connect to an instance using Private Service Connect for more details. -
dns_names- The list of DNS names used by this instance. Different connection types for an instance may have different DNS names. DNS names can apply to an individual instance or a cluster of instances. -
dns_names.0.name- The DNS name. -
dns_names.0.connection_type- The connection type of the DNS name. Can be eitherPUBLIC,PRIVATE_SERVICES_ACCESS, orPRIVATE_SERVICE_CONNECT. -
dns_names.0.dns_scope- The scope that the DNS name applies to.- An
INSTANCEDNS name applies to an individual Cloud SQL instance.
- An
-
service_account_email_address- The service account email address assigned to the instance. -
ip_address.0.ip_address- The IPv4 address assigned. -
ip_address.0.time_to_retire- The time this IP address will be retired, in RFC 3339 format. -
ip_address.0.type- The type of this IP address.-
A
PRIMARYaddress is an address that can accept incoming connections. -
An
OUTGOINGaddress is the source address of connections originating from the instance, if supported. -
A
PRIVATEaddress is an address for an instance which has been configured to use private networking see: Private IP.
-
-
first_ip_address- The first IPv4 address of any type assigned. This is to support accessing the first address in the list in a terraform output when the resource is configured with acount. -
available_maintenance_versions- The list of all maintenance versions applicable on the instance. -
public_ip_address- The first public (PRIMARY) IPv4 address assigned. This is a workaround for an issue fixed in Terraform 0.12 but also provides a convenient way to access an IP of a specific type without performing filtering in a Terraform config. -
private_ip_address- The first private (PRIVATE) IPv4 address assigned. This is a workaround for an issue fixed in Terraform 0.12 but also provides a convenient way to access an IP of a specific type without performing filtering in a Terraform config. -
psc_service_attachment_link- the URI that points to the service attachment of the instance. -
instance_type- The type of the instance. See API reference for SqlInstanceType for supported values.
~> NOTE: Users can upgrade a read replica instance to a stand-alone Cloud SQL instance with the help of instance_type. To promote, users have to set the instance_type property as CLOUD_SQL_INSTANCE and remove/unset master_instance_name and replica_configuration from instance configuration. This operation might cause your instance to restart.
-
settings.ip_configuration.psc_config.psc_auto_connections.consumer_network_status- (Output) The connection policy status of the consumer network. -
settings.ip_configuration.psc_config.psc_auto_connections.ip_address- (Output) The IP address of the consumer endpoint. -
settings.ip_configuration.psc_config.psc_auto_connections.status- (Output) The connection status of the consumer endpoint. -
settings.version- Used to make sure changes to thesettingsblock are atomic. -
settings.0.effective_availability_type- (Computed) The availability type of the Cloud SQL instance, high availability (REGIONAL) or single zone (ZONAL). This field always contains the value that is reported by the API (for read pools,settings.0.effective_availability_typemay differ fromsettings.0.availability_type). -
server_ca_cert.0.cert- The CA Certificate used to connect to the SQL Instance via SSL. -
server_ca_cert.0.common_name- The CN valid for the CA Cert. -
server_ca_cert.0.create_time- Creation time of the CA Cert. -
server_ca_cert.0.expiration_time- Expiration time of the CA Cert. -
server_ca_cert.0.sha1_fingerprint- SHA Fingerprint of the CA Cert.
Users can perform a switchover on a replica by following the steps below.
~>WARNING: Failure to follow these steps can lead to data loss (You will be warned during plan stage). To prevent data loss during a switchover, please verify your plan with the checklist below.
For a more in-depth walkthrough with example code, see the Switchover Guide
MySQL/PostgreSQL: Create a cross-region, Enterprise Plus edition primary and replica pair, then set the value of primary's replication_cluster.failover_dr_replica_name as the replica.
SQL Server: Create a cascadable replica in a different region from the primary (cascadable_replica is set to true in replica_configuration)
- Change instance_type from
READ_REPLICA_INSTANCEtoCLOUD_SQL_INSTANCE - Remove
master_instance_name - (SQL Server) Remove
replica_configuration - Add current primary's name to the replica's
replica_nameslist - (MySQL/PostgreSQL) Add current primary's name to the replica's
replication_cluster.failover_dr_replica_name. - (MySQL/PostgreSQL) Adjust
backup_configuration. See Switchover Guide for details.
- Change
instance_typefromCLOUD_SQL_INSTANCEtoREAD_REPLICA_INSTANCE - Set
master_instance_nameto the original replica (which will be primary after switchover) - (SQL Server) Set
replica_configurationand setcascadable_replicatotrue - Remove original replica from
replica_names- NOTE: Do not delete the replica_names field, even if it has no replicas remaining. Set replica_names = [ ] to indicate it having no replicas.
- (MySQL/PostgreSQL) Set
replication_cluster.failover_dr_replica_nameas the empty string. - (MySQL/PostgreSQL) Adjust
backup_configuration. See Switchover Guide for details.
terraform planoutputs "0 to add, 0 to destroy"terraform plandoes not say "must be replaced" for any resource- Every resource "will be updated in-place"
- Only the 2 instances involved in switchover have planned changes
- (Recommended) Use
deletion_protectionon instances as a safety measure
google_sql_database_instance provides the following
Timeouts configuration options:
create- Default is 90 minutes.update- Default is 90 minutes.delete- Default is 90 minutes.
Database instances can be imported using one of any of these accepted formats:
projects/{{project}}/instances/{{name}}{{project}}/{{name}}{{name}}
In Terraform v1.5.0 and later, use an import block to import Database instances using one of the formats above. For example:
import {
id = "projects/{{project}}/instances/{{name}}"
to = google_sql_database_instance.default
}When using the terraform import command, Database instances can be imported using one of the formats above. For example:
$ terraform import google_sql_database_instance.default projects/{{project}}/instances/{{name}}
$ terraform import google_sql_database_instance.default {{project}}/{{name}}
$ terraform import google_sql_database_instance.default {{name}}~> NOTE: Some fields (such as replica_configuration) won't show a diff if they are unset in
config and set on the server.
When importing, double-check that your config has all the fields set that you expect- just seeing
no diff isn't sufficient to know that your config could reproduce the imported resource.