Google Cloud SQL Database Instance

This page shows how to write Terraform for Cloud SQL Database Instance and write them securely.

google_sql_database_instance (Terraform)

The Database Instance in Cloud SQL can be configured in Terraform with the resource name google_sql_database_instance. The following sections describe 5 examples of how to use the resource and its parameters.

Example Usage from GitHub

sql_database_instance_test.tf#L6
resource "google_sql_database_instance" "sql_server" {
  name             = "master-instance"
  database_version = "SQLSERVER_2017_ENTERPRISE"
  settings {
    tier              = "db-custom-16-61440"
    availability_type = "ZONAL"
positive.tf#L1
resource "google_sql_database_instance" "positive1" {
  name             = "master-instance"
  database_version = "POSTGRES_11"
  region           = "us-central1"

  settings {
sql_database_instance_test.tf#L6
resource "google_sql_database_instance" "sql_server" {
  name             = "master-instance"
  database_version = "SQLSERVER_2017_ENTERPRISE"
  settings {
    tier              = "db-custom-16-61440"
    availability_type = "ZONAL"
positive.tf#L1
resource "google_sql_database_instance" "positive1" {
  name             = "master-instance"
  database_version = "POSTGRES_11"
  region           = "us-central1"

  settings {
positive.tf#L1
resource "google_sql_database_instance" "positive1" {
    name             = "master-instance"
    database_version = "POSTGRES_11"
    region           = "us-central1"

    settings {

Review your Terraform file for Google best practices

Shisho Cloud, our free checker to make sure your Terraform configuration follows best practices, is available (beta).

Security Best Practices for google_sql_database_instance

There are 12 settings in google_sql_database_instance that should be taken care of for security reasons. The following section explain an overview and example code.

risk-label

Ensure to disable local_infile setting in MySQL

It is better to disable the local_infile setting in MySQL. If this is not disabled, arbitrary files might be readable.

risk-label

Ensure to enable automated backups for the recovery to prevent any data-losses

It is better to enable automated backups as the default to restore the data when we face corruption or data-loss incident.

risk-label

Ensure to disable cross-database ownership chaining

It is better to disable cross-database ownership chaining. The security feature provided by SQL Server allows users to access the other databases are been currently using.

risk-label

Ensure to disable contained database authentication

It is better to disable contained database authentication. Users having ALTER permissions might grant access to the database.

risk-label

Ensure to enable SSL connections to a SQL database instance

It is better to enable SSL connections to a SQL database instance. If in-transit data is encrypted, the data will not be exposed.

risk-label

Ensure to enable checkpoints logging in PostgreSQL

It is better to enable checkpoints logging in PostgreSQL. This provides beneficial information to identify potential performance issues.

risk-label

Ensure to enable logging connections in PostgreSQL

It is better to enable logging connections in PostgreSQL. This provides beneficial information such as session length to identify potential performance issues.

risk-label

Ensure to enable logging disconnections in PostgreSQL

It is better to enable logging disconnections in PostgreSQL. This provides beneficial information such as session length to identify potential performance issues.

risk-label

Ensure to enable temporary file logging should for all temporary files.

It is better to enable temporary file logging as the default. The `value` should be set as `0` in the `log_temp_files` flag to log all files greater than 0 bytes.

risk-label

Ensure Cloud SQL database instances are not publicly exposed

It is better to avoid public access from database instances to prevent the disclosure of sensitive data.

risk-label

Ensure to configure the error log severity in PostgreSQL

It is better to configure the error log severity in PostgreSQL properly. If we set the minimum log severity too high will cause errors not to be logged.

risk-label

Ensure to enable logging of lock waits in PostgreSQL

It is better to enable logging of lock waits in PostgreSQL, which might be the cause of poor performance and availability issues.

Review your Google Cloud SQL settings

You can check if the google_sql_database_instance setting in your .tf file is correct in 3 min with Shisho Cloud.

Parameters

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

The MySQL, PostgreSQL or SQL Server (beta) version to use. Supported values include MYSQL_5_6, MYSQL_5_7, MYSQL_8_0, POSTGRES_9_6,POSTGRES_11, SQLSERVER_2017_STANDARD, SQLSERVER_2017_ENTERPRISE, SQLSERVER_2017_EXPRESS, SQLSERVER_2017_WEB. Database Version Policies includes an up-to-date reference of supported versions.

Used to block Terraform from deleting a SQL Instance.

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.

The name of the instance that will act as the master in the replication setup. Note, this requires the master to have binary_log_enabled set, as well as existing backups.

  • name optional computed - string

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.

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.

The ID of the project in which the resource belongs. If it is not provided, the provider project is used.

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.

  • region optional computed - string

The region the instance will sit in. Note, Cloud SQL is not available in all regions. A valid region must be provided to use this resource. If a region is not provided in the resource definition, the provider region will be used instead, but this will be an apply-time error for instances if the provider region is not supported with Cloud SQL. If you choose not to provide the region argument for this resource, make sure you understand this.

Initial root password. Required for MS SQL Server, ignored by MySQL and PostgreSQL.

The URI of the created resource.

The service account email address assigned to the instance.

  • clone list block

    The timestamp of the point in time that should be restored.

    The name of the instance from which the point in time should be restored.

  • replica_configuration list block

    PEM representation of the trusted CA's x509 certificate.

    PEM representation of the replica's x509 certificate.

    PEM representation of the replica's private key. The corresponding public key in encoded in the client_certificate.

    The number of seconds between connect retries.

    Path to a SQL file in Google Cloud Storage from which replica instances are created. Format is gs://bucket/filename.

    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.

    Time in ms between replication heartbeats.

    Password for the replication connection.

    Permissible ciphers for use in SSL encryption.

    Username for replication connection.

    True if the master's common name value is checked during the SSL handshake.

  • restore_backup_context list block

    The ID of the backup run to restore from.

    The ID of the instance that the backup was taken from.

    The full project ID of the source instance.

  • settings list block

    This specifies when the instance should be active. Can be either ALWAYS, NEVER or ON_DEMAND.

    This property is only applicable to First Generation instances. First Generation instances are now deprecated, see https://cloud.google.com/sql/docs/mysql/deprecation-notice for information on how to upgrade to Second Generation instances. A list of Google App Engine project names that are allowed to access this instance.

    The availability type of the Cloud SQL instance, high availability (REGIONAL) or single zone (ZONAL). For MySQL instances, ensure that settings.backup_configuration.enabled and settings.backup_configuration.binary_log_enabled are both set to true.

    This property is only applicable to First Generation instances. First Generation instances are now deprecated, see here for information on how to upgrade to Second Generation instances. Specific to read instances, indicates when crash-safe replication flags are enabled.

    Configuration to increase storage size automatically. Note that future terraform apply calls will attempt to resize the disk to the value specified in disk_size - if this is set, do not set disk_size.

    The size of data disk, in GB. Size of a running instance cannot be reduced but can be increased.

    The type of data disk: PD_SSD or PD_HDD.

    Pricing plan for this instance, can only be PER_USE.

    This property is only applicable to First Generation instances. First Generation instances are now deprecated, see here for information on how to upgrade to Second Generation instances. Replication type for this instance, can be one of ASYNCHRONOUS or SYNCHRONOUS.

    The machine type to use. See tiers for more details and supported versions. Postgres supports only shared-core machine types such as db-f1-micro, and custom machine types such as db-custom-2-13312. See the Custom Machine Type Documentation to learn about specifying custom machine types.

    A set of key/value user label pairs to assign to the instance.

    Used to make sure changes to the settings block are atomic.

    • backup_configuration list block

      True if binary logging is enabled. If settings.backup_configuration.enabled is false, this must be as well. Cannot be used with Postgres.

      True if backup configuration is enabled.

      Location of the backup configuration.

      True if Point-in-time recovery is enabled.

      HH:MM format time indicating when backup configuration starts.

      The number of days of transaction logs we retain for point in time restore, from 1-7.

    • database_flags list block

      Name of the flag.

      Value of the flag.

    • insights_config list block

      True if Query Insights feature is enabled.

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

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

      True if Query Insights will record client address when enabled.

    • ip_configuration list block

      Whether this Cloud SQL instance should be assigned a public IPV4 address. At least ipv4_enabled must be enabled or a private_network must be configured.

      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 ipv4_enabled must be enabled or a private_network must be configured. This setting can be updated, but it cannot be removed after it is set.

    • location_preference list block

      A Google App Engine application whose zone to remain in. Must be in the same region as this instance.

      The preferred compute engine zone.

    • maintenance_window list block
      • day optional - number

      Day of week (1-7), starting on Monday

      Hour of day (0-23), ignored if day not set

      Receive updates earlier (canary) or later (stable)

  • timeouts single block

Explanation in Terraform Registry

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.

Frequently asked questions

What is Google Cloud SQL Database Instance?

Google Cloud SQL Database Instance is a resource for Cloud SQL of Google Cloud Platform. Settings can be wrote in Terraform.

Where can I find the example code for the Google Cloud SQL Database Instance?

For Terraform, the infracost/infracost, Checkmarx/kics and gilyas/infracost source code examples are useful. See the Terraform Example section for further details.

security-icon

Automate config file reviews on your commits

Fix issues in your infrastructure as code with auto-generated patches.