# SkillPatch skill: alloydb-basics

This skill guides agents through managing AlloyDB for PostgreSQL resources including clusters, instances, and backups. It provides quick-start CLI workflows, reference documentation links, and integration guidance for AlloyDB MCP tools to enable automated database operations. It also covers security best practices, IAM authentication, and AI-powered database features.

You (the agent) were given this URL and asked to use this skill. This is a **public** skill — no SkillPatch account, API key, or prior setup is required. Two ways to use it:

**1. Use it right now** — the skill's complete file tree (SKILL.md + all reference files) is inlined below; read `SKILL.md` first, then follow it, consulting the other files as it directs.

**2. Install the exact package onto disk** (recommended if you can run a shell — this reproduces the skill byte-for-byte, including any binary assets that can't be inlined):

```bash
mkdir -p .claude/skills/alloydb-basics
curl -sSL https://skillpatch.dev/install_skill/alloydb-basics | tar -xz -C .claude/skills/
```

(`.claude/skills/` is Claude Code's convention; use whatever directory your agent loads skills from.)


---

## Skill files (7)

- `SKILL.md`
- `references/cli-usage.md`
- `references/client-library-usage.md`
- `references/core-concepts.md`
- `references/iac-usage.md`
- `references/iam-security.md`
- `references/mcp-usage.md`


### `SKILL.md`

````markdown
---
name: alloydb-basics
metadata:
  category: Databases
description: >-
  Manages clusters, instances, and backups for AlloyDB for PostgreSQL, and
  integrates with AlloyDB model context protocol (MCP) tools for automated database operations.
---

# AlloyDB Basics

AlloyDB for PostgreSQL is a managed, PostgreSQL-compatible database service
designed for enterprise-grade performance and availability. It utilizes a
disaggregated compute and storage architecture to scale resources independently.
It also provides AlloyDB AI, a collection of features that includes AI-powered
search (vector, hybrid search, and AI functions), natural language capabilities,
conversational analytics, and inference features like forecasting and model
endpoint management to help developers build AI apps faster.

## Quick Start

1.  **Enable the AlloyDB API:**

    ```bash
    gcloud services enable alloydb.googleapis.com --quiet
    ```

2.  **Create a Cluster:**

    ```bash
    gcloud alloydb clusters create my-cluster --region=us-central1 \
        --password=my-password --network=my-vpc \
        --quiet
    ```

    *Note: For production, we recommend using IAM database authentication
    instead of passwords. If passwords must be used, use secure secret
    management (e.g., Secret Manager) instead of passing passwords in
    cleartext.*

3.  **Create a Primary Instance:**

    ```bash
    gcloud alloydb instances create my-primary --cluster=my-cluster \
        --region=us-central1 --instance-type=PRIMARY --cpu-count=2 \
        --quiet
    ```

## Reference Directory

-   [Core Concepts](references/core-concepts.md): Architecture, disaggregated
    storage, and performance features.

-   [CLI Usage](references/cli-usage.md): Essential `gcloud alloydb` commands
    for cluster and instance management.

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

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

-   [Infrastructure as Code](references/iac-usage.md): Terraform
    configuration and deployment examples.

-   [IAM & Security](references/iam-security.md): Predefined roles, service
    agents, and database authentication.

*If you need product information not found in these references, use the
    Developer Knowledge MCP server `search_documents` tool.*
````


### `references/cli-usage.md`

```markdown
# AlloyDB CLI Usage

AlloyDB resources are managed using the `gcloud alloydb` command group.

## Clusters

1. Create a cluster: `gcloud alloydb clusters create CLUSTER_ID --region=REGION
   --password=PASSWORD`

2. List clusters: `gcloud alloydb clusters list --region=REGION`

3. Get cluster info: `gcloud alloydb clusters describe CLUSTER_ID
   --region=REGION`

4. Delete a cluster: `gcloud alloydb clusters delete CLUSTER_ID --region=REGION`

## Instances

1. Create a primary instance: `gcloud alloydb instances create INSTANCE_ID
   --cluster=CLUSTER_ID --region=REGION --instance-type=PRIMARY --cpu-count=8`

2. Create a read pool instance: `gcloud alloydb instances create INSTANCE_ID
   --cluster=CLUSTER_ID --region=REGION --instance-type=READ_POOL
   --read-pool-node-count=2 --cpu-count=2`

3. List instances: `gcloud alloydb instances list --cluster=CLUSTER_ID
   --region=REGION`

4. Restart an instance: `gcloud alloydb instances restart INSTANCE_ID
   --cluster=CLUSTER_ID --region=REGION`

## Backups

1. Create a backup: `gcloud alloydb backups create BACKUP_ID
   --cluster=CLUSTER_ID --region=REGION`

2. List backups: `gcloud alloydb backups list --region=REGION`

```


### `references/client-library-usage.md`

````markdown
# AlloyDB Client Libraries & Connectors

Google Cloud provides various ways to connect to AlloyDB idiomatically from
different programming languages. We optionally provide Client Libraries and
Connectors to facilitate secure authentication and connection from your clients
to your AlloyDB instances. These tools handle the management of SSL
certificates, firewall rules, and IAM Auth token automation.

## AlloyDB Language Connectors

Language connectors are libraries for Python, Java, and Go designed for
developers who prefer an integrated, driver-level experience over the
operational overhead of managing the Auth Proxy as a separate binary.

### Python

-   **Installation:**

  ```bash
  pip install "google-cloud-alloydb-connector[pg8000]" sqlalchemy
  ```

-   **Usage Example:**

  ```python
  import sqlalchemy
  from google.cloud.alloydbconnector import Connector

  INSTANCE_URI = "projects/MY_PROJECT/locations/MY_REGION/clusters/MY_CLUSTER/instances/MY_INSTANCE"

  with Connector() as connector:
      pool = sqlalchemy.create_engine(
          "postgresql+pg8000://",
          creator=lambda: connector.connect(
              INSTANCE_URI,
              "pg8000",
              user="my-user",
              password="my-password",
              db="my-db",
          ),
      )

      with pool.connect() as conn:
          result = conn.execute(sqlalchemy.text("SELECT NOW()")).fetchone()
          print(result)
  ```

### Java

-   **Maven Dependency:**

  ```xml
  <dependency>
    <groupId>com.google.cloud</groupId>
    <artifactId>alloydb-jdbc-connector</artifactId>
  </dependency>
  <dependency>
    <groupId>org.postgresql</groupId>
    <artifactId>postgresql</artifactId>
  </dependency>
  <dependency>
    <groupId>com.zaxxer</groupId>
    <artifactId>HikariCP</artifactId>
  </dependency>
  ```

-   **Configuring a Connection Pool:**

    We recommend using HikariCP for connection pooling. To use HikariCP with the
    Java Connector, you will need to set the usual properties (e.g., JDBC URL,
    username, password, etc) and you will need to set two Connector specific
    properties:

    *   `socketFactory` should be set to
        `com.google.cloud.alloydb.SocketFactory`
    *   `alloydbInstanceName` should be set to the AlloyDB instance you want to
    connect to, e.g.:
        `projects/<PROJECT>/locations/<REGION>/clusters/<CLUSTER>/instances/<INSTANCE>`

    Basic configuration of a data source looks like this:

  ```java
  import com.zaxxer.hikari.HikariConfig;
  import com.zaxxer.hikari.HikariDataSource;

  public class ExampleApplication {

    private HikariDataSource dataSource;

    public HikariDataSource getDataSource() {
      HikariConfig config = new HikariConfig();

      // There is no need to set a host on the JDBC URL
      // since the Connector will resolve the correct IP address.
      config.setJdbcUrl(String.format("jdbc:postgresql:///%s", System.getenv("ALLOYDB_DB")));
      config.setUsername(System.getenv("ALLOYDB_USER"));
      config.setPassword(System.getenv("ALLOYDB_PASS"));

      // Tell the driver to use the AlloyDB Java Connector's SocketFactory
      // when connecting to an instance/
      config.addDataSourceProperty("socketFactory",
          "com.google.cloud.alloydb.SocketFactory");
      // Tell the Java Connector which instance to connect to.
      config.addDataSourceProperty("alloydbInstanceName",
          System.getenv("ALLOYDB_INSTANCE_NAME"));

      dataSource = new HikariDataSource(config);
      return dataSource;
    }

    // Use DataSource as usual ...

  }
  ```

    See [end to end
        test](https://github.com/GoogleCloudPlatform/alloydb-java-connector/blob/main/jdbc/postgres/src/test/java/com/google/cloud/alloydb/postgres/PgJdbcIntegrationTests.java)
    for a full example.

    See [About Pool
        Sizing](https://github.com/brettwooldridge/HikariCP/wiki/About-Pool-Sizing)
    for useful guidance on getting the best performance from a connection pool.

### Go

-   **Installation:**

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

-   **Usage Example:**

  ```go
  package main

  import (
      "database/sql"
      "fmt"
      "log"

      "cloud.google.com/go/alloydbconn/driver/pgxv5"
  )

  func main() {
      // Register the AlloyDB driver with the name "alloydb"
      // Uses Private IP by default. See Network Options below for details.
      cleanup, err := pgxv5.RegisterDriver("alloydb")
      if err != nil {
          log.Fatal(err)
      }
      defer cleanup()

      // Instance URI format:
      //   projects/PROJECT/locations/REGION/clusters/CLUSTER/instances/INSTANCE
      db, err := sql.Open("alloydb", fmt.Sprintf(
          "host=%s user=%s password=%s dbname=%s sslmode=disable",
          "projects/my-project/locations/us-central1/clusters/my-cluster/instances/my-instance",
          "my-user",
          "my-password",
          "my-db",
      ))
      if err != nil {
          log.Fatal(err)
      }
      defer db.Close()

      var greeting string
      if err := db.QueryRow("SELECT 'Hello, AlloyDB!'").Scan(&greeting); err != nil {
          log.Fatal(err)
      }
      fmt.Println(greeting)
  }
  ```

## Standard PostgreSQL Drivers

Since AlloyDB is PostgreSQL-compatible, you can also use standard drivers:

-   **Python:** `psycopg2`, `asyncpg`, `pg8000`

-   **Java:** `PostgreSQL JDBC Driver`

-   **Go:** `lib/pq`, `jackc/pgx`

For more details, see: [AlloyDB
Connectors](https://cloud.google.com/alloydb/docs/connect-external).
````


### `references/core-concepts.md`

```markdown
# AlloyDB Core Concepts

AlloyDB for PostgreSQL is a fully managed, PostgreSQL-compatible database
service designed for high performance, scale, and availability. It is built on
top of a cloud-native storage engine that separates compute from storage,
allowing for efficient scaling and high availability.

AlloyDB is ideal for enterprise-grade transactional workloads, such as ERP or
CRM systems, as well as for analytical workloads that benefit from its columnar
engine, and vector workloads using its [vector search
capabilities](https://docs.cloud.google.com/alloydb/docs/ai/perform-vector-search.md.txt).

## Regional Availability

AlloyDB is a regional service. A cluster consists of a primary instance and
optional read pool instances, all of which are located in the same region. The
storage is replicated across multiple zones within the region to ensure high
availability.

## AlloyDB Auth Proxy

The [AlloyDB Auth
Proxy](https://cloud.google.com/alloydb/docs/auth-proxy/connect) is a standalone
tool that can be deployed in any environment, and works by opening a local
socket and proxying connections to your AlloyDB instance.

## Connectivity Options

### Private vs Public IP

When connecting to AlloyDB, you can use either a Private IP or a Public IP:

-   **Private IP:** Your client must be deployed either in the same VPC network
    as your AlloyDB cluster (when using PSA), or have a PSC endpoint in your VPC
    (when using PSC) to connect directly using Private IP. For indirect methods
    of connecting outside your VPC, see [Enable private services
    access](https://cloud.google.com/alloydb/docs/configure-connectivity).
-   **Public IP:** If enabled on your instance, you can connect from outside the
    VPC network.

## Connection Pooling

For production workloads, use connection poolers like **PgBouncer** (integrated
in AlloyDB) to manage high numbers of concurrent connections efficiently.

## Pricing

For up-to-date pricing information, visit the official [AlloyDB
Pricing](https://cloud.google.com/alloydb/pricing) page. Pricing is based on the
number of vCPUs and memory for each instance, as well as the storage used.

```


### `references/iac-usage.md`

````markdown
# AlloyDB Infrastructure as Code Usage

AlloyDB resources can be managed using Terraform via the Google Cloud Provider,
or via Kubernetes Config Connector (KCC).

## Terraform

### Resources

1.  `google_alloydb_cluster`: Manages an AlloyDB cluster.
2.  `google_alloydb_instance`: Manages an AlloyDB instance within a cluster.

### Example

```terraform
data "google_project" "project" {}

resource "google_compute_network" "default" {
  name = "alloydb-network"
}

resource "google_compute_global_address" "private_ip_alloc" {
  name          =  "alloydb-cluster"
  address_type  = "INTERNAL"
  purpose       = "VPC_PEERING"
  prefix_length = 16
  network       = google_compute_network.default.id
}

resource "google_service_networking_connection" "vpc_connection" {
  network                 = google_compute_network.default.id
  service                 = "servicenetworking.googleapis.com"
  reserved_peering_ranges = [google_compute_global_address.private_ip_alloc.name]
}

resource "google_alloydb_cluster" "default" {
  cluster_id = "alloydb-cluster"
  location   = "us-central1"
  network_config {
    network = google_compute_network.default.id
  }

  initial_user {
    password = "alloydb-cluster"
  }

  deletion_protection = false
}

resource "google_alloydb_instance" "default" {
  cluster       = google_alloydb_cluster.default.name
  instance_id   = "alloydb-instance"
  instance_type = "PRIMARY"

  machine_config {
    cpu_count = 2
  }

  depends_on = [google_service_networking_connection.vpc_connection]
}
```

For more information, see the [Google Provider
Reference](https://registry.terraform.io/providers/hashicorp/google/latest/docs/resources/alloydb_cluster).

## Kubernetes Config Connector (KCC)

### Resources

1.  `AlloyDBCluster`: Manages an AlloyDB cluster.
2.  `AlloyDBInstance`: Manages an AlloyDB instance within a cluster.

### Example

```yaml
apiVersion: compute.cnrm.cloud.google.com/v1beta1
kind: ComputeNetwork
metadata:
  name: alloydb-network-kcc
spec:
  routingMode: REGIONAL
  autoCreateSubnetworks: false
---
apiVersion: compute.cnrm.cloud.google.com/v1beta1
kind: ComputeAddress
metadata:
  name: alloydb-kcc-addr
spec:
  location: global
  addressType: INTERNAL
  purpose: VPC_PEERING
  prefixLength: 16
  networkRef:
    name: alloydb-network-kcc
---
apiVersion: servicenetworking.cnrm.cloud.google.com/v1beta1
kind: ServiceNetworkingConnection
metadata:
  name: alloydb-vpc-connection-kcc
spec:
  networkRef:
    name: alloydb-network-kcc
  service: servicenetworking.googleapis.com
  reservedPeeringRanges:
    - name: alloydb-kcc-addr
---
apiVersion: alloydb.cnrm.cloud.google.com/v1beta1
kind: AlloyDBCluster
metadata:
  name: alloydb-cluster-kcc
spec:
  location: us-central1
  networkConfig:
    networkRef:
      name: alloydb-network-kcc
  initialUser:
    password:
      valueFrom:
        secretKeyRef:
          name: alloydb-secret
          key: password
---
apiVersion: alloydb.cnrm.cloud.google.com/v1beta1
kind: AlloyDBInstance
metadata:
  name: alloydb-instance-kcc
spec:
  clusterRef:
    name: alloydb-cluster-kcc
  instanceType: PRIMARY
  machineConfig:
    cpuCount: 2
```

For more information, see the [Config Connector resources](https://docs.cloud.google.com/config-connector/docs/reference/overview.md.txt).

````


### `references/iam-security.md`

```markdown
# AlloyDB IAM & Security

AlloyDB utilizes Google Cloud Identity and Access Management (IAM) to provide
granular access control and robust security features.

## Predefined IAM Roles

The following table describes the predefined roles available for AlloyDB:

| Role Name | Usage |
| :--- | :--- |
| `roles/alloydb.admin` | Full control of all AlloyDB resources. |
| `roles/alloydb.client` | Connectivity access to AlloyDB instances. |
| `roles/alloydb.databaseUser` | Authenticated database-user access to instances. |
| `roles/alloydb.viewer` | Read-only access to all AlloyDB resources. |

## Secure Connectivity

1.  **Network Security:**
    -   **Private IP:** Keeps traffic internal to Google Cloud.
        -   **Private Service Connect (PSC):** Recommended for new
            configurations. Offers enhanced security, better IP management, and
            flexible multi-VPC topologies without peering.
        -   **Private Services Access (PSA):** Uses VPC peering.
    -   **Public IP:** Allows connections from outside GCP.
        -   **ALWAYS** use with **Authorized Networks** to restrict access to
            specific IP ranges.
        -   **NEVER** use `0.0.0.0/0` in Authorized Networks.
    -   **VPC Service Controls (VPC-SC):** Define security perimeters around
        your AlloyDB instances to prevent data exfiltration.

1.  **Encryption:**
    -   **In Transit:** TLS encryption is enforced by default for all
        connections.
    -   **At Rest:** Data is always encrypted, using Google-managed keys by
        default. Customer-Managed Encryption Keys (CMEK) are supported for
        greater control.

1.  **Authentication & Authorization:**
    -   **IAM Authentication:** **Recommended.** Uses Google Cloud Identity and
        Access Management (IAM) principals (users/service accounts) and
        short-lived OAuth tokens. Centralizes access control and avoids database
        passwords.
    -   **Built-in Database Authentication:** Standard PostgreSQL
        username/password. Use strong password policies if this method is
        chosen.
    -   **Database Authorization:** Standard PostgreSQL GRANT / REVOKE
        statements manage permissions within the database, regardless of the
        authentication method.

1.  **Connection Methods:**
    -   **Direct Connection:** Standard PostgreSQL connection.
    -   **AlloyDB Connectors (Auth Proxy & Language Libraries):** **Highly
        Recommended for security.**
        -   Provide connection-level **IAM Authorization**.
        -   Automatically use **mTLS** (Mutual TLS) for encrypted and
            authenticated connections.
        -   Simplify using IAM Database Authentication (tokens are handled
            automatically).
        -   Essential for secure Public IP access without wide open Authorized
            Networks.
        -   Best practice: Run Auth Proxy as a sidecar to the application.

**Key Recommendations for Agents:**

-   **Prioritize Private IP:** Guide users to use Private IP (especially PSC)
    over Public IP whenever their application is within GCP.
-   **Push AlloyDB Connectors:** Strongly recommend AlloyDB Connectors (Auth
    Proxy or language libraries) because they enhance security through IAM
    connection authorization and mTLS, especially crucial for Public IP.
-   **IAM Authentication is Preferred:** Encourages centralized management and
    token-based auth.
-   **Secure Public IP:** If Public IP is necessary, stress the absolute need
    for tightly restricted Authorized Networks.
-   **Leverage Cloud Security Tools:** Remind users to use VPC-SC and Security
    Command Center for monitoring and policy enforcement.

## Data Security

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

- **IAM Database Authentication:** Authenticate to the database using IAM
  identities (users or service accounts) instead of static passwords.

## Service Agents

AlloyDB uses a managed service agent
(`service-PROJECT_NUMBER@gcp-sa-alloydb.iam.gserviceaccount.com`) to manage
resources like storage and backups. Ensure this agent has the necessary
permissions in your project.

For more information, see: [Security, privacy, risk, and compliance for AlloyDB for PostgreSQL](https://docs.cloud.google.com/alloydb/docs/security-privacy-compliance.md.txt).

```


### `references/mcp-usage.md`

```markdown
# AlloyDB MCP Usage

AlloyDB supports a remote Model Context Protocol (MCP) server, allowing AI
applications to interact with AlloyDB resources.

## Endpoint

The AlloyDB MCP server endpoint is regional:
`https://alloydb.REGION.rep.googleapis.com/mcp`

Replace `REGION` with the regional location of the endpoint (e.g.,
`us-central1`).

## Setup and Authentication

1. Enable the AlloyDB API in your project.
2. Grant the `roles/mcp.toolUser` role to the principal making the tool calls.
3. Configure your MCP host to point to the regional endpoint.

For more details, see the [Use the AlloyDB remote MCP
server](https://cloud.google.com/alloydb/docs/ai/use-alloydb-mcp) guide.

## Resources

- [AlloyDB MCP Reference](https://docs.cloud.google.com/alloydb/docs/reference/mcp.md.txt)
- [MCP Toolbox](https://mcp-toolbox.dev/): An open-source alternative to the remote MCP server that runs on a local machine or IDE.
    - [MCP Toolbox AlloyDB Integration](https://mcp-toolbox.dev/integrations/alloydb/source/)
    - [Configure your MCP client](https://docs.cloud.google.com/alloydb/docs/connect-ide-using-mcp-toolbox.md.txt)
- For additional specialized skills including health auditing, performance monitoring, and lifecycle management, install the [AlloyDB for PostgreSQL](https://github.com/gemini-cli-extensions/alloydb) Gemini CLI extension or Claude Plugin.

```
