Skip to content

googleSqlDatabaseInstance

Creates a new Google SQL Database Instance. For more information, see the official documentation, or the JSON API.

\~> NOTE on googleSqlDatabaseInstance: - Second-generation instances include a default 'root'@'%' user with no password. This user will be deleted by Terraform on instance creation. You should use googleSqlUser to define a custom user with a restricted host and strong password.

-> Note: On newer versions of the provider, you must explicitly set deletionProtection=false (and run terraformApply 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.

Example Usage

SQL Second Generation Instance

/*Provider bindings are generated by running cdktf get.
See https://cdk.tf/provider-generation for more details.*/
import * as google from "./.gen/providers/google";
/*The following providers are missing schema information and might need manual adjustments to synthesize correctly: google.
For a more precise conversion please use the --provider flag in convert.*/
new google.sqlDatabaseInstance.SqlDatabaseInstance(this, "main", {
  database_version: "POSTGRES_14",
  name: "main-instance",
  region: "us-central1",
  settings: [
    {
      tier: "db-f1-micro",
    },
  ],
});

Granular restriction of network access

/*Provider bindings are generated by running cdktf get.
See https://cdk.tf/provider-generation for more details.*/
import * as google from "./.gen/providers/google";
import * as random from "./.gen/providers/random";
/*The following providers are missing schema information and might need manual adjustments to synthesize correctly: google, random.
For a more precise conversion please use the --provider flag in convert.*/
const onprem = ["192.168.1.2", "192.168.2.3"];
const googleComputeInstanceApps = new google.computeInstance.ComputeInstance(
  this,
  "apps",
  {
    boot_disk: [
      {
        initialize_params: [
          {
            image: "ubuntu-os-cloud/ubuntu-1804-lts",
          },
        ],
      },
    ],
    machine_type: "f1-micro",
    name: "apps-${count.index + 1}",
    network_interface: [
      {
        access_config: [{}],
        network: "default",
      },
    ],
  }
);
/*In most cases loops should be handled in the programming language context and 
not inside of the Terraform context. If you are looping over something external, e.g. a variable or a file input
you should consider using a for loop. If you are looping over something only known to Terraform, e.g. a result of a data source
you need to keep this like it is.*/
googleComputeInstanceApps.addOverride("count", 8);
const randomIdDbNameSuffix = new random.id.Id(this, "db_name_suffix", {
  byte_length: 4,
});
const googleSqlDatabaseInstancePostgres =
  new google.sqlDatabaseInstance.SqlDatabaseInstance(this, "postgres", {
    database_version: "POSTGRES_14",
    name: `postgres-instance-\${${randomIdDbNameSuffix.hex}}`,
    settings: [
      {
        ip_configuration: [
          {
            authorized_networks: [],
          },
        ],
        tier: "db-f1-micro",
      },
    ],
  });
/*In most cases loops should be handled in the programming language context and 
not inside of the Terraform context. If you are looping over something external, e.g. a variable or a file input
you should consider using a for loop. If you are looping over something only known to Terraform, e.g. a result of a data source
you need to keep this like it is.*/
googleSqlDatabaseInstancePostgres.addOverride(
  "settings.0.ip_configuration.0.authorized_networks",
  {
    for_each: `\${${googleComputeInstanceApps.fqn}}`,
    content: [
      {
        name: "${apps.value.name}",
        value: "${apps.value.network_interface.0.access_config.0.nat_ip}",
      },
    ],
  }
);

Private IP Instance

\~> NOTE: For private IP instance setup, note that the googleSqlDatabaseInstance does not actually interpolate values from googleServiceNetworkingConnection. You must explicitly add a dependsOnreference 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.id
      enable_private_path_for_google_cloud_services = true
    }
  }
}

provider "google-beta" {
  region = "us-central1"
  zone   = "us-central1-a"
}

Argument Reference

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 if clone is not set.

  • databaseVersion - (Required) The MySQL, PostgreSQL or SQL Server version to use. Supported values include mysql56, mysql57, mysql80, postgres96,postgres10, postgres11, postgres12, postgres13, postgres14, sqlserver2017Standard, sqlserver2017Enterprise, sqlserver2017Express, sqlserver2017Web. sqlserver2019Standard, sqlserver2019Enterprise, sqlserver2019Express, sqlserver2019Web. 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.

  • maintenanceVersion - (Optional) The current software version on the instance. This attribute can not be set during creation. Refer to availableMaintenanceVersions attribute to see what maintenanceVersion are available for upgrade. When this attribute gets updated, it will cause an instance restart. Setting a maintenanceVersion value that is older than the current one on the instance will be ignored.

  • masterInstanceName - (Optional) The name of the existing instance that will act as the master in the replication setup. Note, this requires the master to have binaryLogEnabled set, 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.

  • replicaConfiguration - (Optional) The configuration for replication. The configuration is detailed below. Valid only for MySQL instances.

  • rootPassword - (Optional) Initial root password. Can be updated. Required for MS SQL Server.

  • encryptionKeyName - (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 the cloudKms >CloudKmsCryptoKeyEncrypter/decrypter role on your key - please see this step.

  • deletionProtection - (Optional) Whether or not to allow Terraform to destroy the instance. Unless this field is set to false in Terraform state, a terraformDestroy or terraformApply command that deletes the instance will fail. Defaults to true.

    \~> 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 settingsDeletionProtectionEnabled.

  • restoreBackupContext - (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.

  • 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.

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 as dbCustom213312. See the Custom Machine Type Documentation to learn about specifying custom machine types.

  • activationPolicy - (Optional) This specifies when the instance should be active. Can be either always, never or onDemand.

  • availabilityType - (Optional) The availability type of the Cloud SQL instance, high availability (regional) or single zone (zonal).' For all instances, ensure that settingsBackupConfigurationEnabled is set to true. For MySQL instances, ensure that settingsBackupConfigurationBinaryLogEnabled is set to true. For Postgres and SQL Server instances, ensure that settingsBackupConfigurationPointInTimeRecoveryEnabled is set to true. Defaults to zonal.

  • collation - (Optional) The name of server instance collation.

  • connectorEnforcement - (Optional) Specifies if connections must use Cloud SQL connectors.

  • deletionProtectionEnabled - (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 to false.

  • diskAutoresize - (Optional) Enables auto-resizing of the storage size. Defaults to true.

  • diskAutoresizeLimit - (Optional) The maximum size to which storage capacity can be automatically increased. The default value is 0, which specifies that there is no limit.

  • diskSize - (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.

  • diskType - (Optional) The type of data disk: PD_SSD or PD_HDD. Defaults to pdSsd.

  • pricingPlan - (Optional) Pricing plan for this instance, can only be perUse.

  • userLabels - (Optional) A set of key/value user label pairs to assign to the instance.

The optional settingsDatabaseFlags sublist supports:

  • name - (Required) Name of the flag.

  • value - (Required) Value of the flag.

The optional settingsActiveDirectoryConfig subblock supports:

  • domain - (Required) The domain name for the active directory (e.g., mydomain.com). Can only be used with SQL Server.

The optional settingsDenyMaintenancePeriod subblock supports:

  • endDate - (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-mm-dd i.e., 2020-11-01, or mm-dd, i.e., 11-01

  • startDate - (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-mm-dd i.e., 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 settingsSqlServerAuditConfig subblock supports:

  • bucket - (Optional) The name of the destination bucket (e.g., gs://mybucket).

  • uploadInterval - (Optional) How often to upload generated audit files. A duration in seconds with up to nine fractional digits, terminated by 's'. Example: "3.5s".

  • retentionInterval - (Optional) How long to keep generated audit files. A duration in seconds with up to nine fractional digits, terminated by 's'. Example: "3.5s".

  • timeZone - (Optional) The time_zone to be used by the database engine (supported only for SQL Server), in SQL Server timezone format.

The optional settingsBackupConfiguration subblock supports:

  • binaryLogEnabled - (Optional) True if binary logging is enabled. Can only be used with MySQL.

  • enabled - (Optional) True if backup configuration is enabled.

  • startTime - (Optional) hh:mm format time indicating when backup configuration starts.

  • pointInTimeRecoveryEnabled - (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.

  • location - (Optional) The region where the backup will be stored

  • transactionLogRetentionDays - (Optional) The number of days of transaction logs we retain for point in time restore, from 1-7.

  • backupRetentionSettings - (Optional) Backup retention settings. The configuration is detailed below.

The optional settingsBackupConfigurationBackupRetentionSettings subblock supports:

  • retainedBackups - (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.

  • retentionUnit - (Optional) The unit that 'retained_backups' represents. Defaults to count.

The optional settingsIpConfiguration subblock supports:

  • ipv4Enabled - (Optional) Whether this Cloud SQL instance should be assigned a public IPV4 address. At least ipv4Enabled must be enabled or a privateNetwork must be configured.

  • privateNetwork - (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 least ipv4Enabled must be enabled or a privateNetwork must be configured. This setting can be updated, but it cannot be removed after it is set.

  • requireSsl - (Optional) Whether SSL connections over IP are enforced or not.

  • allocatedIpRange - (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?.

  • enablePrivatePathForGoogleCloudServices - (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 settingsIpConfigurationAuthorizedNetworks[] sublist supports:

  • expirationTime - (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 settingsLocationPreference subblock supports:

  • followGaeApplication - (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.

  • secondaryZone - (Optional) The preferred Compute Engine zone for the secondary/failover.

The optional settingsMaintenanceWindow 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 (17), starting on Monday

  • hour - (Optional) Hour of day (023), ignored if day not set

  • updateTrack - (Optional) Receive updates earlier (canary) or later (stable)

The optional settingsInsightsConfig subblock for instances declares Query Insights(MySQL, PostgreSQL) configuration. It contains:

  • queryInsightsEnabled - True if Query Insights feature is enabled.

  • queryStringLength - Maximum query length stored in bytes. Between 256 and 4500. Default to 1024.

  • recordApplicationTags - True if Query Insights will record application tags from query when enabled.

  • recordClientAddress - True if Query Insights will record client address when enabled.

  • queryPlansPerMinute - Number of query execution plans captured by Insights per minute for all queries combined. Between 0 and 20. Default to 5.

The optional settingsPasswordValidationPolicy subblock for instances declares Password Validation Policy configuration. It contains:

  • minLength - 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.

  • reuseInterval - Specifies the number of previous passwords that you can't reuse.

  • disallowUsernameSubstring - Prevents the use of the username in the password.

  • passwordChangeInterval - Specifies the minimum duration after which you can change the password.

  • enablePasswordPolicy - Enables or disable the password validation policy.

The optional replicaConfiguration block must have masterInstanceName set to work, cannot be updated, and supports:

  • caCertificate - (Optional) PEM representation of the trusted CA's x509 certificate.

  • clientCertificate - (Optional) PEM representation of the replica's x509 certificate.

  • clientKey - (Optional) PEM representation of the replica's private key. The corresponding public key in encoded in the clientCertificate.

  • connectRetryInterval - (Optional) The number of seconds between connect retries. MySQL's default is 60 seconds.

  • dumpFilePath - (Optional) Path to a SQL file in GCS from which replica instances are created. Format is gs://bucket/filename.

  • failoverTarget - (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.

  • masterHeartbeatPeriod - (Optional) Time in ms between replication heartbeats.

  • password - (Optional) Password for the replication connection.

  • sslCipher - (Optional) Permissible ciphers for use in SSL encryption.

  • username - (Optional) Username for replication connection.

  • verifyServerCertificate - (Optional) True if the master's common name value is checked during the SSL handshake.

The optional clone block supports:

  • sourceInstanceName - (Required) Name of the source instance which will be cloned.

  • pointInTime - (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".

  • databaseNames - (Optional) (SQL Server only, use with pointInTime) Clone only the specified databases from the source instance. Clone all databases if empty.

  • allocatedIpRange - (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?.

The optional restoreBackupContext 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.

  • backupRunId - (Required) The ID of the backup run to restore from.

  • instanceId - (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.`

Attributes Reference

In addition to the arguments listed above, the following computed attributes are exported:

  • selfLink - The URI of the created resource.

  • connectionName - The connection name of the instance to be used in connection strings. For example, when connecting with Cloud SQL Proxy.

  • serviceAccountEmailAddress - The service account email address assigned to the instance.

  • ipAddress0IpAddress - The IPv4 address assigned.

  • ipAddress0TimeToRetire - The time this IP address will be retired, in RFC 3339 format.

  • ipAddress0Type - The type of this IP address.

    • A primary address is an address that can accept incoming connections.

    • An outgoing address is the source address of connections originating from the instance, if supported.

    • A private address is an address for an instance which has been configured to use private networking see: Private IP.

  • firstIpAddress - 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 a count.

  • availableMaintenanceVersions - The list of all maintenance versions applicable on the instance.

  • publicIpAddress - 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.

  • privateIpAddress - 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.

  • instanceType - The type of the instance. The supported values are sqlInstanceTypeUnspecified, cloudSqlInstance, onPremisesInstance and readReplicaInstance.

\~> NOTE: Users can upgrade a read replica instance to a stand-alone Cloud SQL instance with the help of instanceType. To promote, users have to set the instanceType property as cloudSqlInstance and remove/unset masterInstanceName and replicaConfiguration from instance configuration. This operation might cause your instance to restart.

  • settingsVersion - Used to make sure changes to the settings block are atomic.

  • serverCaCert0Cert - The CA Certificate used to connect to the SQL Instance via SSL.

  • serverCaCert0CommonName - The CN valid for the CA Cert.

  • serverCaCert0CreateTime - Creation time of the CA Cert.

  • serverCaCert0ExpirationTime - Expiration time of the CA Cert.

  • serverCaCert0Sha1Fingerprint - SHA Fingerprint of the CA Cert.

Timeouts

googleSqlDatabaseInstance provides the following Timeouts configuration options:

  • create - Default is 40 minutes.
  • update - Default is 30 minutes.
  • delete - Default is 30 minutes.

Import

Database instances can be imported using one of any of these accepted formats:

$ terraform import google_sql_database_instance.main projects/{{project}}/instances/{{name}}
$ terraform import google_sql_database_instance.main {{project}}/{{name}}
$ terraform import google_sql_database_instance.main {{name}}

\~> NOTE: Some fields (such as replicaConfiguration) 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.