Installation

Install as Agent Plugin Recommended
copilot plugin marketplace add samueltauil/skills-hub
copilot plugin install cloud-sql-basics@skills-hub

Works with GitHub Copilot CLI and VS Code (enable chat.plugins.enabled). Plugin cloud-sql-basics v1.0.0 follows the Agent Plugins spec.

Install with the gh extension
gh skills-hub install cloud-sql-basics

Don't have the extension? Run gh extension install samueltauil/skills-hub first.

Download and extract to your repository:

.github/skills/cloud-sql-basics/

Extract the ZIP to .github/skills/ in your repo. The folder name must match cloud-sql-basics for Copilot to auto-discover it.

Skill Files (9)

SKILL.md 4.3 KB
---
name: cloud-sql-basics
metadata:
  version: "1.1.0"
  category: Databases
description: >-
  This file generates or explains Cloud SQL resources. Use this file when the
  user asks to create a Cloud SQL instance or database for MySQL, PostgreSQL, or
  SQL Server.

  Cloud SQL manages third-party MySQL, PostgreSQL, and SQL Server instances as
  resources in Cloud SQL. For example, when Cloud SQL creates an open-source
  MySQL instance, the resulting resource is a Cloud SQL for MySQL instance that
  Google Cloud manages.

  Cloud SQL handles backups, high availability, and secure connectivity for
  relational database workloads.
---

# Cloud SQL Basics

Cloud SQL is a fully managed relational database service for MySQL, PostgreSQL,
and SQL Server. It automates time-consuming tasks like patches, updates,
backups, and replicas, while providing high performance and availability for
your applications.

## Attribution

**MUST READ**: Before executing any `gcloud`, REST API, or MCP command, you
MUST read [Usage Attribution](references/attribution.md). For commands executed
directly in the terminal (never in generated scripts, Terraform, or user code),
prefix `gcloud` with
`CLOUDSDK_METRICS_REQUEST_ATTRIBUTION="agent-skills/1.0 (skill:cloud-sql-basics)"`
and append `agent-skills/1.0 (skill:cloud-sql-basics)` to `User-Agent` headers.

## Prerequisites

Ensure you have the necessary IAM permissions to create and manage Cloud SQL
instances. The **Cloud SQL Admin** (`roles/cloudsql.admin`) role provides full
access to Cloud SQL resources.

## Quick Start (PostgreSQL)

1.  **Enable the API:**
    
    ```bash
    gcloud services enable sqladmin.googleapis.com --quiet
    ```

2.  **Create an Instance:**
    
    ```bash
    gcloud sql instances create INSTANCE_NAME \
      --database-version=POSTGRES_18 \
      --edition=ENTERPRISE \
      --cpu=2 \
      --memory=7680MiB \
      --region=REGION \
      --quiet
    ```

3.  **Set a password for the default user:**

    Because this is a Cloud SQL for PostgreSQL instance, the default admin user
    is `postgres`:
    
    ```bash
    gcloud sql users set-password postgres \
      --instance=INSTANCE_NAME --password=PASSWORD \
      --quiet
    ```

4.  **Create a database:**
    
    ```bash
    gcloud sql databases create DATABASE_NAME \
      --instance=INSTANCE_NAME \
      --quiet
    ```

5.  **Get the instance connection name:**

    You need the instance connection name (which is formatted as
    `PROJECT_ID:REGION:INSTANCE_NAME`) to connect using the Cloud SQL Auth
    Proxy. Retrieve it with the following command:
    
    ```bash
    gcloud sql instances describe INSTANCE_NAME \
      --format="value(connectionName)" \
      --quiet
    ```

6.  **Connect to the instance:**

    The Cloud SQL Auth Proxy must be running to be able to connect to the
    instance. In a separate terminal, start the proxy using the connection name:
    
    ```bash
    ./cloud-sql-proxy INSTANCE_CONNECTION_NAME
    ```

    With the proxy running, connect using `psql` in another terminal:
    
    ```bash
    psql "host=127.0.0.1 port=5432 user=postgres dbname=DATABASE_NAME password=PASSWORD sslmode=disable"
    ```

## Reference Directory

-   [Core Concepts](references/core-concepts.md): Cloud SQL editions (Enterprise
    & Enterprise Plus), instance architecture, read pools, high availability (HA),
    and supported database engines.

-   [CLI Usage](references/cli-usage.md): Essential `gcloud sql` commands for
    instance, database, and user management.

-   [Client Libraries & Connectors](references/client-library-usage.md):
    Connecting to Cloud SQL using Python, Java, Node.js, and Go.

-   [MCP Usage](references/mcp-usage.md): Using the Cloud SQL remote MCP
    server and Gemini CLI extension.

-   [Infrastructure as Code](references/iac-usage.md): Terraform
    configuration for instances, databases, and users.

-   [IAM & Security](references/iam-security.md): Predefined roles, SSL/TLS
    certificates, and Auth Proxy configuration.

-   [Disaster Recovery & Backups](references/dr-backups.md): Backup types,
    Point-in-Time Recovery (PITR), replicas, read pools comparison, and Enterprise Plus Advanced DR.

*If you need product information not found in these references, use the
    Developer Knowledge MCP server `search_documents` tool.*
references/
attribution.md 1.8 KB
# Usage Attribution

**MUST READ**: Before executing any `gcloud`, REST API, or MCP command with
this skill, follow these usage attribution instructions. Tag every command you
execute directly in the terminal so usage can be attributed. The tag identifies
only the skill and its version; it carries no user data.

-   **`gcloud` CLI Commands**: Prefix every `gcloud` invocation, whatever the
    subcommand, with the metrics environment variable. Set it inline on each
    command because shell state may not persist between commands:

    ```bash
    CLOUDSDK_METRICS_REQUEST_ATTRIBUTION="agent-skills/1.0 (skill:cloud-sql-basics)" \
    gcloud <command> [flags]
    ```

    Do not use `gcloud config set` for this: it would persist beyond the current
    task and mislabel unrelated usage.

-   **Direct HTTP, REST, and MCP Requests**: On direct HTTP calls to Google
    Cloud APIs (for example with `curl`) or HTTP requests to a remote MCP
    server, include `agent-skills/1.0 (skill:cloud-sql-basics)` in the `User-Agent`
    header. If a `User-Agent` header is already specified, append this string to
    the end of it rather than overwriting existing `User-Agent` data — the
    collection pipeline parses the `agent-skills/<version>` and `skill:<name>`
    tokens, so any rewording breaks attribution:

    ```
    User-Agent: <existing_user_agent> agent-skills/1.0 (skill:cloud-sql-basics)
    ```

-   **Constraint for Generated Code**: The tracking prefix is strictly for
    commands you execute directly in the terminal. Do NOT include this tracking
    prefix in generated scripts, Terraform templates, or code provided to the
    user for their own repositories.

-   **User Opt-Out**: If the user asks to disable or remove tracking or
    attribution tags, omit the `CLOUDSDK_METRICS_REQUEST_ATTRIBUTION` variable
    and custom `User-Agent` suffix from all commands.
cli-usage.md 3.3 KB
# Cloud SQL CLI Usage

The `gcloud sql` command group is used to manage Cloud SQL instances and
related resources.

## Basic Syntax

```bash
gcloud sql [GROUP] [COMMAND] [FLAGS]
```

## Essential Commands

### Instance Management

- **Create a primary instance:**

  ```bash
  gcloud sql instances create my-instance \
      --database-version=POSTGRES_18 \
      --edition=ENTERPRISE \
      --cpu=2 \
      --memory=7680MiB \
      --region=us-central1 \
      --ssl-mode=ENCRYPTED_ONLY \
      --enable-point-in-time-recovery \
      --database-flags=cloudsql.iam_authentication=on \
      --quiet
  ```

- **Create a read pool (Enterprise Plus):**

  Creates a multi-node load-balanced read pool connected to a primary instance.

  ```bash
  gcloud sql instances create my-read-pool \
      --master-instance-name=my-instance \
      --instance-type=READ_POOL_INSTANCE \
      --edition=ENTERPRISE_PLUS \
      --tier=db-perf-optimized-N-2 \
      --node-count=2 \
      --no-assign-ip \
      --quiet
  ```

- **Create a read replica:**

  Creates an individual single-node read replica.

  ```bash
  gcloud sql instances create my-replica \
      --master-instance-name=my-instance \
      --quiet
  ```

- **List instances:**

  ```bash
  gcloud sql instances list --quiet
  ```

- **Describe an instance or read pool:**

  ```bash
  gcloud sql instances describe my-instance --quiet
  ```

- **Restart an instance:**

  ```bash
  gcloud sql instances restart my-instance --quiet
  ```

### Database and User Management

- **Create a database:**

  ```bash
  gcloud sql databases create my-db --instance=my-instance --quiet
  ```

- **Create an IAM database user (Recommended):**

  ```bash
  gcloud sql users create user-email@example.com \
      --instance=my-instance \
      --type=CLOUD_IAM_USER \
      --quiet
  ```

- **Create a user with a static password:**

  ```bash
  gcloud sql users create my-user --instance=my-instance \
      --password=my-password \
      --quiet
  ```

### Operations and Backups

- **List operations:**

  ```bash
  gcloud sql operations list --instance=my-instance --quiet
  ```

- **Create a backup:**

  ```bash
  gcloud sql backups create --instance=my-instance --quiet
  ```

- **Restore from a backup:**

  - *To the same instance that took the backup:*
    ```bash
    gcloud sql backups restore backup_id --restore-instance=my-instance --quiet
    ```

  - *To a different target instance:*
    *(Requires `--backup-instance` to specify the source instance of the backup ID)*
    ```bash
    gcloud sql backups restore backup_id \
        --restore-instance=target-instance \
        --backup-instance=source-instance \
        --quiet
    ```

## Common Flags

- `--project`: Specifies the Google Cloud project ID.

- `--region`: The region where the instance is located.

- `--edition`: Database edition (`ENTERPRISE` or `ENTERPRISE_PLUS`).

- `--tier`: Machine tier (e.g., `db-f1-micro`, `db-perf-optimized-N-2`).

- `--ssl-mode`: SSL enforcement mode (`ALLOW_UNENCRYPTED_AND_ENCRYPTED`, `ENCRYPTED_ONLY`, `TRUSTED_CLIENT_CERTIFICATE_REQUIRED`).

- `--database-flags`: Specifies database parameters (e.g., `cloudsql.iam_authentication=on`).

- `--tags`: Attaches Resource Manager tags (e.g., `tagKeys/123456789012=tagValues/987654321098`).

- `--format`: Changes output format (e.g., `json`, `yaml`).
client-library-usage.md 2.9 KB
# Cloud SQL Client Libraries

Google Cloud provides client libraries and connectors to simplify connecting to
Cloud SQL from various programming languages.

## Getting Started

Ensure you have the latest version of the Google Cloud SDK installed and
authenticated.
[Install Google Cloud SDK](https://cloud.google.com/sdk/docs/install)

### Language Connectors

The Cloud SQL Language Connectors (Python, Java, Go, Node.js) provide a secure
way to connect to the Cloud SQL instance without managing IP allowlists or SSL
certificates.

#### Python

-   **Installation for a Cloud SQL for PostgreSQL instance:**

    ```bash
    pip install "cloud-sql-python-connector[pg8000]"
    ```

-   **Usage Example:**

    ```python
    from google.cloud.sql.connector import Connector
    connector = Connector()
    def getconn():
      conn = connector.connect(
          "project:region:instance",
          "pg8000",
          user="my-user",
          password="my-password",
          db="my-db"
      )
      return conn
    ```

#### Java

-   **Maven Dependencies:**

    The recommended method is to use the Cloud SQL JDBC Socket Factory. Add the
    BOM to your `<dependencyManagement>` section:

    ```xml
    <dependencyManagement>
      <dependencies>
        <dependency>
          <groupId>com.google.cloud.sql</groupId>
          <artifactId>jdbc-socket-factory-bom</artifactId>
          <version>1.18.0</version>
          <type>pom</type>
          <scope>import</scope>
        </dependency>
      </dependencies>
    </dependencyManagement>
    ```

    Then add dependencies for your database:

    *   **PostgreSQL:**
        ```xml  
        <dependencies>
          <dependency>
            <groupId>org.postgresql</groupId>
            <artifactId>postgresql</artifactId>
            <version>42.7.3</version>
          </dependency>
          <dependency>
            <groupId>com.google.cloud.sql</groupId>
            <artifactId>postgres-socket-factory</artifactId>
          </dependency>
        </dependencies>
        ```

    *   **MySQL:**
        ```xml 
        <dependencies>
          <dependency>
            <groupId>com.mysql</groupId>
            <artifactId>mysql-connector-j</artifactId>
            <version>8.0.33</version>
          </dependency>
          <dependency>
            <groupId>com.google.cloud.sql</groupId>
            <artifactId>mysql-socket-factory-connector-j-8</artifactId>
          </dependency>
        </dependencies>
        ```

#### Node.js (TypeScript)

-   **Installation:**

    ```bash
    npm install @google-cloud/cloud-sql-connector
    ```

#### Go

-   **Installation:**

    ```bash
    go get cloud.google.com/go/cloudsqlconn
    ```

## Cloud SQL Admin API

To manage Cloud SQL resources (e.g., list instances) programmatically, use the
`sqladmin` libraries.

-   [Cloud SQL Admin API Overview](https://docs.cloud.google.com/sql/docs/mysql/admin-api.md.txt)
core-concepts.md 5.4 KB
# Cloud SQL Core Concepts

Cloud SQL provides managed relational databases, abstracting the underlying
infrastructure while offering standard database engines.

## Cloud SQL Editions

Cloud SQL offers tier-based pricing and feature editions tailored to different
performance, availability, and operational requirements:

-   **Cloud SQL Enterprise Edition:**
    -   **Target Workloads:** Core business applications requiring standard 
        managed database capabilities.
    -   **Availability SLA:** 99.95% (excludes planned maintenance).
    -   **Performance & Hardware:** Shared core VMs (up to 1 vCPU, 1.7 GB RAM) 
        or Dedicated core VMs (up to 96 vCPU, 624 GB RAM, or N4 up to 80 vCPU / 
        624 GB RAM).
    -   **Maintenance Downtime:** Standard maintenance impact (< 30 seconds).
    -   **Point-in-Time Recovery (PITR):** Up to 7 days of log retention.

-   **Cloud SQL Enterprise Plus Edition:**
    -   **Target Workloads:** Mission-critical workloads requiring highest 
        availability, maximum read performance, and minimal operational downtime.
    -   **Availability SLA:** 99.99% (includes planned maintenance).
    -   **Performance & Hardware:** Powered by high-performance machine series 
        (N2, C4A up to 128 vCPU / 864 GB RAM) and SSD-based Data Cache for up to 
        4x improved read performance.
    -   **Maintenance Downtime:** Sub-second downtime (< 1 second) for maintenance 
        and planned scaling operations.
    -   **Enterprise Features:** Exclusive support for Read Pools, Managed 
        Connection Pooling, Advanced Disaster Recovery (DR) with cross-region 
        write endpoints, and 35-day PITR log retention.
    -   **Upgrades:** Supports in-place edition upgrades from Enterprise with 
        minimal or sub-second downtime.

## Supported Engines

Cloud SQL supports the following database engines (see [supported
versions](https://docs.cloud.google.com/sql/docs/db-versions.md.txt)):

-   **MySQL:** Versions 5.6, 5.7, 8.0, 8.4 (default), and 9.7.

-   **PostgreSQL:** Versions 9.6, 10, 11, 12, 13, 14, 15, 16, 17, and 18
    (default).

-   **SQL Server:** 2017 (Express, Web, Standard, Enterprise), 2019, 2022, and
    2025 (Express, Enterprise, Standard).

## Instance Architecture

Each Cloud SQL instance is powered by a virtual machine (VM) running the
database program.

-   **Primary Instance:** The main read/write connection point.

-   **High Availability (HA):** Provides a standby VM in a different zone with
    automatic failover.

-   **Read Replicas:** Used to scale read traffic and provide local access in
    different regions (individual single-node instances).

-   **Read Pools:** Multi-node load-balanced groups of read nodes designed for 
    high-concurrency read workloads.
    -   **Edition Requirement:** Supported exclusively on **Cloud SQL Enterprise Plus edition** 
        on the new network architecture.
    -   **Node Capacity & Limits:**
        -   **MySQL & PostgreSQL:** 1 to 20 read pool nodes.
        -   **SQL Server:** 1 to 7 read pool nodes.
        -   The combined total of standalone read replicas and read pool nodes per primary instance cannot exceed 20 (MySQL/PostgreSQL) or 7 (SQL Server).
    -   **Scaling Options:**
        -   **Manual Scaling:** Sub-second downtime for manual scale-out/scale-in 
            (adding or removing nodes) and scale-up/scale-down (changing node machine tiers).
        -   **Autoscaling:** Dynamically adjusts node counts between specified
            `--auto-scale-min-node-count` and `--auto-scale-max-node-count`
            thresholds based on `AVERAGE_CPU_UTILIZATION` or `AVERAGE_DB_CONNECTIONS`.
            Supports configurable cooldown periods (default 600s, minimum 60s)
            and optional scale-in disabling (`--auto-scale-disable-scale-in`).
    -   **High Availability & SLA:** Pools with 2 or more nodes are covered under the Cloud SQL SLA, with nodes distributed across zones within the region.
    -   **Routing & Consistency:** Routes traffic based on node process health 
        regardless of replication lag. Logical sessions connecting across 
        requests are not guaranteed read-your-own-writes consistency across 
        different nodes (LSN/GTID progress may differ).
    -   **Topology:** Must replicate directly from the primary instance (cascading read pools or cascading replicas to read pools are not supported).


## Storage and Networking

-   **Persistent Disk:** Scalable and durable network storage attached to the
    VM.

-   **Connectivity:** Supports Private IP (using VPC peering for MySQL and
    PostgreSQL only; or using private services access or Private Service Connect
    for all Cloud SQL engines) and Public IP (with authorized networks or Auth
    Proxy).

## Pricing

Cloud SQL pricing is based on:

-   **Instance Type:** vCPUs and RAM.

-   **Storage:** Amount of data stored and IOPS.

-   **Networking:** Network egress and IP address usage.

-   **DNS pricing:** Charge is per zone per month (regardless of whether you use
    your zone). You also pay for queries against your zones.

-   **Licensing:** Applies to SQL Server only. In addition to instance and
    resource pricing, SQL Server also has a licensing component. High
    availability, or regional instances, will only incur the cost for a single
    license for the active resource. As a managed service, Cloud SQL does not
    support BYOL (Bring your own license).

For the latest pricing, visit: [Cloud SQL
Pricing](https://cloud.google.com/sql/pricing).
dr-backups.md 7.4 KB
# Cloud SQL Disaster Recovery & Backups

Cloud SQL provides multiple mechanisms for data protection, continuous replication, high availability, and disaster recovery (DR).

## Backup Types and Recovery

- **Automated Backups:** Daily instance snapshots taken during a
  user-configurable 4-hour window. Enterprise edition retains 7 backups by
  default; Enterprise Plus edition retains 15 backups by default (configurable
  from 1 to 365 backups for both editions).

- **On-Demand Backups:** Manually created backups that remain stored until explicitly deleted. Useful before performing high-risk schema migrations or administrative changes.

- **Enhanced Backups:** Managed data protection integrated with Google Cloud **Backup and DR Service** for enterprise governance, centralized management, and compliance across projects.
  - **Air-Gapped & Immutable Vaults:** Backups are stored in separate, logically isolated projects to protect against ransomware and accidental deletion.
  - **Extended Retention & Flexible Schedules:** Supports up to **10 years** of retention (compared to 1 year for standard backups) with flexible schedules (hourly, daily, weekly, monthly, or yearly).
  - **Retention Lock:** Enforces non-deletable, non-modifiable backup rules until the specified retention duration expires.
  - **Cross-Project Recovery:** Facilitates recovery of database workloads into different target projects for disaster recovery operations.

- **Point-in-Time Recovery (PITR):** Uses continuous transaction logging (binary logging for MySQL, write-ahead logging for PostgreSQL, transaction logging for SQL Server) to restore an instance to a specific second in time.
  - **Retention Limits:** Up to 7 days (Enterprise edition) or up to 35 days (Enterprise Plus edition).
  - **Storage:** Stored on disk or Cloud Storage depending on configuration.

- **Final Backups:** Automated final state snapshots taken before instance deletion or post-failover rebuilds to protect data against accidental loss.

- **Backup Locations:** Stored by default in the closest multi-region location to the instance, or in custom regional/multi-region storage buckets. Can be restored to the same instance or to a new target instance.

### Standard vs. Enhanced Backups

| Feature | Standard Backups | Enhanced Backups |
| :--- | :--- | :--- |
| **Management** | Instance-level Cloud SQL backups | Centralized Backup and DR Service |
| **Storage Vault** | Same project / multi-region storage bucket | Separate air-gapped immutable backup project |
| **Max Retention** | Up to 1 year | Up to 10 years |
| **Scheduling** | Daily (4-hour configurable window) | Hourly, Daily, Weekly, Monthly, Yearly |
| **Retention Lock** | Not supported | Supported (Enforced retention policy) |
| **Cross-Project Recovery** | Standard instance restore to project targets | Centralized cross-project recovery workflows |
| **Billing Model** | Cloud SQL backup storage pricing | Backup and DR Service pricing model |

## Replication Types and High Availability (HA)

- **High Availability (HA) Standby Replicas:** Provides regional redundancy with a standby VM situated in a secondary zone within the same region. Employs automatic synchronous replication and instant failover in the event of primary hardware or zonal failure.

- **Standalone Read Replicas:** Asynchronous read-only instances (zonal or cross-region) used to scale query traffic and provide local read access.
  - **Node Limits:** Up to 20 total for MySQL/PostgreSQL; up to 7 for SQL Server.

- **Cascading Replicas:** Read replicas that replicate from another read replica rather than directly from the primary instance, reducing replication load on the primary instance.

## Advanced Disaster Recovery (DR)

Exclusive to **Cloud SQL Enterprise Plus Edition**, Advanced DR simplifies regional disaster recovery and drill testing:

- **Designated DR Replica:** A cross-region read replica designated as the target for regional recovery operations.

- **Replica Failover:** Rapid cross-region failover triggered during primary region outages. Promotes the designated DR replica to primary while retaining the old primary in the replication topology for eventual restoration.

- **Switchover:** Zero-data-loss, minimal-downtime operation used for planned
  cross-region failover or routine DR drills. Gracefully reverses roles between
  the primary instance and the DR replica.

- **DNS Write Endpoints:** Provides a global DNS endpoint that automatically shifts write traffic to the newly promoted primary instance following a switchover or replica failover.

## Read Pools vs. Read Replicas in Architecture

| Feature | Standalone Read Replica | Read Pool Node |
| :--- | :--- | :--- |
| **Primary Purpose** | Read scaling & cross-region DR failover target | High-concurrency, load-balanced regional read traffic |
| **Topology** | Direct or cascading from primary instance | Direct replication only (no cascading) |
| **Connection Endpoint** | Individual dedicated IP / Connection name | Single load-balanced IP / Connection name pool |
| **DR & Promotion** | Can be promoted to an independent primary | Cannot be promoted directly to a primary instance |
| **Scaling Mechanism** | Individual instance creation/deletion | Manual scaling or automatic scaling (1-20 nodes) |

## Disaster Recovery & Backup CLI Management

### Backup Management & Operations

- **Enable automated backups and Point-in-Time Recovery (PITR):**
  ```bash
  gcloud sql instances patch my-instance \
      --backup-start-time=03:00 \
      --enable-point-in-time-recovery \
      --quiet
  ```

- **Create an on-demand backup:**
  ```bash
  gcloud sql backups create --instance=my-instance \
      --description="Pre-migration snapshot" \
      --quiet
  ```

- **List available backups:**
  ```bash
  gcloud sql backups list --instance=my-instance --quiet
  ```

- **Restore from a backup:**
  - *To the original instance (overwrites current data):*
    ```bash
    gcloud sql backups restore backup_id --restore-instance=restore-instance --quiet
    ```
  - *To a different target instance:*
    ```bash
    gcloud sql backups restore backup_id \
        --restore-instance=restore-instance \
        --backup-instance=source-instance \
        --quiet
    ```

- **Perform Point-in-Time Recovery (PITR Clone):**
  Clones an instance to a new instance state at a specific RFC 3339 timestamp.
  ```bash
  gcloud sql instances clone source-instance restored-instance \
      --point-in-time="2026-07-16T12:00:00Z" \
      --quiet
  ```

### High Availability & Disaster Recovery Operations

- **Simulate/trigger High Availability (HA) failover:**
  Fail over to the standby instance in the secondary zone for testing.
  ```bash
  gcloud sql instances failover my-ha-instance --quiet
  ```

- **Perform planned DR switchover (Enterprise Plus Edition):**
  Executes a zero-data-loss switchover to a designated cross-region DR replica.
  ```bash
  gcloud sql instances switchover my-dr-replica --quiet
  ```

- **Promote a read replica to an independent primary:**
  ```bash
  gcloud sql instances promote-replica my-replica --quiet
  ```

For more information, see:

- [About Backups in Cloud SQL](https://docs.cloud.google.com/sql/docs/mysql/backup-recovery/manage-standard-backups.md.txt)
- [About High Availability (HA)](https://docs.cloud.google.com/sql/docs/mysql/high-availability.md.txt)
- [About Disaster Recovery in Cloud SQL](https://docs.cloud.google.com/sql/docs/mysql/intro-to-cloud-sql-disaster-recovery.md.txt)
iac-usage.md 2.7 KB
# 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

```terraform
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) or `cloudsql_iam_authentication = "on"` (for MySQL) inside
    the `settings.database_flags` block. The user or service account must also
    be granted the `roles/cloudsql.instanceUser` IAM role.
-   **Deletion Protection:** By default, the Terraform Google provider sets
    `deletion_protection = true`. Set `deletion_protection = false` in dev/test
    environments if you intend to run `terraform destroy`.
-   **Point-in-Time Recovery (PITR):** Setting `enabled = true` in
    `backup_configuration` enables automated daily backups. Explicitly set
    `point_in_time_recovery_enabled = true` to enable continuous WAL archiving
    for PITR.
-   **Edition Selection:** Explicitly declare `edition = "ENTERPRISE"` or
    `edition = "ENTERPRISE_PLUS"` inside `settings` to define the feature set
    and SLA level.

### Reference Documentation

- [Terraform Google Provider - SQL Database Instance](https://registry.terraform.io/providers/hashicorp/google/latest/docs/resources/sql_database_instance)
- [Terraform Google Provider - SQL Database](https://registry.terraform.io/providers/hashicorp/google/latest/docs/resources/sql_database)
- [Terraform Google Provider - SQL User](https://registry.terraform.io/providers/hashicorp/google/latest/docs/resources/sql_user)
iam-security.md 12.6 KB
# Cloud SQL IAM & Security

Cloud SQL uses Identity and Access Management (IAM) to control access to
instances and databases for all supported engines of Cloud SQL. All three engines
such as PostgreSQL, MySQL and SQL Server can be created and secured.

## Predefined IAM Roles

| Predefined Role | Usage |
| :--- | :--- |
| `roles/cloudsql.admin` | Full control over all Cloud SQL resources. |
| `roles/cloudsql.editor` | Manage Cloud SQL resources. Cannot see or modify

 permissions, nor modify users or ssl Certs. Cannot import data or restore from
a backup, nor clone, delete, or promote instances. Cannot start or stop
  replicas. Cannot delete databases, replicas, or backups. |
| `roles/cloudsql.viewer` | Read-only access to Cloud SQL resources. |
| `roles/cloudsql.client` | Connectivity access to Cloud SQL instances from App
 Engine and the Cloud SQL Auth Proxy. Not required for accessing an instance
  using IP addresses. |
| `roles/cloudsql.instanceUser` | Permission to log in to a Cloud SQL
  instance. |
| `roles/cloudsql.schemaViewer` | Role allowing access to a Cloud SQL instance
  schema in Knowledge Catalog. |
| `roles/cloudsql.studioUser` | Role allowing access to Cloud SQL Studio. |

## IAM Best Practices & Least Privilege

To secure Cloud SQL, follow the **Principle of Least Privilege (PoLP)**. Grant
members only the minimum permissions necessary to perform their tasks, and
restrict powerful roles.

-   **Important:** Administrative roles such as `roles/cloudsql.admin` grant full
    control over instances (including deletion and credential management).
    These roles should be granted with extreme caution and reserved exclusively
    for automated deployment pipelines or designated database administrators. Do
    not grant them to general developers or application runtimes.
-   **Separation of Duties:**
    -   Use `roles/cloudsql.admin` for provisioning and instance creation.
    -   Use `roles/cloudsql.client` and `roles/cloudsql.instanceUser` for
        application connectivity and access.
    -   Avoid broad project-level roles like `roles/editor` or `roles/owner` for
        database access.
-   **`setIamPolicy` Risk & Privilege Escalation:**
    -   **Included Roles:** Roles containing `cloudsql.instances.setIamPolicy`
        include `roles/cloudsql.admin`, `roles/resourcemanager.projectIamAdmin`,
        and `roles/owner` (note that `roles/cloudsql.editor` does **not**
        include `setIamPolicy`).
    -   **Escalation Risk:** Any identity with `setIamPolicy` permissions can
        modify IAM policies and grant themselves or others elevated roles,
        leading to complete privilege escalation.
    -   **Best Practices:**
        -   Never grant `setIamPolicy` permissions to application runtimes or
            general developers.
        -   Restrict `setIamPolicy` exclusively to automated CI/CD deployment
            pipelines or designated security administrators.
        -   Enable Data Access audit logging for IAM policy changes and use
            IAM Role Recommendations to detect over-privileged bindings.

### Example: Granting Permissions to Create Instances

To allow a deployment service account to provision Cloud SQL instances, grant
it the `roles/cloudsql.admin` role at the project level:

```bash
gcloud projects add-iam-policy-binding project_id \
    --member="serviceAccount:deployment_sa@project_id.iam.gserviceaccount.com" \
    --role="roles/cloudsql.admin"
```

## Secure Connectivity

-   **Cloud SQL Auth Proxy:** The recommended way to connect securely. It
    provides IAM-based authentication and end-to-end encryption without
    requiring SSL/TLS certificates or authorized networks.

-   **Private IP:** Use VPC, private services access, or Private Service Connect
    (PSC) to keep database traffic within the Google Cloud network.

-   **Authorized Networks:** If using Public IP, restrict access to specific
    CIDR ranges.
-   **VPC Service Controls (VPC-SC):** Establish a security perimeter around
    your database instances to prevent data exfiltration.

-   **Server Certificate Authorities (CA):** Choose a CA hierarchy (`serverCaMode`)
    to sign database server certificates:
    - `GOOGLE_MANAGED_INTERNAL_CA` (Per-instance CA): Dedicated unique CA per
      instance.
    - `GOOGLE_MANAGED_CAS_CA` (Shared CA): Regional shared CA managed by Google.
    - `CUSTOMER_MANAGED_CAS_CA` (Customer-managed CA): Integrates with your own
      CA Service pool.
    - **Recommendation:** Use **Customer-managed CA** for maximum security to
      maintain ownership of the trust anchor, utilize modern ECDSA 384-bit (EC
      P-384) keys, and support custom DNS naming.

-   **SSL/TLS Enforcement:** Enforce encryption for all incoming connections
    by configuring the instance `sslMode` (or `--ssl-mode` in CLI / `ssl_mode` 
    in Terraform):
    - `ALLOW_UNENCRYPTED_AND_ENCRYPTED`: Default mode; allows both unencrypted 
       and encrypted connections.
    - `ENCRYPTED_ONLY`: Restricts connections to SSL/TLS encrypted traffic only.
    - `TRUSTED_CLIENT_CERTIFICATE_REQUIRED`: Enforces Mutual TLS (mTLS), 
       requiring client certificates.
    - **Recommendation:** Use **`ENCRYPTED_ONLY`** or
      **`TRUSTED_CLIENT_CERTIFICATE_REQUIRED`** to prevent transmission of 
      credentials in clear text.
    - *Note:* Enforcing SSL requires an automatic instance restart for MySQL and 
      SQL Server. For PostgreSQL, the change applies to new connections without 
      restarting, but existing unencrypted connections remain active until a 
      manual restart.

## Data Security

-   **Encryption at Rest:** All data is encrypted by default. Use
    Customer-Managed Encryption Keys (CMEK) for additional control.

-   **IAM Database Authentication:** Authenticate to the database using IAM
    users or service accounts instead of static passwords (available for MySQL
    and PostgreSQL).

-   **Least Privilege IAM Roles:**
    - Grant the application's service account the roles/cloudsql.client role.
    - Grant database login rights using roles/cloudsql.instanceUser.
    - Avoid assigning admin roles like roles/cloudsql.admin to applications.

-   **Password Policies:** Enforce security requirements for built-in database users:
    - **Instance-level policy:** Configure a `password_validation_policy` (via
      Terraform or CLI) to enforce minimum length, complexity checks
      (`COMPLEXITY_DEFAULT`), password reuse restrictions, and to disallow
      username substrings.
    - **User-level policy (MySQL 8.0+):** Enforce password expiration, account
      locking after failed attempts (`--password-policy-allowed-failed-attempts`),
      and current password verification using `gcloud sql users set-password-policy`.
    - **Recommendation:** Use IAM Database Authentication where possible to
      bypass database passwords entirely. For built-in accounts, enable the
      instance-level password validation policy.

-   **Client-Side Encryption:** Protect sensitive data at the column level (e.g.,
    credit card numbers, PII) before writing to the database:
    -   Encrypt data using cryptographic libraries like **Tink** combined with
        keys stored in **Cloud KMS**.
    -   Enforces double access control: a client must have both database query
        access and IAM permissions to decrypt the Cloud KMS key.

## Audit Logging

Cloud SQL supports both Google Cloud-level auditing and database engine-level
auditing to track administrative and database access events.

-   **Cloud Audit Logs:** Admin Activity logs are enabled by default. To track
    data access, you must explicitly enable **Data Access audit logs** for the
    Cloud SQL Admin API in your project's IAM configuration.
-   **Database Auditing:** Enable database-specific plugins to log SQL queries,
    logins, and local actions to Cloud Logging:
    -   **MySQL:** Enable the `cloudsql_mysql_audit` database flag (requires an
        instance restart).
    -   **PostgreSQL:** Set the `cloudsql.enable_pgaudit` flag to `on` (requires
        an instance restart), run `CREATE EXTENSION pgaudit;` in the database,
        and configure the `pgaudit.log` flag (e.g., set to `all` or `write`).
    -   **SQL Server:** Specify a Cloud Storage bucket using the
        `--audit-bucket-path` flag to upload audit logs (requires an instance
        restart).

## Brute-Force Protection & Threat Detection

Cloud SQL provides built-in mechanisms and integration with Security Command
Center (SCC) to detect and protect instances against brute-force attacks:

-   **Automated Login Throttling:** Cloud SQL tracks failed connection attempts.
    When consecutive failures exceed a threshold, Cloud SQL logs a warning with
    the IP address and username, and automatically introduces real-time
    response delays (throttling) to slow down attack attempts.
-   **Account Lockout (MySQL 8.0+):** Enforce user password policies to lock
    accounts after a set number of failed attempts using
    `--password-policy-allowed-failed-attempts`.
-   **Security Command Center (SCC):** Event Threat Detection analyzes Cloud
    Logging to alert on repeated failed login attempts, unexpected superuser
    queries, or data exfiltration events.
-   **Recommended Mitigation:** Use IAM Database Authentication or the Cloud
    SQL Auth Proxy to bypass database passwords entirely and eliminate static
    credential brute-force vectors.

## Organization Policies

-   **Cloud SQL organization policies:** Organization policies let organization
    administrators set restrictions on how users can configure instances under
    that organization.

## Resource Manager Tags

Resource Manager tags are key-value pairs that can be attached to Cloud SQL
instances to manage access, IAM conditions, and organization policies.

-   **IAM Enforcement:** Unlike labels (which are for billing/grouping), tags
    integrate with IAM policies. You can restrict actions (e.g., preventing
    instance deletion) based on tags like `environment/production`.
-   **IAM Conditions:** Combine tags with IAM conditions to grant permissions
    only to instances with specific tag bindings.
-   **Tag Format:** In `gcloud` commands, reference tags using either:
    -   **Resource IDs (Recommended):** `tagKeys/TAG_KEY_ID=tagValues/TAG_VALUE_ID`
        (e.g., `tagKeys/123456789012=tagValues/987654321098`)
    -   **Namespaced Path:** `ORGANIZATION_ID/KEY_SHORT_NAME/VALUE_SHORT_NAME`
        (e.g., `123456789012/environment/production`)
-   **gcloud configuration:** Attach tags when creating instances using the
    `--tags` flag:
    ```bash
    gcloud sql instances create instance_name \
        --tags="tagKeys/123456789012=tagValues/987654321098" \
        --database-version=POSTGRES_18 \
        --edition=ENTERPRISE \
        --cpu=2 \
        --memory=7680MiB \
        --region=region
    ```

## Service Accounts

-   **Service Identity:** Cloud SQL uses an instance service account
    (`p[PROJECT_NUMBER]-[UNIQUE_ID]@gcp-sa-cloud-sql.iam.gserviceaccount.com`)
    for tasks like exporting a SQL dump file to Cloud Storage. Service agent
    accounts (`service-PROJECT_NUMBER@gcp-sa-cloud-sql.iam.gserviceaccount.com`)
    are used only for internal management tasks.


For more information, see:

- [About Access Control - Cloud SQL for MySQL](https://docs.cloud.google.com/sql/docs/mysql/instance-access-control.md.txt)
- [About Access Control - Cloud SQL for PostgreSQL](https://docs.cloud.google.com/sql/docs/postgres/instance-access-control.md.txt)
- [About Access Control - Cloud SQL for SQL Server](https://docs.cloud.google.com/sql/docs/sqlserver/instance-access-control.md.txt)
- [Configure SSL/TLS & CAs - Cloud SQL for MySQL](https://docs.cloud.google.com/sql/docs/mysql/configure-ssl-instance.md.txt)
- [Configure SSL/TLS & CAs - Cloud SQL for PostgreSQL](https://docs.cloud.google.com/sql/docs/postgres/configure-ssl-instance.md.txt)
- [Customer-Managed CAs - Cloud SQL for MySQL](https://docs.cloud.google.com/sql/docs/mysql/customer-managed-ca.md.txt)
- [Database Audit Logging - Cloud SQL for MySQL](https://docs.cloud.google.com/sql/docs/mysql/use-db-audit.md.txt)
- [Database Audit Logging (pgAudit) - Cloud SQL for PostgreSQL](https://docs.cloud.google.com/sql/docs/postgres/pg-audit.md.txt)
- [Database Audit Logging - Cloud SQL for SQL Server](https://docs.cloud.google.com/sql/docs/sqlserver/db-audit.md.txt)
- [Client-Side Encryption - Cloud SQL for MySQL](https://docs.cloud.google.com/sql/docs/mysql/client-side-encryption.md.txt)
- [Manage Resource Manager Tags - Cloud SQL](https://docs.cloud.google.com/sql/docs/mysql/manage-tags.md.txt)
- [Brute-Force Protection - Cloud SQL for MySQL](https://docs.cloud.google.com/sql/docs/mysql/use-brute-force-protection.md.txt)
- [Brute-Force Protection - Cloud SQL for PostgreSQL](https://docs.cloud.google.com/sql/docs/postgres/use-brute-force-protection.md.txt)
mcp-usage.md 3.2 KB
# Cloud SQL MCP Usage

Cloud SQL can be managed via the Model Context Protocol (MCP), which allows
agents to manage database instances, execute SQL queries, and automate backup or
migration workflows.

MCP is available via remote Google Cloud MCP servers and through local execution
with the MCP Toolbox.

## Google Cloud MCP for Cloud SQL

The Cloud SQL MCP server includes the following tools:

-   `clone_instance`: Creates a Cloud SQL instance as a clone of a source
    instance.
-   `create_backup`: Creates an on-demand backup of a Cloud SQL instance.
-   `create_instance`: Initiates the creation of a Cloud SQL instance.
-   `create_user`: Creates a database user for a Cloud SQL instance.
-   `execute_sql`: Executes any valid SQL statements (DDL, DCL, DQL, DML) on a
    Cloud SQL instance.
-   `execute_sql_readonly`: Safely executes read-only SQL queries on a Cloud
    SQL instance.
-   `get_instance`: Gets details and status of a Cloud SQL instance.
-   `get_operation`: Gets the status of a long-running operation in Cloud SQL.
-   `import_data`: Imports data into a Cloud SQL instance from Cloud Storage.
-   `list_instances`: Lists all Cloud SQL instances in a project.
-   `list_users`: Lists all database users for a Cloud SQL instance.
-   `postgres_upgrade_precheck`: Performs pre-checks before upgrading
    PostgreSQL engine versions.
-   `restore_backup`: Restores a backup to a Cloud SQL instance.
-   `update_instance`: Updates supported settings of a Cloud SQL instance.
-   `update_user`: Updates a database user for a Cloud SQL instance.

## Server Toolsets & IAM Requirements

-   **Full MCP Set Endpoint:** `https://sqladmin.googleapis.com/mcp` (Exposes
    all management, query, and backup tools).
-   **Read-Only Toolset Endpoint:**
    `https://sqladmin.googleapis.com/mcp/readonly` (Restricts access to
    read-only tools like `execute_sql_readonly`).
-   **Required IAM Role:** Using the Cloud SQL remote MCP server requires the
    `roles/mcp.toolUser` role in addition to Cloud SQL resource roles (e.g.,
    `roles/cloudsql.admin` or `roles/cloudsql.editor`).

## Setup Instructions

For remote server setup, see the documentation for:
-   [PostgreSQL MCP](https://docs.cloud.google.com/sql/docs/postgres/use-cloudsql-mcp.md.txt)
-   [MySQL MCP](https://docs.cloud.google.com/sql/docs/mysql/use-cloudsql-mcp.md.txt)
-   [SQL Server MCP](https://docs.cloud.google.com/sql/docs/sqlserver/use-cloudsql-mcp.md.txt)

## Supported Operations

Agents using the Cloud SQL MCP can:

-   Automate database schema migrations.
-   Create and restore instance backups on-demand.
-   Run engine version upgrade pre-checks (PostgreSQL).
-   Perform health checks and monitor operation logs.
-   Assist in debugging SQL performance issues using read-only or full SQL
    execution tools.

## MCP toolbox for databases

MCP toolbox for databases can be installed locally and provide various
predefined and custom tools for Cloud SQL. Read more about MCP Toolbox in the
documentation.

-   [Cloud SQL for PostgreSQL](https://mcp-toolbox.dev/integrations/cloud-sql-pg/source/)
-   [Cloud SQL for MySQL](https://mcp-toolbox.dev/integrations/cloud-sql-mysql/source/)
-   [Cloud SQL for SQL Server](https://mcp-toolbox.dev/integrations/cloud-sql-mssql/source/)

License (Apache-2.0)

View full license text
Licensed under the Apache License, Version 2.0. See https://github.com/google/skills/blob/main/LICENSE