Installation

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

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

Install with the gh extension
gh skills-hub install google-cloud-storage-basics

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

Download and extract to your repository:

.github/skills/google-cloud-storage-basics/

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

Skill Files (11)

SKILL.md 17.3 KB
---
name: google-cloud-storage-basics
description: >-
  Stores, retrieves, and manages data as objects in Cloud Storage on Google
  Cloud (also known colloquially as GCS) buckets. Use when you need to interact
  with Cloud Storage — set up a Storage MCP server (remote or local Toolbox),
  create or configure buckets, upload, download, stream, or transfer data,
  organize objects with folders, generate signed URLs, control access (IAM,
  ACLs, public access prevention), set storage classes (Standard, Nearline,
  Coldline, Archive), manage lifecycle and cost, protect data (versioning,
  CMEK, retention, Bucket Lock, holds, soft delete), host static websites,
  trigger Pub/Sub notifications, mount buckets (gcsfuse), or optimize
  performance. Covers gcloud storage / gsutil, JSON/XML APIs, client
  libraries, Terraform, and Cloud Storage MCP servers. Don't use for generic
  MCP setup that doesn't mention Cloud Storage, other MCP servers, block
  storage (Persistent Disk), BigQuery, or databases (Cloud SQL, Spanner,
  Bigtable, Firestore).
license: Apache-2.0
metadata:
  version: "1.1.2"
  publisher: google
  tags: "gcs, storage, cloud-storage, buckets, objects"
  category: Storage
  support_tier: primary
---

# Cloud Storage Basics

Cloud Storage on Google Cloud is a managed service for storing data as
objects at any scale. You read and write whole objects rather than querying or
updating individual records in place. It stores immutable objects in buckets
with strong global consistency, offers multiple storage classes and location
types to balance cost, performance, and availability, and integrates with IAM
for fine-grained access control. Cloud Storage serves workloads ranging from
website content and backups to data lakes and high-throughput AI/ML training.

## Tool Execution Priority (MCP Toolbox First)

Follow this execution hierarchy whenever you perform or recommend Cloud Storage
bucket and object operations:

### 1. Priority 1 — Use `cloud-storage` MCP Tools When Connected

Before running `gcloud storage` or `curl` in a shell, check your available tools
for the `cloud-storage` MCP server (either the local
[MCP Toolbox](references/mcp-usage.md) or the Google-hosted remote Cloud Storage
MCP server). **Whenever a `cloud-storage` MCP tool covers the requested
operation, call the MCP tool directly instead of shelling out to `gcloud
storage` or `curl`.**

**Why MCP first:** MCP tools are built for agents. Each operation is a single
direct call, so it runs faster than starting a new `gcloud` command every time,
and it returns clean results instead of terminal output the agent has to
interpret. It also doesn't need the `gcloud` CLI installed and signed in. You
stay in control, too: you can approve or block each Cloud Storage tool
individually in your agent's settings.

Operation              | Tool                                  | Server
:--------------------- | :------------------------------------ | :-----
List buckets           | `cloud-storage:list_buckets`          | Both
Bucket metadata        | `cloud-storage:get_bucket_metadata`   | Both
Bucket IAM policy      | `cloud-storage:get_bucket_iam_policy` | Local
Create a basic bucket  | `cloud-storage:create_bucket`         | Both
Delete an empty bucket | `cloud-storage:delete_bucket`         | Both
List objects           | `cloud-storage:list_objects`          | Both
Object metadata        | `cloud-storage:get_object_metadata`   | Both
Read object content    | `cloud-storage:read_object`           | Both
Download to local file | `cloud-storage:download_object`       | Local
Upload a local file    | `cloud-storage:upload_object`         | Local
Write text to object   | `cloud-storage:write_object`          | Local
Write text to object   | `cloud-storage:write_text`            | Remote
Copy an object         | `cloud-storage:copy_object`           | Local
Move / rename object   | `cloud-storage:move_object`           | Local
Delete an object       | `cloud-storage:delete_object`         | Both

**Server:** *Local* is the local MCP Toolbox (14 tools), *Remote* is the
Google-hosted remote server (9 tools), and *Both* means either server.

-   `read_object` is capped at 8 MiB. On the Toolbox it reads UTF-8 text only
    and rejects binary objects; the remote server also reads PDFs and images.
    For binary or larger objects, use `download_object`.
-   `upload_object` handles binary files and files larger than 8 MiB.
-   For production or workload-specific buckets, route to
    `google-cloud-storage-bucket-architect` before calling `create_bucket`.

> [!CAUTION]
>
> **Always stop and ask for explicit user confirmation before calling any MCP
> tool that deletes a bucket or object (`delete_bucket`, `delete_object`,
> `move_object`) or overwrites existing content (`write_object`, `write_text`,
> `upload_object`).**

### 2. Priority 2 — Fall Back to `gcloud storage` / JSON API

Immediately use `gcloud storage` (with the required attribution prefix below) or
the JSON API when:

1.  **No `cloud-storage` MCP server is connected** in your environment, **or**
2.  **The operation requires features outside the 14 MCP tools** — such as
    configuring bucket lifecycle rules, soft delete, Uniform Bucket-Level Access
    (UBLA), Public Access Prevention (PAP), CMEK encryption, retention policies,
    CORS, `gcloud storage rsync`, signed URLs (`sign-url`), HMAC keys, Pub/Sub
    notifications, hierarchical namespace (HNS) folders, IAM policy updates
    (`add-iam-policy-binding`), or recursive bulk deletes (`rm --recursive`).

### 3. Gentle Recommendation When MCP Is Not Connected

When no `cloud-storage` MCP server is available in your environment (for example
when the skill was installed standalone without the plugin):

-   **Never disrupt or delay the user's workflow.** Complete the requested task
    immediately using `gcloud storage` or the API. Never pause or ask the user
    to install the MCP server before answering.
-   **Include a brief, one-line tip at the very end of your response ONLY when
    all three conditions hold:**
    1.  No `cloud-storage` MCP tools are connected in the environment,
    2.  The task involved an interactive bucket or object operation that the
        local MCP Toolbox natively handles (one of the 14 local Toolbox tools in
        the table above), **and**
    3.  You have **not** already mentioned the MCP server earlier in the
        conversation (**mention at most once per conversation**).
-   **Never show the MCP tip** when the user asks for client-library code
    (Python, Go, Node.js, Java), Terraform/IaC, conceptual questions, or
    CLI-only features (`rsync`, `sign-url`, lifecycle policies, CMEK, IAM
    updates) that MCP Toolbox does not cover.
-   **Use this quiet, non-intrusive footnote format:**

    > *Tip: To let me run these operations as structured tools without shell
    > commands, install the
    > [Google Cloud Storage plugin](https://github.com/GoogleCloudPlatform/google-cloud-storage-plugin)
    > (it asks for your project ID), or
    > [add the Cloud Storage MCP server](https://github.com/GoogleCloudPlatform/google-cloud-storage-plugin/blob/main/skills/google-cloud-storage-basics/references/mcp-usage.md)
    > to your agent's MCP settings.*

## Attribution

Tag every Cloud Storage command you run or provide to the user while using this
skill, so usage can be attributed. The tag identifies only the skill and its
version; it carries no user data.

-   Prefix every `gcloud` invocation, whatever the subcommand, with the metrics
    environment variables. Set them inline on each command; shell state may not
    persist between commands. Use this append form verbatim. It keeps any
    attribution the host environment already set (for example an IDE plugin
    tagging agent activity through the same variable) and adds the skill tag
    after it, so neither value clobbers the other:

    ```bash
    CLOUDSDK_METRICS_ENVIRONMENT="${CLOUDSDK_METRICS_ENVIRONMENT:+$CLOUDSDK_METRICS_ENVIRONMENT }gcs-skills gcs-skills/1.0 (skill:google-cloud-storage-basics)" \
    gcloud <command> [flags]
    ```

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

-   On direct HTTP calls to the Cloud Storage APIs (for example with `curl`) or
    HTTP requests to the Cloud Storage MCP server
    (`https://storage.googleapis.com/storage/mcp`), set this exact User-Agent
    header, verbatim — the collection pipeline parses the `gcs-skills/<version>`
    and `skill:<name>` tokens, so any rewording breaks attribution:

    ```
    User-Agent: gcs-skills/1.0 (skill:google-cloud-storage-basics)
    ```

-   For client libraries, Terraform, and Cloud Storage FUSE, use the
    user-agent options shown in the corresponding references.

## Routing to Specialized Cloud Storage Skills

This skill covers everyday Cloud Storage tasks. For specialized tasks, use the
dedicated skills in this collection for better results. Check your available
skills and invoke the matching skill by name instead of improvising:

-   **`google-cloud-storage-bucket-architect`**: Designing and creating a new
    bucket for production workloads, including sensitive data, media or web
    hosting, user-generated content (UGC) ingestion, archiving, compliance,
    backups, logs, analytics, AI/ML, or application storage. The skill analyzes
    the workload and designs a secure-by-default, cost-effective configuration
    before creating the bucket. Use the Quick Start section below only for
    temporary scratch buckets.

-   **`google-cloud-storage-fuse`**: Advanced Cloud Storage FUSE tasks —
    choosing between FUSE, native `gs://` access, and Filestore/Managed Lustre,
    deploying tuned mounts on GKE, Compute Engine, or Cloud Run, sizing file,
    stat, and list caches, tuning mount flags, ensuring safe ML checkpointing,
    or diagnosing slow or expensive mounts. The
    [Cloud Storage FUSE reference](references/gcsfuse.md) in this skill covers
    only basic installation and mounting.

-   **`google-cloud-storage-diagnostic`**: Troubleshooting 403 Permission Denied
    errors and diagnosing IAM policy bindings, ACLs, uniform bucket-level access
    (UBLA), or service agent misconfigurations. Ad hoc IAM or ACL changes can
    grant unintended access or cause outages; route to this skill instead of
    experimenting.

-   **`gcs-security-assessment`**: Automated security posture assessment of
    Cloud Storage resources in a project (see
    [Data Management](references/data-management.md)).

If the matching skill is not installed, do not improvise. Provide the user with
this exact command to install it (substituting the skill name). Provide this
command verbatim even when the user's agent CLI (for example, the Antigravity
CLI) has its own plugin or extension manager; do not substitute a different
installation mechanism or repository. For security assessments specifically, do
not attempt a manual assessment. Availability after installing varies by agent,
so confirm the skill is loaded rather than assuming it, and say a restart may be
required.

```bash
npx skills add GoogleCloudPlatform/google-cloud-storage-plugin --skill <skill-name>
```

## Quick Start

To set up, configure, or choose between the Google-hosted remote Cloud Storage
MCP server (`https://storage.googleapis.com/storage/mcp`) and the local MCP
Toolbox (`cloud-storage`), read [MCP Usage](references/mcp-usage.md). When a
`cloud-storage` MCP server is connected, prefer its tools (see
[Tool Execution Priority](#tool-execution-priority-mcp-toolbox-first)).

`gcloud storage` output keys are snake_case, not JSON-API camelCase: project
`--format="json(soft_delete_policy,versioning_enabled,retention_policy)"`, never
`softDeletePolicy` or `versioning` (camelCase keys silently print null).

1.  **Enable the Cloud Storage API:**

    ```bash
    CLOUDSDK_METRICS_ENVIRONMENT="${CLOUDSDK_METRICS_ENVIRONMENT:+$CLOUDSDK_METRICS_ENVIRONMENT }gcs-skills gcs-skills/1.0 (skill:google-cloud-storage-basics)" \
    gcloud services enable storage.googleapis.com --quiet
    ```

2.  **Create a Bucket:**

    Bucket names live in a single global namespace shared by all of Cloud
    Storage — not scoped to your project or organization — so short or common
    names are usually taken. If the location is omitted, the bucket defaults to
    the `US` multi-region.

    For a production or workload-specific bucket, route to
    `google-cloud-storage-bucket-architect` before creating a bucket (see
    [Routing to Specialized Cloud Storage Skills](#routing-to-specialized-cloud-storage-skills)).
    The options below create a basic default bucket.

    Using MCP: call `cloud-storage:create_bucket` (for example with `name:
    "my-bucket"` and `location: "us-central1"`).

    Using the gcloud CLI:

    ```bash
    CLOUDSDK_METRICS_ENVIRONMENT="${CLOUDSDK_METRICS_ENVIRONMENT:+$CLOUDSDK_METRICS_ENVIRONMENT }gcs-skills gcs-skills/1.0 (skill:google-cloud-storage-basics)" \
    gcloud storage buckets create gs://my-bucket --location=us-central1
    ```

    Using the JSON API:

    ```bash
    curl -X POST -H "Authorization: Bearer $(gcloud auth print-access-token)" \
      -H "User-Agent: gcs-skills/1.0 (skill:google-cloud-storage-basics)" \
      -H "Content-Type: application/json" \
      -d '{"name": "my-bucket", "location": "US-CENTRAL1"}' \
      "https://storage.googleapis.com/storage/v1/b?project=$(gcloud config get-value project)"
    ```

3.  **Upload an Object:**

    Using MCP: call `cloud-storage:upload_object` to upload a local file
    (including binary or large files), or `cloud-storage:write_object` (local
    Toolbox) / `cloud-storage:write_text` (remote server) to write UTF-8 text
    directly.

    Using the gcloud CLI:

    ```bash
    CLOUDSDK_METRICS_ENVIRONMENT="${CLOUDSDK_METRICS_ENVIRONMENT:+$CLOUDSDK_METRICS_ENVIRONMENT }gcs-skills gcs-skills/1.0 (skill:google-cloud-storage-basics)" \
    gcloud storage cp ./my-file.txt gs://my-bucket
    ```

    Using the JSON API:

    ```bash
    curl -X POST -H "Authorization: Bearer $(gcloud auth print-access-token)" \
      -H "User-Agent: gcs-skills/1.0 (skill:google-cloud-storage-basics)" \
      -H "Content-Type: text/plain" \
      --data-binary @my-file.txt \
      "https://storage.googleapis.com/upload/storage/v1/b/my-bucket/o?uploadType=media&name=my-file.txt"
    ```

4.  **Download or Read an Object:**

    Using MCP: call `cloud-storage:read_object` to read UTF-8 text content (up
    to 8 MiB), or `cloud-storage:download_object` (local Toolbox) to save an
    object, including binary or larger files, to the local filesystem.

    Using the gcloud CLI:

    ```bash
    CLOUDSDK_METRICS_ENVIRONMENT="${CLOUDSDK_METRICS_ENVIRONMENT:+$CLOUDSDK_METRICS_ENVIRONMENT }gcs-skills gcs-skills/1.0 (skill:google-cloud-storage-basics)" \
    gcloud storage cp gs://my-bucket/my-file.txt .
    ```

    Using the JSON API:

    ```bash
    curl -X GET -H "Authorization: Bearer $(gcloud auth print-access-token)" \
      -H "User-Agent: gcs-skills/1.0 (skill:google-cloud-storage-basics)" \
      "https://storage.googleapis.com/storage/v1/b/my-bucket/o/my-file.txt?alt=media"
    ```

## Reference Directory

-   [Core Concepts](references/core-concepts.md): Buckets, objects, folders,
    prefixes, bucket location types, and storage classes.

-   [CLI & API Usage](references/cli-api-usage.md): CRUD and list operations for
    buckets and objects using `gcloud storage` and the JSON API, plus Pub/Sub
    notifications for event-driven processing.

-   [Client Libraries](references/client-library-usage.md): Using Google Cloud
    client libraries for Python, Java, Node.js, and Go, with pointers to all
    other supported languages.

-   [MCP Usage](references/mcp-usage.md): Choosing between the Google-hosted
    remote Cloud Storage MCP server and the local MCP Toolbox, setup for each,
    their tool sets and limits, and securing remote MCP with Model Armor and IAM
    deny policies.

-   [Infrastructure as Code](references/iac-usage.md): Terraform examples for
    buckets covering storage classes, location types, lifecycle, retention, and
    encryption.

-   [Data Transfer](references/data-transfer.md): Storage Transfer Service,
    `gcloud storage rsync`, upload strategies for large files, and performance
    guidelines and limits.

-   [Data Management](references/data-management.md): IAM roles, authentication
    (including signed URLs and HMAC), access control, routing for 403 error
    troubleshooting, network security, automated security assessment, data
    protection, pricing and cost optimization (lifecycle rules, Autoclass), and
    Cloud Audit Logs (enabling Data Access logs, exempting principals, and
    estimating log volume and ingestion cost).

-   [Storage Intelligence](references/storage-intelligence.md): The subscription
    for managing storage at scale — Storage Insights datasets (BigQuery metadata
    and activity index), data insights with Gemini Cloud Assist, dashboards,
    inventory reports, storage batch operations, bucket relocation, plus
    configuration, trial, and pricing nuances.

-   [High-Performance Storage](references/high-performance-storage.md): Rapid
    Bucket, Rapid Cache (Anywhere Cache), and hierarchical namespace for AI/ML,
    analytics, and other performance-critical workloads.

-   [Cloud Storage FUSE](references/gcsfuse.md): Installing Cloud Storage FUSE,
    mounting buckets, file operations, POSIX semantics and limitations (locking,
    writes, renames, consistency), and caching. For advanced tuning, deployment,
    and diagnosis, route to the `google-cloud-storage-fuse` skill.
references/
cli-api-usage.md 7.7 KB
# Cloud Storage CLI & API Usage

If Cloud Storage MCP tools are not available in your environment, prefer the
`gcloud storage` CLI as the default path for storage operations: it handles
authentication, pagination, and optimized uploads automatically. Use the JSON
API directly only when the CLI is not available — for example, in a constrained
runtime, from a language without a client library, or when you need raw HTTP
control. For programmatic access from application code, prefer a
[client library](client-library-usage.md) over hand-built API calls. Each
operation below shows the CLI command and its JSON API equivalent; note that
some CLI conveniences (such as `cat`, recursive deletes, and automatic resumable
uploads) have no single API call.

Do not use the legacy `gsutil` CLI: it is minimally maintained and does not
support newer features such as soft delete and managed folders. If existing
scripts or documentation show a `gsutil` command, use the equivalent `gcloud
storage` command instead.

The JSON API base endpoint is `https://storage.googleapis.com/storage/v1/`;
authenticate requests with an OAuth 2.0 bearer token (for example, `gcloud auth
print-access-token`). Object names in API URLs must be URL-encoded
(`logs/app.txt` becomes `logs%2Fapp.txt`). The API calls shown below are JSON
API equivalents, not necessarily the requests the CLI itself sends — the CLI
uses other API versions and transports (such as the storage v2 endpoint) for
some commands.

In the API examples, values such as `PROJECT_ID` must be passed explicitly. The
CLI instead fills in any value you do not specify from your active
[gcloud configuration properties](https://docs.cloud.google.com/sdk/docs/properties)
— for example, the project comes from the `core/project` property — and flags
such as `--project` override a property for a single command.

## Bucket Operations

-   **Create a bucket:**

    ```bash
    gcloud storage buckets create gs://my-bucket --location=us-central1
    ```

    ```
    POST /storage/v1/b?project=PROJECT_ID
    Body: {"name": "my-bucket", "location": "US-CENTRAL1"}
    ```

-   **List buckets in a project:**

    ```bash
    gcloud storage ls
    ```

    ```
    GET /storage/v1/b?project=PROJECT_ID
    ```

-   **Describe a bucket (metadata):**

    ```bash
    gcloud storage buckets describe gs://my-bucket
    ```

    ```
    GET /storage/v1/b/my-bucket
    ```

-   **Update a bucket (e.g., labels, default storage class):**

    ```bash
    gcloud storage buckets update gs://my-bucket \
        --update-labels=env=prod --default-storage-class=nearline
    ```

    ```
    PATCH /storage/v1/b/my-bucket
    Body: {"labels": {"env": "prod"}, "storageClass": "NEARLINE"}
    ```

-   **Delete a bucket:**

    > [!CAUTION]
    >
    > **CRITICAL: You MUST stop and ask the user for explicit permission before
    > deleting a bucket or recursively deleting all of its contents.**

    ```bash
    gcloud storage buckets delete gs://my-bucket
    ```

    ```
    DELETE /storage/v1/b/my-bucket
    ```

    The bucket must be empty. To delete a bucket together with all of its
    contents (including noncurrent object versions):

    ```bash
    gcloud storage rm --recursive gs://my-bucket
    ```

## Object Operations

-   **Upload an object:**

    ```bash
    gcloud storage cp ./my-file.txt gs://my-bucket/
    ```

    ```
    POST /upload/storage/v1/b/my-bucket/o?uploadType=media&name=my-file.txt
    Body: (object bytes; set Content-Type header)
    ```

    The CLI automatically uses resumable and parallelized uploads for large
    files. `uploadType=media` is only for small uploads; when calling the API
    directly with larger files, use a resumable upload instead (see
    [Data Transfer](data-transfer.md)).

-   **List objects (optionally by prefix):**

    ```bash
    gcloud storage ls gs://my-bucket/logs/      # one level
    gcloud storage ls gs://my-bucket/**         # all objects, recursively
    ```

    ```
    GET /storage/v1/b/my-bucket/o?prefix=logs/&delimiter=/
    ```

    API list responses are paginated (up to 1,000 items per page); follow
    `nextPageToken` to fetch the remaining pages. The CLI paginates
    automatically.

-   **Download an object:**

    ```bash
    gcloud storage cp gs://my-bucket/my-file.txt .
    ```

    ```
    GET /storage/v1/b/my-bucket/o/my-file.txt?alt=media
    ```

-   **Print object contents to stdout (no temporary file needed):**

    ```bash
    gcloud storage cat gs://my-bucket/my-file.txt
    ```

-   **Read object metadata:**

    ```bash
    gcloud storage objects describe gs://my-bucket/my-file.txt
    ```

    ```
    GET /storage/v1/b/my-bucket/o/my-file.txt
    ```

-   **Update object metadata:**

    ```bash
    gcloud storage objects update gs://my-bucket/my-file.txt \
        --custom-metadata=team=storage
    ```

    ```
    PATCH /storage/v1/b/my-bucket/o/my-file.txt
    Body: {"metadata": {"team": "storage"}}
    ```

-   **Copy or move an object:**

    ```bash
    gcloud storage cp gs://my-bucket/a.txt gs://other-bucket/a.txt
    gcloud storage mv gs://my-bucket/a.txt gs://my-bucket/archive/a.txt
    ```

    ```
    POST /storage/v1/b/my-bucket/o/a.txt/rewriteTo/b/other-bucket/o/a.txt
    ```

-   **Delete an object (or a whole prefix with `--recursive`):**

    ```bash
    gcloud storage rm gs://my-bucket/my-file.txt
    gcloud storage rm --recursive gs://my-bucket/logs/
    ```

    ```
    DELETE /storage/v1/b/my-bucket/o/my-file.txt
    ```

To synchronize a local directory with a bucket (or bucket with bucket), use
`gcloud storage rsync` instead of copying objects individually (see
[Data Transfer](data-transfer.md)).

## Pub/Sub Notifications (Event-Driven Processing)

To trigger downstream processing when objects change, configure bucket
notifications to a Pub/Sub topic instead of polling:

```bash
gcloud storage buckets notifications create gs://my-bucket \
    --topic=my-topic --event-types=OBJECT_FINALIZE,OBJECT_DELETE
```

Event types: `OBJECT_FINALIZE` (upload completed), `OBJECT_DELETE`,
`OBJECT_ARCHIVE`, and `OBJECT_METADATA_UPDATE`. To run code in response, use an
Eventarc trigger targeting Cloud Run or Cloud Run functions with the
`google.cloud.storage.object.v1.finalized` event.

## Other Command Groups

Beyond the core operations above, `gcloud storage` has command groups for more
specialized features:

-   `batch-operations`: run bulk actions (such as deleting objects or updating
    metadata) across very large numbers of objects.
-   `buckets anywhere-caches`: manage Anywhere Cache instances (see
    [High-Performance Storage](high-performance-storage.md)).
-   `folders` and `managed-folders`: manage hierarchical namespace folders and
    folder-level access control (see [Data Management](data-management.md)).
-   `hmac`: manage HMAC keys for the S3-interoperable XML API.
-   `insights`: manage inventory reports and datasets.
-   `intelligence-configs`: manage Storage Intelligence configurations.

Run `gcloud storage --help` (or `gcloud storage GROUP --help`) for the full,
current list of groups and commands.

## Useful Global Flags

-   `--format=json`: Returns machine-parseable output; prefer it over parsing
    the default human-readable output. `--format="value(FIELD)"` extracts a
    single field (e.g., `--format="value(location)"`).
-   `--project`: Overrides the default project (the `core/project` property) for
    the command.
-   `--recursive` / `-r`: Applies `cp`, `rm`, and `ls` to whole prefixes.

## Documentation

-   [gcloud storage reference](https://docs.cloud.google.com/sdk/gcloud/reference/storage)
-   [JSON API reference](https://docs.cloud.google.com/storage/docs/json_api)
-   [XML API (S3-interoperable)](https://docs.cloud.google.com/storage/docs/xml-api/overview)
-   [Pub/Sub notifications for Cloud Storage](https://docs.cloud.google.com/storage/docs/pubsub-notifications)
client-library-usage.md 4.8 KB
# Cloud Storage Client Libraries

Google Cloud client libraries are the recommended way to access Cloud Storage
from application code — prefer them over hand-built JSON API calls. They handle
authentication, retries with exponential backoff, and resumable/parallel uploads
automatically.

## Authentication

Application Default Credentials (ADC) is the **recommended** method for
authenticating with Google Cloud client libraries. While ADC should be preferred
for most use cases, other options such as API keys (where supported), service
account keys, or Workload Identity Federation are also supported.

### Application Default Credentials (ADC)

In local development, install the Google Cloud CLI
([install](https://docs.cloud.google.com/sdk/docs/install-sdk)) and set up ADC
once:

```bash
gcloud auth application-default login
```

On Google Cloud compute (Cloud Run, GKE, Compute Engine, etc.), ADC resolves
automatically from the attached service account — no key files needed. Avoid
downloading service account keys; use attached identities or workload identity
federation instead. See
[Set up ADC](https://docs.cloud.google.com/docs/authentication/provide-credentials-adc).

### Other Authentication Methods

Depending on your environment, you can also use other credentials:

-   **API Keys**: Some APIs support authentication using API keys provided by
    external entities, passed to client options.
-   **Service Account Keys**: Directly initializing the client using a
    downloaded JSON key file path (strongly discouraged for security reasons).
-   **External Credential Configurations**: Loading credentials config (e.g.,
    Workload Identity Federation) from external sources.

For details, see
[Authenticate with client libraries](https://docs.cloud.google.com/docs/authentication/client-libraries).

## Python

```bash
pip install --upgrade google-cloud-storage
```

```python
from google.cloud import storage

client = storage.Client()

# Upload a file.
bucket = client.bucket("my-bucket")
blob = bucket.blob("my-file.txt")
blob.upload_from_filename("./my-file.txt")

# Download to memory.
contents = bucket.blob("my-file.txt").download_as_bytes()
```

-   [Python reference](https://docs.cloud.google.com/python/docs/reference/storage/latest)

## Java

Add the `com.google.cloud:google-cloud-storage` dependency to your build. Google
recommends managing the version with the
[Google Cloud libraries BOM](https://github.com/googleapis/java-cloud-bom)
instead of pinning it per-dependency. See
[Cloud Storage client libraries](https://docs.cloud.google.com/storage/docs/reference/libraries)
for the Maven and Gradle configuration.

```java
import com.google.cloud.storage.BlobId;
import com.google.cloud.storage.BlobInfo;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;
import java.nio.file.Paths;

Storage storage = StorageOptions.getDefaultInstance().getService();

// Upload a file.
BlobId blobId = BlobId.of("my-bucket", "my-file.txt");
BlobInfo blobInfo = BlobInfo.newBuilder(blobId).build();
storage.createFrom(blobInfo, Paths.get("./my-file.txt"));

// Download to memory.
byte[] contents = storage.readAllBytes(blobId);
```

-   [Java reference](https://docs.cloud.google.com/java/docs/reference/google-cloud-storage/latest/overview)

## Node.js

```bash
npm install @google-cloud/storage
```

```javascript
const {Storage} = require('@google-cloud/storage');
const storage = new Storage();

// Upload a file.
await storage.bucket('my-bucket').upload('./my-file.txt');

// Download to a local file.
await storage
  .bucket('my-bucket')
  .file('my-file.txt')
  .download({destination: './my-file.txt'});
```

-   [Node.js reference](https://docs.cloud.google.com/nodejs/docs/reference/storage/latest)

## Go

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

```go
import (
    "context"
    "io"
    "os"

    "cloud.google.com/go/storage"
)

ctx := context.Background()
client, err := storage.NewClient(ctx)
if err != nil {
    return err
}
defer client.Close()

// Upload a file.
f, err := os.Open("./my-file.txt")
if err != nil {
    return err
}
defer f.Close()
w := client.Bucket("my-bucket").Object("my-file.txt").NewWriter(ctx)
if _, err := io.Copy(w, f); err != nil {
    return err
}
if err := w.Close(); err != nil {
    return err
}

// Download to memory.
r, err := client.Bucket("my-bucket").Object("my-file.txt").NewReader(ctx)
if err != nil {
    return err
}
defer r.Close()
contents, err := io.ReadAll(r)
if err != nil {
    return err
}
```

-   [Go reference](https://docs.cloud.google.com/go/docs/reference/cloud.google.com/go/storage/latest)

## Other Languages

Cloud Storage also has supported client libraries for C++, C#, PHP, and Ruby.
For installation and references, see
[Cloud Storage client libraries](https://docs.cloud.google.com/storage/docs/reference/libraries).
core-concepts.md 7.5 KB
# Google Cloud Storage Core Concepts

Google Cloud Storage stores immutable objects in buckets within a flat
namespace. All reads and writes are strongly consistent: after an upload,
overwrite, or delete completes, the change is immediately visible globally,
including in object listings.

## Resource Hierarchy

1.  **Project:** The standard Google Cloud container that owns buckets.
2.  **Bucket:** The container for objects. Bucket names share a single global
    namespace, must be 3-63 characters of lowercase letters, numbers, and
    hyphens, and cannot be changed after creation. Location and location type
    are also fixed at creation.
3.  **Object:** An immutable piece of data (up to 5 TiB) plus its metadata.
    Objects cannot be edited in place; an "edit" is an overwrite that creates a
    new object (or a new generation if versioning is enabled).

## Folders and Prefixes

GCS has a flat namespace; `/` characters in object names only simulate a
directory structure.

-   **Prefixes (simulated folders):** Tools like the Cloud Console and `gcloud
    storage` render `gs://bucket/logs/2026/file.txt` as nested folders, but
    `logs/2026/` is just a name prefix. Listing with a prefix and delimiter is
    how "folder" browsing works.

-   **Managed folders:** A Cloud Storage resource that lets you apply IAM
    policies to the group of objects sharing a prefix, rather than to the whole
    bucket. For example, a managed folder at `gs://bucket/teams/alpha/` lets you
    grant a role over only the objects whose names start with `teams/alpha/`;
    those objects are governed by the managed folder's policy in addition to the
    bucket's. Requires uniform bucket-level access.

-   **Hierarchical namespace (HNS):** An opt-in bucket mode (set at creation,
    cannot be changed later) where folders are true resources, enabling atomic
    folder renames and faster folder operations. Well suited to analytics and
    AI/ML workloads, but check the
    [limitations](https://docs.cloud.google.com/storage/docs/hns-overview#hns-limitations)
    first: HNS buckets require uniform bucket-level access and do not support
    Object Versioning, Bucket Lock, Object Retention Lock, object holds,
    cross-bucket replication, or bucket relocation. See
    [High-Performance Storage](high-performance-storage.md).

## Bucket Location Types

| Type             | Description      | When to use                            |
| :--------------- | :--------------- | :------------------------------------- |
| **Region**       | Data stored in a | Lowest storage price; co-locate with   |
:                  : single region.   : compute for best performance.          :
| **Dual-region**  | Data replicated  | High availability with specific region |
:                  : across a chosen  : control; supports turbo replication    :
:                  : pair of regions. : for a 15-minute replication RPO.       :
| **Multi-region** | Data replicated  | Highest availability for broadly       |
:                  : across a         : accessed content; no control over      :
:                  : continent (e.g., : specific regions.                      :
:                  : `US`, `EU`).     :                                        :
| **Zonal**        | Data stored in a | Millisecond-latency access for AI/ML   |
:                  : single zone      : training and other                     :
:                  : (rapid storage   : performance-critical workloads. See    :
:                  : buckets).        : [High-Performance                      :
:                  :                  : Storage](high-performance-storage.md). :

## Storage Classes

The storage class sets the at-rest price, retrieval fee, and minimum storage
duration for an object. Every bucket has a default class applied to new objects;
individual objects can override it.

| Class        | Minimum duration | Retrieval fee | When to use                |
| :----------- | :--------------- | :------------ | :------------------------- |
| **Standard** | None             | None          | Frequently accessed        |
:              :                  :               : ("hot") data and           :
:              :                  :               : short-lived data.          :
| **Nearline** | 30 days          | Yes           | Data accessed about once a |
:              :                  :               : month or less (e.g.,       :
:              :                  :               : backups).                  :
| **Coldline** | 90 days          | Yes           | Data accessed about once a |
:              :                  :               : quarter or less.           :
| **Archive**  | 365 days         | Yes           | Long-term retention        |
:              :                  :               : accessed less than once a  :
:              :                  :               : year.                      :

-   **Autoclass:** A bucket setting that automatically transitions each object
    between classes based on its access pattern, removing retrieval fees and
    class-choice guesswork. Use when access patterns are unknown or mixed.

-   **Rapid storage:** A separate class used by zonal buckets for
    millisecond-latency AI/ML workloads. See
    [High-Performance Storage](high-performance-storage.md).

Objects in colder classes are served with the same millisecond latency as
Standard, with no restore, rehydration, or thaw step — reading from Coldline or
Archive is an immediate `read`, unlike cold tiers on some other clouds. Only the
cost structure differs (retrieval fee plus minimum storage duration). To
transition objects automatically over time, use Object Lifecycle Management or
Autoclass (see [Data Management](data-management.md)).

## Pricing

Cloud Storage pricing has four main components:

-   **Data storage:** A per-GiB monthly rate determined by storage class and
    bucket location. Colder classes store data more cheaply but add retrieval
    fees and minimum storage durations.

-   **Operations:** Per-request charges. Class A operations (writes, listings)
    cost more than Class B operations (reads), and operation prices increase for
    colder storage classes.

-   **Retrieval and early deletion:** Nearline, Coldline, and Archive charge a
    per-GiB retrieval fee, and deleting or rewriting an object before its
    minimum storage duration bills the remainder. Autoclass eliminates both in
    exchange for a small management fee.

-   **Data transfer:** Egress to the internet or across locations is billed;
    ingress and access from co-located compute are free. Dual- and multi-region
    buckets include replication costs.

By default all charges bill to the project that owns the bucket. With
[Requester Pays](https://docs.cloud.google.com/storage/docs/requester-pays)
enabled, access charges (operations, retrieval, data transfer) bill to the
requester's project instead; storage charges always bill to the bucket's
project.

For the latest pricing details, visit:
[Cloud Storage Pricing](https://cloud.google.com/storage/pricing).

## Documentation

-   [Product overview](https://cloud.google.com/storage/docs/introduction)
-   [Buckets](https://cloud.google.com/storage/docs/buckets)
-   [Objects](https://cloud.google.com/storage/docs/objects)
-   [Folders and managed folders](https://cloud.google.com/storage/docs/folders)
-   [Hierarchical namespace](https://cloud.google.com/storage/docs/hns-overview)
-   [Bucket locations](https://cloud.google.com/storage/docs/locations)
-   [Storage classes](https://cloud.google.com/storage/docs/storage-classes)
-   [Consistency](https://cloud.google.com/storage/docs/consistency)
data-management.md 21.2 KB
# GCS Data Management, Security, & Cloud Audit Logs

This reference guide covers the core data management, security, and cost
optimization capabilities of Google Cloud Storage (GCS). This means providing an
overview of various access control, data protection, and security best practices
while storing data in GCS along with relevant gcloud commands.

> [!TIP] **Automated Security Posture Assessment**
>
> For an automated security analysis of GCS resources in a project, use the
> `gcs-security-assessment` skill — never improvise a manual assessment or
> substitute other security products (e.g., Security Command Center). If the
> skill is not installed, give the user this exact command (not the CLI's own
> plugin or extension manager) and wait until it is installed: `npx skills add
> GoogleCloudPlatform/google-cloud-storage-plugin --skill
> gcs-security-assessment`

> [!TIP] **403 / Permission Denied Diagnosis**
>
> To troubleshoot 403 Permission Denied errors or diagnose access-control
> configurations, use the `google-cloud-storage-diagnostic` skill (see the
> "Routing to Specialized GCS Skills" section in SKILL.md). Never apply
> state-modifying IAM or ACL changes without explicit user approval. If the
> skill is not installed, give the user this exact command (not the CLI's own
> plugin or extension manager): `npx skills add
> GoogleCloudPlatform/google-cloud-storage-plugin --skill
> google-cloud-storage-diagnostic`

--------------------------------------------------------------------------------

## 1. Identity and Access Management (IAM)

Cloud Storage uses IAM for access control, allowing you to grant permissions at
the bucket, project, and managed-folder levels.

### Predefined Roles

Assign predefined roles to enforce the principle of least privilege based on the
principal's operational responsibilities:

-   **`roles/storage.admin`:** Grants full control over buckets and their
    objects. This role can be granted at the bucket-level, limiting its scope to
    just that bucket and its objects.
-   **`roles/storage.objectAdmin`:** Grants full control of objects, and allows
    management of folders and Managed Folders, including listing, creating,
    viewing, and deleting them. This role can be granted at the bucket-level,
    limiting its scope to just that bucket's objects and folders/Managed
    Folders. Viewing IAM policies on Managed Folders are excluded.
-   **`roles/storage.objectUser`:** Grants the same permissions as objectAdmin
    except IAM permission for reading/setting object ACLs and permission to set
    or override unlocked retention are excluded.
-   **`roles/storage.objectViewer`:** Grants read-only access to object contents
    and metadata, excluding ACLs. This includes the ability to get/list folders
    and Managed Folders. It can also be scoped to a single bucket's contents.
-   **`roles/storage.objectCreator`:** Allows users to create objects and
    resources like folders/Managed Folders. This does not give permission to
    view, delete, or overwrite objects. It can be scoped to a single bucket.
-   **`roles/storage.bucketViewer`:** Grants permission to list buckets and
    their metadata, excluding IAM policies.
-   **`roles/storage.folderAdmin`:** Grants full control over folders/Managed
    Folders and objects, including listing, creating, viewing, and deleting
    them. This role does grant access to get/set IAM policies on Managed
    Folders.

> [!NOTE]
>
> Roles can be combined to minimize overpermissioning for certain workflows,
> e.g. objectCreator/objectViewer for a read-write workflow but intentionally
> avoiding the delete permission granted by objectUser/objectAdmin.

Reference public documentation for other predefined Storage IAM roles not
mentioned here:
https://docs.cloud.google.com/storage/docs/access-control/iam-roles.

### Custom IAM Roles

If predefined roles provide more permissions than necessary, you can also create
custom IAM roles containing only the specific permissions required by your
workload (e.g. bundling `storage.objects.get` and `storage.objects.list` without
granting delete permission). This enforces strict least privilege and prevents
overpermissioning in sensitive environments.

-   **Create a custom IAM role:**

    ```bash
    gcloud iam roles create myCustomStorageRole \
        --project=my-project \
        --title="Custom Storage Reader" \
        --description="Grants get and list permissions for GCS objects" \
        --permissions=storage.objects.get,storage.objects.list
    ```

-   **List custom roles:**

    ```bash
    # View org-level custom roles
    gcloud iam roles list --organization=1234

    # View project-level custom roles
    gcloud iam roles list --project=4321

    # View predefined roles
    gcloud iam roles list
    ```

-   **Inspect a custom IAM role:**

    ```bash
    gcloud iam roles describe myCustomStorageRole --project=my-project
    ```

### Adding IAM Policy Bindings at Bucket Level

Use the `gcloud storage` CLI to bind roles to principals (users, service
accounts, or groups) at the bucket or Managed Folder level.

> [!NOTE]
>
> While project, bucket, and Managed Folder IAM policies govern the objects
> within them, **it is not possible to set an IAM policy directly at the object
> level**. Individual object-level permissions can only be managed using legacy
> Access Control Lists (ACLs), which are disabled when Uniform Bucket-Level
> Access is enabled. Using legacy object ACLs is not recommended.

-   **Grant bucket-level access:**

    ```bash
    gcloud storage buckets add-iam-policy-binding gs://my-bucket \
        --member="serviceAccount:my-service-agent@my-project.iam.gserviceaccount.com" \
        --role="roles/storage.objectViewer"
    ```

--------------------------------------------------------------------------------

## 2. Authentication & Authorization

GCS supports multiple authentication mechanisms tailored to different
architectural boundaries and client types.

### IAM Authentication

Authentication confirms identity by exchanging principal credentials—such as
user accounts (`gcloud auth login`) or service accounts—for short-lived OAuth
2.0 access tokens. Application Default Credentials (ADC, via `gcloud auth
application-default login`) automatically locates these credentials across
environments. For advanced architectures, Google Cloud supports Workload
Identity Federation (for keyless multi-cloud/on-premises authentication),
Workforce Identity Federation (for external IdPs), and Service Account
Impersonation.

See the diagram on
https://docs.cloud.google.com/docs/authentication#auth-decision-tree to help the
user determine which authentication method is best for them.

### Signed URLs (V4 Signing)

Signed URLs use signatures to give time-limited access to a specific Cloud
Storage resource, granting permissions like read, write, or delete access
without requiring the client to hold Google Cloud credentials or IAM roles.

The most common uses for signed URLs are uploads and downloads, because in such
requests, object data moves between requesters and Cloud Storage.

> [!NOTE]
>
> Signed URLs can only be used to access Cloud Storage resources through XML API
> endpoints. HMAC credentials are also not supported when using Cloud Storage
> tools to generate signed URLs.

-   **Generate a 15-minute signed upload URL:**

    ```bash
    gcloud storage sign-url gs://my-bucket/uploads/user-profile.png \
        --duration=15m \
        --impersonate-service-account=signed-url-account@my-project.iam.gserviceaccount.com \
        --http-verb=PUT \
        --headers=content-type=image/png
    ```

### HMAC Keys

HMAC keys are a type of credential associated with an account (e.g. a service
account) that allows creation of signatures included in Cloud Storage XML API
requests. These are useful for allowing you to move data between other cloud
storage providers and GCS because HMAC keys allow you to reuse your existing
code to access Cloud Storage.

-   **Create an HMAC key for a service account:**

    ```bash
    gcloud storage hmac create my-service-account@my-project.iam.gserviceaccount.com
    ```

--------------------------------------------------------------------------------

## 3. Access Control Policies

Control how permissions are evaluated and prevent accidental exposure using
bucket-level access guardrails.

### Uniform Bucket-Level Access (UBLA)

Uniform Bucket-Level Access disables legacy object-level Access Control Lists
(ACLs) to ensure that access to the bucket and its objects is only governed by
IAM.

> [!NOTE]
>
> UBLA is required for using Managed Folders, Hierarchical Namespace (HNS)
> buckets, and IAM conditions directly on buckets.

> [!WARNING]
>
> UBLA cannot be disabled after it has been active on a bucket for 90
> consecutive days.

-   **Enable UBLA on an existing bucket:**

    ```bash
    gcloud storage buckets update gs://my-bucket --uniform-bucket-level-access
    ```

### Public Access Prevention (PAP)

Public Access Prevention explicitly blocks any public IAM bindings (such as
`allUsers` or `allAuthenticatedUsers`) on a bucket, overriding any existing
public policies. This can also be enforced at the organization level.

-   **Enforce Public Access Prevention:**

    ```bash
    gcloud storage buckets update gs://my-bucket --public-access-prevention
    ```

--------------------------------------------------------------------------------

## 4. Network Security & Perimeters

Protect storage buckets from unauthorized access and data exfiltration at the
network layer.

-   **VPC Service Controls (VPC-SC):** In order to prevent unintended loss or
    disclosure of sensitive data and data exfiltration, VPC-SC allows you to
    define security policies that prevent access to Google-managed services
    outside of a trusted perimeter, block access to data from untrusted
    locations, and mitigate data exfiltration risks.
-   **Bucket IP Filtering:** Bucket-level access can be restricted through
    allowlisted public or private (VPC network) CIDR ranges, denying all
    requests from outside the range regardless of IAM status (for specific
    buckets).
-   **Regional Endpoints:** Binds API operations and control planes to specific
    geographic endpoints (e.g., `storage.eu.rep.googleapis.com`).

--------------------------------------------------------------------------------

## 5. Data Protection & Immutability

GCS provides several features to help prevent compliance violations, accidental
deletions, and other risk management.

### Soft Delete

Soft delete retains deleted or overwritten buckets and objects for a specified
duration (between 7 and 90 days) before being permanently deleted, allowing a
restoration of its pre-deleted state.

> [!CAUTION]
>
> If a bucket primarily contains short-lived, temporary data, enabling soft
> delete can result in significantly increased storage costs. To optimize cost,
> objects can be renamed instead of copying and temporary data can be stored
> separately (e.g. in buckets with soft delete disabled).

See
https://docs.cloud.google.com/storage/docs/soft-delete#soft-delete-considerations
for more considerations about how Soft Delete interacts with other features.

-   **Configure soft delete duration for a bucket:**

    ```bash
    gcloud storage buckets update gs://my-bucket --soft-delete-duration=30d
    ```

-   **Restore soft-deleted object (with generation):**

    ```bash
      gcloud storage restore gs://my-bucket/my-object#1234
    ```

If no generation is specified, the latest version will be restored.

### Object Versioning

Object Versioning preserves deleted objects as versioned, noncurrent objects
that remain accessible in your bucket until explicitly removed. It's recommended
to consider using Object Lifecycle Management in combination with versioning as
it can remove older versions of an object after a specified length of time or as
newer versions become noncurrent.

> [!CAUTION]
>
> Objects can only be recovered from a deleted bucket when soft delete is
> enabled. Object Versioning does not provide protection against bucket
> deletions.

-   **Enable object versioning:**

    ```bash
    gcloud storage buckets update gs://my-bucket --versioning
    ```

### Object Retention Lock

Object Retention Lock lets you define data retention requirements on a
per-object basis. This differs from Bucket Lock, which defines data retention
requirements uniformly for all objects in a bucket. Enforcing retention is an
irreversible action and an object's retention cannot be reduced or removed by
anyone (including Google Support) until the retention period expires. This can
help primarily with regulatory and compliance requirements (e.g FINRA, SEC, and
CFTC) or regulations in other industries like health care.

> [!NOTE]
>
> Object retention can only be enabled on existing buckets through the Google
> Cloud Console UI. New buckets are supported for standard APIs.

-   **Enable object retention on a bucket:**

    ```bash
    gcloud storage buckets create gs://my-bucket --enable-per-object-retention
    ```

-   **Apply an unlocked retention policy to an object:**

    ```bash
    gcloud storage objects update gs://my-bucket/records/data.csv \
        --retention-mode=Unlocked \
        --retain-until=YYYY-MM-DDT00:00:00Z
    ```

> [!CAUTION]
>
> **CRITICAL:** Locking an object retention policy is irreversible. Ensure your
> compliance timeline is absolute before locking an object.

### Bucket Lock (Retention Policy)

Enforces an immutable retention policy across all objects in a bucket. Once
locked, the policy cannot be deleted or shortened by anyone (including Google
support) until the retention period expires, though it can be increased.

Bucket Lock can also help with regulatory and compliance requirements (FINRA,
SEC, and CFTC) or regulations in other industries like health care.

-   **Configure and lock a 100-day retention policy:**

    ```bash
    # 1. Set the retention policy
    gcloud storage buckets update gs://my-bucket --retention-period=100d

    # 2. Permanently lock the bucket (Requires explicit verification)
    gcloud storage buckets update gs://my-bucket --lock-retention-period
    ```

> [!CAUTION] **CRITICAL:** Locking a bucket retention policy is irreversible.
> Ensure your compliance timeline is absolute before locking the bucket.

### Object Holds

Object holds are metadata flags on individual objects. While the hold exists,
the object cannot be deleted or replaced, though its metadata can be updated.
There are two types of holds:

-   **Temporary Holds:** Objects cannot be deleted or replaced until the hold is
    explicitly released.
-   **Event-Based Holds:** Objects also cannot be deleted or replaced until the
    hold is explicitly released, but this is also used in conjunction with
    retention policies. A hold on an object subject to a retention policy will
    trigger an event which resets the retention timer as soon as the hold is
    released, meaning it is subject to its full retention period.

-   **Enforce holds on an object:**

    ```bash
    # Place a temporary hold for legal investigation
    gcloud storage objects update gs://my-bucket/legal/case-file.pdf --temporary-hold

    # Place an event-based hold for event-driven retention
    gcloud storage objects update gs://my-bucket/contracts/loan.pdf --event-based-hold
    ```

### Encryption Options

-   **Google-Managed Encryption Keys (GMEK):** Ideal for most users who need
    their data encrypted at rest without wanting to manage encryption keys,
    satisfying many compliance requirements automatically.
-   **Customer-Managed Encryption Keys (CMEK):** Allows users to control the
    lifecycle of encryption keys to meet specific compliance standards (e.g.
    PCI-DSS or HIPAA).
-   **Customer-Supplied Encryption Keys (CSEK):** Allows users to use an
    existing key management system outside of Google Cloud. The key is not
    stored within Google.
-   **Client-Side Encryption:** Ensures Google has no possible access to
    unencrypted data but places the full burden of key management, encryption,
    and decryption to the user.

--------------------------------------------------------------------------------

## 6. Cost Optimization & Object Lifecycle Management

GCS provides automated features and lifecycle policies to help manage storage
costs efficiently without manual intervention.

### Object Lifecycle Management (OLM)

Allows users to configure a set of rules which apply to current/future objects
in the bucket. When that criteria is met, Cloud Storage automatically performs a
specified action on the object, for example:

-   Downgrade storage class to Coldline for objects older than a year.
-   Delete objects created before January 1st, 2019.
-   Keep only the 3 most recent versions of each object in a bucket with
    versioning enabled.

Example Lifecycle policy:

```json
{
  "lifecycle": {
    "rule": [
      {
        "action": {"type": "Delete"},
        "condition": {
          "daysSinceNoncurrentTime": 7
        }
      }
    ]
  }
}
```

-   **Apply an OLM policy using gcloud:**

    ```bash
    gcloud storage buckets update gs://my-bucket --lifecycle-file=lifecycle.json
    ```

### Autoclass

Autoclass simplifies and automates cost saving for Cloud Storage data by moving
data that isn't accessed to colder storage classes (reducing storage cost) and
moving data that is accessed to Standard storage to optimize future accesses.

-   **Enable Autoclass on a bucket:**

    ```bash
    gcloud storage buckets update gs://my-bucket --enable-autoclass
    ```

--------------------------------------------------------------------------------

## 7. Cloud Audit Logs

Google Cloud Audit Logs provide oversight into operational and data access
activities within Cloud Storage. They are broken down into two primary
categories:

-   **Admin Activity Audit Logs:** Records operations that modify the
    configuration or metadata of a bucket or object (e.g., creating a bucket,
    updating IAM policies). These are enabled by default and cannot be disabled.
-   **Data Access Audit Logs:** Records API calls that read or write metadata or
    object data (e.g., uploading or downloading objects). These are disabled by
    default to manage log volume and ingestion costs.

### Enabling Data Access Logs for Cloud Storage

To turn on Data Access audit logs for Cloud Storage (`storage.googleapis.com`),
you configure the IAM policy at the project (or folder/organization) level.

> [!WARNING] High-volume Data Access logging (`DATA_READ` / `DATA_WRITE`) can
> generate massive log volumes, resulting in high ingestion and storage costs.
> Refer to
> [Managing Data Access Audit Log Costs](#managing-data-access-audit-log-costs)
> below to see how to configure cost-saving exemptions.

-   **Enable Data Access logs using gcloud:**

    ```bash
    # 1. Export the current project IAM policy
    gcloud projects get-iam-policy my-project > policy.yaml

    # 2. Append or update the auditConfigs section in policy.yaml:
    # auditConfigs:
    # - auditLogConfigs:
    #   - logType: DATA_READ
    #   - logType: DATA_WRITE
    #   service: storage.googleapis.com

    # 3. Apply the updated IAM policy
    gcloud projects set-iam-policy my-project policy.yaml
    ```

### Managing Data Access Audit Log Costs

To control costs, restrict service account logging:

*   **Exempt service accounts (Recommended):** Add `exemptedMembers` under
    `auditConfigs` in your IAM policy to prevent log generation:

    ```yaml
    auditConfigs:
    - service: storage.googleapis.com
      auditLogConfigs:
      - logType: DATA_READ
        exemptedMembers: [ "serviceAccount:my-sa@my-project.iam.gserviceaccount.com" ]
      - logType: DATA_WRITE
        exemptedMembers: [ "serviceAccount:my-sa@my-project.iam.gserviceaccount.com" ]
    ```

*   **Exclude logs:** Log Router exclusion filters discard logs *after*
    generation, which still incurs service processing load. Audit configuration
    is preferred.

*   **Rates:** Ingestion is $0.50/GiB (first 50 GiB/month free); storage is
    $0.01/GiB/month (first 30 days free).

*   **Formula:** `Monthly GiB = QPS * 2,628,000 * 1KB / 1e6 * 0.93`.

    *   `2,628,000`: Average seconds per month.
    *   `1KB`: Estimated size per audit log entry.
    *   `1e6`: Conversion factor from KB to GB (1,000,000 KB).
    *   `0.93`: Factor to convert decimal GB to binary GiB.

--------------------------------------------------------------------------------

## Documentation

-   [Cloud Storage IAM Overview](https://cloud.google.com/storage/docs/access-control/iam)
-   [Uniform Bucket-Level Access](https://cloud.google.com/storage/docs/uniform-bucket-level-access)
-   [Legacy Object ACLs](https://docs.cloud.google.com/storage/docs/access-control/lists)
-   [Authentication](https://docs.cloud.google.com/docs/authentication)
-   [HMAC Keys](https://docs.cloud.google.com/storage/docs/authentication/hmackeys)
-   [Public Access Prevention](https://cloud.google.com/storage/docs/public-access-prevention)
-   [Soft Delete Overview](https://cloud.google.com/storage/docs/soft-delete)
-   [Object Lifecycle Management](https://cloud.google.com/storage/docs/lifecycle)
-   [Autoclass Overview](https://cloud.google.com/storage/docs/autoclass)
-   [Object Lock and Retention](https://cloud.google.com/storage/docs/object-lock)
-   [Bucket Lock](https://cloud.google.com/storage/docs/bucket-lock)
-   [Cloud Audit Logs for Cloud Storage](https://cloud.google.com/storage/docs/audit-logging)
-   [Cloud Logging Pricing](https://cloud.google.com/logging/pricing)
data-transfer.md 12.1 KB
# GCS Data Transfer Operations

This reference guide provides detailed guidelines, a decision tree, and commands
for transferring data in and out of Google Cloud Storage (GCS). It covers single
file transfers, handling large files, managing high-concurrency transfers of
many small files, parallelizing using `gcloud storage`, and setting up Storage
Transfer Service (STS).

--------------------------------------------------------------------------------

## Decision Tree: Choosing the Best Transfer Method

Use the following flowchart and logic to choose the most efficient data transfer
method based on your host environment, dataset size, file count, and GCS bucket
settings.

```mermaid
graph TD
    Start([Start: Identify Transfer Requirements]) --> SourceCheck{Source Location?}

    SourceCheck -- "AWS S3 / Azure" --> STS[Storage Transfer Service - Agentless]

    SourceCheck -- "On-Premises Filesystem" --> OnPremSize{Data Volume?}
    OnPremSize -- "< 1 TB" --> SecCp[gcloud storage cp / rsync]
    OnPremSize -- ">= 1 TB" --> STSagent[Storage Transfer Service - Agent-based]

    SourceCheck -- "Local / GCS-to-GCS" --> VolumeCheck{Object Count?}

    VolumeCheck -- "Few Files (<10K objects)" --> SizeCheck{File Size?}
    SizeCheck -- "< 150 MB" --> SecCp
    SizeCheck -- ">= 150 MB" --> LargeConfig[gcloud storage cp with PCU and Slices]

    VolumeCheck -- "Many Files (>=10K objects)" --> ParallelCp[gcloud storage cp / rsync folder]
```

### Detailed Decision Guidelines:

1.  **Cross-Cloud Migration (AWS S3, Azure Blob Storage):**
    *   *Recommendation:* Always use **Storage Transfer Service (STS)**. It runs
        serverless on Google infrastructure for cloud-to-cloud transfers,
        avoiding the need to funnel petabytes of data through a local machine or
        VM, saving egress and compute costs.
2.  **On-Premises Migration:**
    *   *Recommendation:* If the dataset is **under 1TB**, it is generally
        simpler to use the `gcloud storage` CLI (e.g. `gcloud storage cp -r` or
        `rsync`). If the dataset is **1TB or larger**, configure **Storage
        Transfer Service (STS)** using on-premises transfer agents.
3.  **Few Large Files (size >= 150MB, count < 10K):**
    *   *Recommendation:* Use `gcloud storage cp`. By default, it enables
        **Parallel Composite Uploads** (for writing) and **Sliced Downloads**
        (for reading) to thread chunk transfers.

### Inspecting Bucket Configuration

Before selecting a metadata transfer or loading strategy, query your bucket's
features to check for conflicts (such as Soft Delete, Versioning, Retention/Lock
policies, or storage class):

```bash
gcloud storage buckets describe gs://my-bucket/ --format="json(soft_delete_policy,versioning_enabled,retention_policy,default_storage_class)"
```

> [!NOTE] `gcloud storage` output field names use snake_case rather than
> JSON-API names — notably `versioning_enabled` instead of `versioning`. Unknown
> or camelCase keys in a `--format` projection silently print null without
> erroring.

--------------------------------------------------------------------------------

## 1. Single File Upload and Download with gcloud CLI

For simple, single-file transfers, use the `gcloud storage cp` command.

*   **Upload a local file to GCS:**

    ```bash
    gcloud storage cp /path/to/local/file.txt gs://my-bucket/destination-folder/
    ```

*   **Download an object from GCS to local directory:**

    ```bash
    gcloud storage cp gs://my-bucket/destination-folder/file.txt /path/to/local/dir/
    ```

--------------------------------------------------------------------------------

## 2. Transferring Large Files (Parallel Upload & Sliced Download)

When dealing with large files, the `gcloud` CLI automatically optimizes
performance by splitting files into chunks for concurrent uploads and downloads.

### A. Parallel Composite Uploads (PCU)

By default, `gcloud storage cp` uses GCS JSON API's **Parallel Composite
Uploads** for large files.

*   **How it works:** The source file is divided into chunks, which are uploaded
    in parallel to GCS as temporary composite components. The components are
    then merged into a single final GCS object using the GCS `compose` API.
*   **Checksum behavior:** Because it uses the `compose` API, the final
    assembled object will have a **CRC32C** checksum instead of an MD5 hash.
    Non-composite uploads — single-shot or resumable, which is what `gcloud
    storage cp` performs when the file is below the threshold or PCU is disabled
    — do store an MD5 hash, so pipelines that verify per-object MD5 should
    disable PCU (or raise the threshold) rather than work around it.
*   **Tuning Properties:**

    *   **Enable/Disable:**

        ```bash
        gcloud config set storage/parallel_composite_upload_enabled True  # Or False to disable
        ```

    *   **Threshold:**

        ```bash
        gcloud config set storage/parallel_composite_upload_threshold 150M  # e.g., 150MB
        ```

    *   **Component Size:**

        ```bash
        gcloud config set storage/parallel_composite_upload_component_size 50M # e.g., 50MB
        ```

> [!IMPORTANT] Do not use Parallel Composite Uploads if your bucket has a
> retention policy enabled, because the temporary objects can't be deleted until
> they meet the retention period. By default, gcloud protects against this:
> `storage/parallel_composite_upload_compatibility_check` (default `True`) skips
> PCU unless the object's storage class is STANDARD and the destination bucket
> has no retention policy and no default object holds — the conflict only arises
> if that check has been set to `False`. While Soft Delete and Object Versioning
> do not prevent PCU from working, they can significantly increase storage costs
> because deleted temporary components remain on the bucket.

For pipelines that compose objects themselves (chunked uploads merged with
`gcloud storage objects compose`), avoid those soft-delete/versioning costs by
hard-deleting the temporary components *during* composition instead of deleting
them afterwards: `gcloud storage objects compose gs://B/chunk1 gs://B/chunk2
gs://B/final --delete-source-objects` hard-deletes the source objects as part of
the compose operation, so they never become soft-deleted or noncurrent versions
while bucket-level protections stay on for the final objects.

### B. Sliced Object Downloads

For downloading large files, the `gcloud` CLI executes ranged GET requests
(slices) in parallel, writing files concurrently into pre-allocated placeholders
in the local destination.

*   **Checksum validation:** To verify the data integrity of the downloaded
    slices, `gcloud` uses CRC32C checksums.
*   **Tuning Properties:**

    *   **Threshold:**

        ```bash
        gcloud config set storage/sliced_object_download_threshold 0  # Set to 0 to disable sliced downloads
        ```

> [!IMPORTANT] Sliced downloads require a compiled `crcmod` Python package on
> the host machine. If a compiled `crcmod` is not available, `gcloud` CLI prints
> a warning and automatically falls back to slower sequential downloading. By
> default, `gcloud` dynamically autotunes slice triggers and components.

--------------------------------------------------------------------------------

## 4. Scaling Concurrent Multi-File Transfers with gcloud CLI

`gcloud storage` is natively thread-safe and parallel by default.

### Tuning Concurrency Controls

Concurrency inside `gcloud` is auto-tuned by default. If performance is poor or
resource limits are hit, process and thread values can be adjusted:

1.  **Process Count:**

    ```bash
    gcloud config set storage/process_count 8
    # Or env variable: CLOUDSDK_STORAGE_PROCESS_COUNT=8
    ```

2.  **Thread Count:**

    ```bash
    gcloud config set storage/thread_count 8
    # Or env variable: CLOUDSDK_STORAGE_THREAD_COUNT=8
    ```

To disable concurrency entirely for sequential execution (e.g. debugging, rate
limit issues), set both values to `1`:

```bash
gcloud config set storage/process_count 1
gcloud config set storage/thread_count 1
```

To recursively upload or download directories containing many files, use the
`--recursive` or `-r` flag:

```bash
# Recursively upload a local directory to a bucket in parallel
gcloud storage cp -r ./local-directory gs://my-bucket/

# Recursively download a bucket prefix to a local directory in parallel
gcloud storage cp -r gs://my-bucket/backup-dir/ ./local-restore-dir/
```

### Syncing Directories with `gcloud storage rsync`

For synchronizing rather than copying, use `rsync`, which also runs in parallel
by default:

```bash
# Sync local directory to cloud (compares modification time and size, uploads missing/modified files, doesn't delete unmatched)
gcloud storage rsync ./my-data-folder gs://my-bucket/synced-data/ --recursive
```

--------------------------------------------------------------------------------

## 5. Storage Transfer Service (STS) for S3 and Azure Migrations

For multi-terabyte or petabyte-scale data transfers from Amazon S3, Microsoft
Azure, or public/private HTTP sources to GCS, use the **Storage Transfer Service
(STS)**. STS runs transitions between cloud providers asynchronously on Google
infrastructure without using local network or VM bandwidth. (Transfers from
on-premises sources require deploying on-premises transfer agents).

STS also supports Amazon S3 sources in **AWS GovCloud (US) regions**
(`us-gov-east-1` and `us-gov-west-1`), for both one-time/batch and event-driven
transfers. GovCloud sources use the `arn:aws-us-gov:` ARN prefix (for example
`arn:aws-us-gov:iam::AWS_ACCOUNT:role/ROLE_NAME`); transfers over the managed
private network are not available for GovCloud regions.

### A. Prerequisites for Storage Transfer Service (STS)

Before creating a transfer job, complete the following steps:

1.  **Enable the API:**

    ```bash
    gcloud services enable storagetransfer.googleapis.com
    ```

2.  **Grant the STS service agent access to the destination bucket:** The
    service agent
    (`project-PROJECT_NUMBER@storage-transfer-service.iam.gserviceaccount.com`)
    needs `roles/storage.legacyBucketWriter` on the destination bucket. If the
    overwrite option is set to check for "different" or "never", it also needs
    `roles/storage.objectViewer`.

    *   **Grant permission command:**

        ```bash
        gcloud storage buckets add-iam-policy-binding gs://DESTINATION_BUCKET_NAME \
            --member="serviceAccount:project-PROJECT_NUMBER@storage-transfer-service.iam.gserviceaccount.com" \
            --role="roles/storage.legacyBucketWriter"
        ```

### B. Credentials JSON File Setup

To authorize read access to your source without putting secret keys into CLI
command arguments, construct a local JSON credential file.

*   **For Amazon S3 (`s3-creds.json`):**

    ```json
    {
      "accessKeyId": "AWS_ACCESS_KEY_ID",
      "secretAccessKey": "AWS_SECRET_ACCESS_KEY"
    }
    ```

*   **For Azure Blob Storage (`azure-creds.json`):**

    ```json
    {
      "sasToken": "AZURE_SHARE_ACCESS_SIGNATURE_TOKEN"
    }
    ```

### C. STS Commands

#### Create a Transfer Job from Amazon S3:

```bash
gcloud transfer jobs create s3://my-aws-s3-bucket/ gs://my-gcs-destination-bucket/ \
    --source-creds-file=s3-creds.json \
    --description="One-time S3 migration to GCS" \
    --name="s3-to-gcs-migration"
```

#### Create a Transfer Job from Azure Blob Storage:

Specify the Azure Blob Storage container endpoint as the source:

```bash
gcloud transfer jobs create https://myazurestorageaccount.blob.core.windows.net/mycontainer/ gs://my-gcs-destination-bucket/ \
    --source-creds-file=azure-creds.json \
    --description="One-time Azure container migration to GCS" \
    --name="azure-to-gcs-migration"
```

#### Additional STS CLI Operations:

*   **Describe the job status and details:**

    ```bash
    gcloud transfer jobs describe s3-to-gcs-migration
    ```

*   **Run a saved transfer job immediately:**

    ```bash
    gcloud transfer jobs run s3-to-gcs-migration
    ```

*   **Monitor progress of the current transfer run in real time:**

    ```bash
    gcloud transfer jobs monitor s3-to-gcs-migration
    ```

*   **List all existing STS transfer jobs:**

    ```bash
    gcloud transfer jobs list
    ```
gcsfuse.md 21.6 KB
# Cloud Storage FUSE (GCSFuse)

Cloud Storage FUSE (gcsfuse) is an open-source FUSE adapter that mounts Google
Cloud Storage (GCS) buckets as local file systems on Linux; Windows (including
Windows Subsystem for Linux) and macOS are not supported. It allows applications
to read and write objects using standard POSIX file system semantics (`open`,
`read`, `write`, `close`) without modifying application code or adopting Google
Cloud client libraries. It is heavily used in AI/ML training and serving (e.g.,
PyTorch, TensorFlow data loaders), data science notebooks, analytics pipelines,
and legacy applications.

Several behaviors below are version-dependent; check the installed version with
`gcsfuse --version`. This reference is current as of GCSFuse v3.10 (June 2026).

> [!IMPORTANT] **Not a General-Purpose POSIX File System:** Cloud Storage FUSE
> translates file operations into Cloud Storage REST API calls. It is optimized
> for high-throughput sequential reads and writes (such as loading model
> checkpoints or training datasets), but it does not support full POSIX
> compliance. Do not use it as a drop-in replacement for NFS or local block
> storage where random writes or file locking are required. For fully
> POSIX-compliant file system products in Google Cloud, see
> [Filestore](https://cloud.google.com/filestore/docs) or
> [Google Cloud Managed Lustre](https://cloud.google.com/managed-lustre/docs).

> [!TIP] **Advanced Cloud Storage FUSE Work**
>
> For advanced Cloud Storage FUSE work beyond the basic installation and
> mounting in this reference, use the `google-cloud-storage-fuse` skill (see the
> "Routing to Specialized Cloud Storage Skills" section in SKILL.md). If it is
> not installed, give the user this exact command (not the CLI's own plugin or
> extension manager): `npx skills add
> GoogleCloudPlatform/google-cloud-storage-plugin --skill
> google-cloud-storage-fuse`

## Quick Start and Installation

> [!NOTE] You cannot use Google Cloud Shell to mount Cloud Storage buckets with
> Cloud Storage FUSE. Run commands on a local Linux machine, Compute Engine VM,
> or supported container environment.

### Managed Environments (Recommended)

In Google Cloud managed compute platforms, Cloud Storage FUSE is pre-integrated
and managed automatically:

*   **Google Kubernetes Engine (GKE):** Use the official
    [Cloud Storage FUSE CSI driver](https://cloud.google.com/kubernetes-engine/docs/concepts/cloud-storage-fuse-csi-driver)
    to mount buckets into Pods either via static `PersistentVolume` (PV) and
    `PersistentVolumeClaim` (PVC) specifications or directly as CSI ephemeral
    volumes.

    *   **GKE Volume Pod Annotation:** Even when using PV/PVC, the Pod
        annotation `gke-gcsfuse/volumes: "true"` is required.
    *   Example pod configuration annotations (Note that on GKE Standard
        clusters, setting a resource limit annotation automatically sets both
        the request and limit of the sidecar container to that same value):

        ```yaml
        metadata:
          annotations:
            gke-gcsfuse/volumes: "true"
            gke-gcsfuse/cpu-limit: "500m"                 # Optional (sets request & limit)
            gke-gcsfuse/memory-limit: "256Mi"             # Optional (sets request & limit)
            gke-gcsfuse/ephemeral-storage-limit: "10Gi"   # Optional (sets request & limit)
        ```

*   **Vertex AI & Cloud Run:** Direct volume mounting of Cloud Storage buckets
    is natively supported in container configurations.

### Manual Linux Installation (Debian / Ubuntu)

For custom Linux environments, install via the official Google Cloud APT
repository using modern keyring verification:

```bash
# 1. Install prerequisites
sudo apt-get update
sudo apt-get install -y curl lsb-release

# 2. Add the Cloud Storage FUSE distribution URI as a source
export GCSFUSE_REPO=gcsfuse-$(lsb_release -c -s)
echo "deb [signed-by=/usr/share/keyrings/cloud.google.asc] https://packages.cloud.google.com/apt $GCSFUSE_REPO main" | sudo tee /etc/apt/sources.list.d/gcsfuse.list

# 3. Import the Google Cloud public key
curl https://packages.cloud.google.com/apt/doc/apt-key.gpg | sudo tee /usr/share/keyrings/cloud.google.asc

# 4. Update package list and install gcsfuse
sudo apt-get update
sudo apt-get install -y gcsfuse
```

## Authentication

Cloud Storage FUSE uses Application Default Credentials (ADC). Authenticate
before mounting:

```bash
# For interactive development or user sessions:
gcloud auth application-default login
```

On Compute Engine VMs or GKE, ensure the attached IAM service account has the
necessary permissions.

*   `roles/storage.objectUser` (covers create, read, update, delete, and list
    for standard workloads).
*   `roles/storage.objectViewer` is the minimum role required to mount a bucket;
    it allows mounting, listing, and reading file contents, but **NOT**
    creating, updating, or deleting objects.

## Mounting and Unmounting

### Mounting Buckets

Create an empty local directory as a mount point and invoke `gcsfuse`:

```bash
# Create local mount directory
mkdir -p /mnt/gcs/my-bucket

# Mount bucket with implicit directory inference
gcsfuse --implicit-dirs my-bucket /mnt/gcs/my-bucket

# Mount a specific subdirectory prefix only (useful for multi-tenant buckets)
gcsfuse --only-dir=data/training --implicit-dirs my-bucket /mnt/gcs/my-bucket

# Mount read-only for shared static datasets; prevents accidental writes and
# pairs well with aggressive caching (see Caching Configuration)
gcsfuse -o ro --implicit-dirs my-bucket /mnt/gcs/my-bucket
```

### Static Mounting via `/etc/fstab`

To persist mounts across system reboots, add an entry to `/etc/fstab`. Before
using the `allow_other` mount option for non-root users, you must edit
`/etc/fuse.conf` and uncomment or add the `user_allow_other` directive.

```
# <file system>  <mount point>        <type>    <options>                                    <dump>  <pass>
my-bucket        /mnt/gcs/my-bucket   gcsfuse   rw,user,noauto,implicit_dirs,allow_other,uid=1001,gid=1001     0       0
```

> [!NOTE] The `noauto` option prevents boot hangs if network connectivity or ADC
> authentication is not ready during early system startup. If automated
> boot-time mounting is required, replace `noauto` with `_netdev` so the OS
> waits for network initialization before mounting.

> [!IMPORTANT] **Persistent Owner Mapping:** Static mounts executed at boot via
> `/etc/fstab` are run by the system as `root`. To ensure non-root applications
> can access files (even with `allow_other`), you must map ownership by
> including `uid` and `gid` in your fstab options (e.g. `uid=1001,gid=1001`).

### Unmounting

Unmount using standard Linux FUSE unmount utilities:

```bash
# Unmount safely (Linux)
fusermount -u /mnt/gcs/my-bucket

# Alternative root unmount command
sudo umount /mnt/gcs/my-bucket
```

> [!CAUTION] Never run `rm -rf` on an active mount point directory to clean it
> up or unmount it. Doing so will recursively delete all objects in the
> underlying Google Cloud Storage bucket! Always unmount first with `fusermount
> -u`.

## CRUD Operations (Bash & Python Equivalent)

Always use context managers in Python so file handles close deterministically
and uploads finalize on close:

Operation           | Bash Command Example                         | Python Equivalent                                                        | GCS API Mapping
:------------------ | :------------------------------------------- | :----------------------------------------------------------------------- | :--------------
**Create / Upload** | `echo "data" > /mnt/gcs/my-bucket/file.txt`  | `with open('/mnt/gcs/my-bucket/file.txt', 'w') as f: f.write('data\n')`  | Streams bytes directly to Cloud Storage by default in v3.0+; finalizes upload on close.
**Read / Download** | `cat /mnt/gcs/my-bucket/file.txt`            | `with open('/mnt/gcs/my-bucket/file.txt', 'r') as f: data = f.read()`    | Initiates GET object request; streams bytes or fetches from cache.
**Update / Append** | `echo "more" >> /mnt/gcs/my-bucket/file.txt` | `with open('/mnt/gcs/my-bucket/file.txt', 'a') as f: f.write('more\n')`  | Downloads existing object, appends locally (or uses server-side compose without downloading if file >= 2 MB), re-uploads upon close. Rapid Buckets instead append directly with no re-upload.
**Delete**          | `rm /mnt/gcs/my-bucket/file.txt`             | `import os; os.remove('/mnt/gcs/my-bucket/file.txt')`                    | Initiates DELETE object request.
**Create Folder**   | `mkdir -p /mnt/gcs/my-bucket/new-folder`     | `import os; os.makedirs('/mnt/gcs/my-bucket/new-folder', exist_ok=True)` | Creates a 0-byte marker object named `new-folder/` (flat namespace buckets) or calls native folder creation API (HNS buckets).

## POSIX Semantics & Limitations

AI agents and automated workflows must account for these architectural
differences before recommending or interacting with Cloud Storage FUSE:

*   **No POSIX File Locking:** Cloud Storage FUSE does not support advisory or
    mandatory file locking (`flock`, `fcntl`, `lockf`). Applications expecting
    POSIX locks across distributed workers will encounter race conditions.
*   **Streaming Writes & Finalization (`close` vs `fsync`):** By default in
    GCSFuse v3.0+ (`--enable-streaming-writes=true`), sequential writes to new
    files stream directly to GCS. Under streaming writes, calling `fsync()` does
    **not** finalize the object on GCS; data is finalized and made visible only
    when the file handle is closed (`close()`). For out-of-order appends or when
    streaming writes are disabled, GCSFuse reverts to legacy staging (buffering
    locally in `--temp-dir` and uploading/finalizing the full object on
    `fsync()` or `close()`). For high-frequency log streams, use Cloud Storage
    client libraries, Cloud Logging directly, or a
    [Rapid Bucket](high-performance-storage.md), where appended data is visible
    in real time.
*   **No Random Writes or Small Appends:** Because GCS objects are immutable,
    writing to the middle of an existing file or appending to files smaller than
    2 MB causes Cloud Storage FUSE to stage and re-upload the entire modified
    file upon file close (`close()` or `flush()`).
    *   **Exception (Append Optimization):** Appending content to the end of a
        file that is 2 MB or larger is optimized so that only the newly appended
        content is uploaded via object composition. This optimization does
        **not** apply to Rapid Buckets (which do not support compose); staged
        re-uploads there always rewrite the full object.
    *   **Exception (Rapid Buckets):** Objects in
        [Rapid Buckets](high-performance-storage.md) are natively appendable.
        Appends through a file handle opened in append mode (`O_APPEND`) to an
        unfinalized object stream directly to GCS with no staging or re-upload
        (`enable-rapid-appends`, default `true`). Random (out-of-order) writes
        still fall back to staged full re-uploads.
*   **Rename Atomicity & Hierarchical Namespace (HNS):** Renaming an individual
    file is an atomic `objects.move` operation by default (in both flat and HNS
    buckets; controlled by `enable-atomic-rename-object`, on by default).
    Renaming a *directory* in a standard flat-namespace bucket, however,
    requires moving every individual object under that prefix (an $O(N)$
    operation), which is non-atomic and slow for large folders. If your workload
    relies on directory renaming or atomic checkpoint rotation, use a bucket
    with **Hierarchical Namespace (HNS)** enabled. Note that while HNS directory
    renames are atomic metadata-only operations, they are executed as
    asynchronous long-running operations (LROs): the folders being renamed can
    still be read and listed during the rename, but write operations on them are
    blocked until the operation completes.
*   **First-Writer-Wins Concurrency (`ESTALE`):** Cloud Storage objects are
    immutable and replaced atomically. If two independent FUSE mounts open and
    modify the same file simultaneously, **first-writer-wins** semantics apply.
    The first mount to close/sync updates the object generation in GCS; when the
    second mount attempts to close/sync its edits, `gcsfuse` returns a
    `syscall.ESTALE` (Stale File Handle) error due to generation precondition
    mismatch (`if-generation-match`).
*   **Implicit Directories Syntax & HNS Redundancy:** GCS does not have native
    directories. Folders are simulated using object keys with trailing slashes
    (e.g., `logs/`). When accessing buckets populated by external tools (such as
    S3 CLI or older scripts) that did not create explicit 0-byte directory
    marker objects, you must mount with `--implicit-dirs` so GCSFuse can infer
    directories from object prefix paths. Note that `--implicit-dirs` adds
    `List` API overhead and is unnecessary if the target bucket has Hierarchical
    Namespace (HNS) enabled.
*   **Extended Attributes:** Not supported.
*   **chmod/chown:** Run without error but are **silently ignored**. Permissions
    must be set at mount time via `--file-mode`, `--dir-mode`, `--uid`, `--gid`.

### POSIX Operation to GCS Mapping

| POSIX Operation        | GCS Translation          | Performance & Cost       |
:                        :                          : Implications (Flat vs    :
:                        :                          : HNS)                     :
| :--------------------- | :----------------------- | :----------------------- |
| **Read (Sequential)**  | `GetObject` (range read) | Efficient, especially    |
:                        :                          : with caching enabled.    :
| **Write (New File)**   | `WriteObject`            | Default in v3.0+.        |
:                        : (Streaming)              : Uploads directly to GCS  :
:                        :                          : in chunks (uses ~96MB    :
:                        :                          : RAM). Falls back to      :
:                        :                          : local staging if limits  :
:                        :                          : exceeded.                :
| **Modify               | Rewrite / Append         | GCS objects are          |
: (Append/Edit)**        :                          : immutable. Standard      :
:                        :                          : edits trigger a full     :
:                        :                          : rewrite. Appends to      :
:                        :                          : files >= 2MB upload only :
:                        :                          : the appended content.    :
| **Rename File (Flat)** | Atomic Move              | Atomic move by default.  |
:                        : (`objects.move`), with   : Non-atomic copy+delete   :
:                        : copy+delete fallback     : is used only if atomic   :
:                        :                          : rename is disabled.      :
| **Rename File (HNS)**  | Atomic Move              | Atomic metadata-only     |
:                        : (`objects.move`)         : operation. Fast, does    :
:                        :                          : not copy data.           :
| **Rename Directory     | Disabled by default.     | Non-atomic. Renames each |
: (Flat)**               : Enabled via              : descendant individually; :
:                        : `--rename-dir-limit`.    : fails with `EMFILE` if   :
:                        : Batch per-object moves   : the directory has more   :
:                        :                          : descendants than the     :
:                        :                          : limit.                   :
| **Rename Directory     | Atomic Rename            | Atomic metadata-only     |
: (HNS)**                : (`folders.rename`)       : operation. Fast.         :
| **Hard Links**         | Not Supported            | Unsupported operation.   |

## Rapid Bucket Integration

Cloud Storage FUSE supports mounting
[Rapid Buckets](high-performance-storage.md) (zonal, high-performance object
storage designed for AI/ML and analytics workloads). Use version 3.7.2 or later.
Google Kubernetes Engine (GKE) environments require version `1.35.0-gke.3047001`
or later. When mounting a Rapid Bucket, GCSFuse utilizes several performance
optimizations:

*   **Optimized Read Path:** GCSFuse automatically utilizes an optimized read
    path that leverages the Linux kernel's read-ahead algorithm by default,
    enabling faster sequential data access and higher aggregate throughput.
    *   *Note on Caching:* The optimized read path is incompatible with GCSFuse
        file caching and buffered reads. By default, these features are disabled
        for Rapid Buckets. To use them, you must disable the kernel reader by
        setting `enable-kernel-reader: false` (a `file-system` config option not
        listed in the public config-file reference).
    *   *Note on non-GKE hosts:* Outside GKE, the optimized read path also
        requires manual kernel tuning with root access (e.g., increasing
        `read_ahead_kb` and the FUSE `max_background` and `congestion_threshold`
        limits) to reach full throughput.
*   **Native Appends & Real-Time Visibility:** Rapid Bucket objects are
    appendable, and GCSFuse uploads data to them in real time for **new files
    regardless of the mode they were opened in**, and for **existing
    (unfinalized) files when opened in append mode (`O_APPEND`)**. Flushed data
    is readable by other clients in real time — unlike standard buckets, where
    data becomes visible only when the file is closed. By default, closing a
    file does **not** finalize the object (`finalize-file-for-rapid: false`), so
    it remains appendable. Appendable objects accept only one writer at a time;
    a new writer preempts the existing stream.
*   **Streaming Persistence:** Object streams are kept open by default for zonal
    buckets, allowing efficient operations (such as reading a Parquet file's
    metadata and subsequent row data in a single stream) and reducing metadata
    round-trip latency.
    *   *Tip:* To maximize the benefits of streaming persistence, ensure your
        application maintains open file handles and reuses them for subsequent
        operations on the same object.

## Caching Configuration

Caching is essential to reduce latency and API cost (especially metadata
operations). Configure caching using a YAML configuration file or the equivalent
command-line flags — every config-file option has a corresponding flag (e.g.,
`file-cache: max-size-mb` ↔ `--file-cache-max-size-mb`).

### Caching Mechanisms

| Mechanism          | Purpose                         | Recommended For      |
| :----------------- | :------------------------------ | :------------------- |
| **File Cache**     | Caches object content locally   | AI/ML dataset        |
: (`file-cache`)     : on disk (`cache-dir`) to serve  : loading, multi-pass  :
:                    : repeated reads at local         : training epochs, and :
:                    : SSD/NVMe speeds.                : repeated query       :
:                    :                                 : workloads.           :
| **Metadata Cache** | Caches file stat attributes in  | Directory-heavy      |
: (`metadata-cache`) : memory to eliminate             : workloads with       :
:                    : high-latency RPCs during `ls`   : thousands of files.  :
:                    : and `stat` calls (enabled by    :                      :
:                    : default).                       :                      :
| **List Cache**     | Caches directory listing scans  | Workloads performing |
: (`file-system`)    : in kernel memory                : frequent directory   :
:                    : (`kernel-list-cache-ttl-secs`). : traversals.          :

Run GCSFuse with the config file:

```bash
gcsfuse --config-file=/path/to/config.yaml my-bucket /path/to/mount
```

### High-Performance Cache Config (Example)

Use this profile for read-heavy workloads (e.g., ML training) where data is
static during the mount.

```yaml
# Root-level configuration
cache-dir: /mnt/local-ssd/gcsfuse-cache # Point to high-performance media (e.g., Local SSD)
file-cache:
  # Enable local file caching
  max-size-mb: -1 # -1 for unlimited (constrained only by local disk)
  enable-parallel-downloads: true # Enabled by default; accelerates large file reads
  cache-file-for-range-read: true # Caches even if file is read in chunks
metadata-cache:
  # TTL for stat (metadata) cache
  # -1 means infinite TTL (perfect for static/read-only datasets)
  ttl-secs: -1
  stat-cache-max-size-mb: 34 # Default. Type cache merged into stat cache in v3.8.0; type-cache flags are no-ops
file-system:
  # Caches directory listings in the kernel
  kernel-list-cache-ttl-secs: -1
```

> [!WARNING] **Stale Data Risk:** Setting `ttl-secs` or
> `kernel-list-cache-ttl-secs` to `-1` or long durations means GCSFuse will not
> detect changes (metadata or file listings) made to the bucket outside of this
> mount. If the bucket is updated by other clients, users will see stale data or
> missing files.

## Documentation

*   [Cloud Storage FUSE overview](https://cloud.google.com/storage/docs/cloud-storage-fuse/overview)
*   [Install Cloud Storage FUSE](https://cloud.google.com/storage/docs/cloud-storage-fuse/install)
*   [Mount a bucket](https://cloud.google.com/storage/docs/cloud-storage-fuse/mount-bucket)
*   [Configuration file reference](https://cloud.google.com/storage/docs/cloud-storage-fuse/config-file)
*   [Caching](https://cloud.google.com/storage/docs/cloud-storage-fuse/caching)
*   [CSI driver for GKE](https://cloud.google.com/kubernetes-engine/docs/how-to/persistent-volumes/cloud-storage-fuse-csi-driver)
*   [Semantics and limitations](https://github.com/GoogleCloudPlatform/gcsfuse/blob/master/docs/semantics.md)
*   [GitHub Repository](https://github.com/GoogleCloudPlatform/gcsfuse)
high-performance-storage.md 11.2 KB
# High-Performance Cloud Storage (AI/ML, Analytics, and More)

Data-intensive and latency-sensitive workloads such as AI/ML training and
serving, analytics, high-performance computing (HPC), media processing, and
high-rate logging or messaging are often bottlenecked by how fast data reaches
the compute. Cloud Storage offers three features to remove that bottleneck. They
are most associated with AI/ML but help any read-heavy or latency-critical
workload:

-   **Rapid Bucket** and **Rapid Cache** are the two products in the **Cloud
    Storage Rapid** family. Rapid Bucket stores data in a new zonal,
    high-performance bucket, while Rapid Cache accelerates reads from your
    *existing* buckets.
-   **Hierarchical namespace (HNS)** is a bucket mode that adds filesystem-like
    folders and higher request rates. It is required by Rapid Bucket and is also
    useful on its own.

Decision guide: to accelerate reads from data you already store, use **Rapid
Cache** (no migration). For a new, latency-critical workload you can colocate
with accelerators, use a **Rapid Bucket**. To get fast folder operations and
higher QPS on a standard bucket, enable **HNS**.

Rapid Bucket and Rapid Cache are premium, performance-tier features available
only in selected regions and zones. For most workloads, a standard regional or
multi-region bucket is the right default.

## Feature Comparison

| Feature          | What it is        | When to use       | Key benefits      |
| :--------------- | :---------------- | :---------------- | :---------------- |
| **Rapid Bucket** | A zonal bucket    | New,              | Sub-millisecond   |
:                  : using the Rapid   : latency-critical  : latency, up to 15 :
:                  : storage class.    : workloads that    : TB/s aggregate    :
:                  : Data lives in a   : can colocate data : throughput, and   :
:                  : single zone,      : with compute in   : 20 million QPS;   :
:                  : colocated with    : one zone, such as : supports          :
:                  : your compute and  : AI/ML training,   : streaming object  :
:                  : accelerators.     : checkpointing,    : appends.          :
:                  :                   : evaluation, and   :                   :
:                  :                   : serving, plus     :                   :
:                  :                   : HPC, high-rate    :                   :
:                  :                   : logging, and      :                   :
:                  :                   : messaging queues. :                   :
| **Rapid Cache**  | A fully managed,  | Read-heavy        | Up to 2.5 TB/s    |
:                  : SSD-backed zonal  : workloads on      : throughput and    :
:                  : read cache        : existing buckets  : lower read        :
:                  : (formerly         : where data is     : latency;          :
:                  : Anywhere Cache)   : read often but    : autoscales;       :
:                  : that fronts       : changed rarely,   : reduces           :
:                  : existing          : such as AI/ML     : data-transfer,    :
:                  : regional,         : training and data : retrieval, and    :
:                  : dual-region, or   : loading,          : read-operation    :
:                  : multi-region      : checkpoint        : fees versus       :
:                  : buckets with no   : restores,         : reading directly  :
:                  : data migration or : analytics, and    : from the bucket.  :
:                  : code changes.     : repeated content  :                   :
:                  :                   : serving.          :                   :
| **Hierarchical   | A bucket mode,    | Workloads needing | Up to 8x higher   |
: namespace        : set at creation,  : fast folder       : initial QPS;      :
: (HNS)**          : where folders are : operations,       : atomic and fast   :
:                  : real resources    : filesystem        : folder renames;   :
:                  : with              : semantics, or     : efficient         :
:                  : filesystem-like   : higher request    : listing;          :
:                  : semantics.        : rates, such as    : preserves object  :
:                  :                   : analytics, AI/ML  : metadata (and     :
:                  :                   : frameworks like   : lifecycle age)    :
:                  :                   : TensorFlow,       : across renames.   :
:                  :                   : Pandas, and       :                   :
:                  :                   : PyTorch, and any  :                   :
:                  :                   : large dataset     :                   :
:                  :                   : organized into    :                   :
:                  :                   : many folders.     :                   :
:                  :                   : Required to       :                   :
:                  :                   : create a Rapid    :                   :
:                  :                   : Bucket.           :                   :

## Important Constraints

Verify these before recommending a feature. The high-performance options trade
flexibility and redundancy for speed.

-   **Rapid Bucket:**

    -   Requires hierarchical namespace and uniform bucket-level access, and
        gcloud CLI version **553.0.0 or later** (earlier versions are not
        compatible with zonal buckets).
    -   Mounting zonal buckets with Cloud Storage FUSE requires **gcsfuse
        version 3.7.2 or later** — earlier releases (including 3.x versions
        before 3.7.2) cannot mount them. Through the GKE CSI driver, the GKE
        cluster must be `1.35.0-gke.3047001` or later.
    -   Data is stored in a **single zone** with no cross-zone redundancy, so it
        does not have the durability and availability of a regional bucket. For
        data you cannot lose, copy it to a regional bucket (for example,
        replicate checkpoints).
    -   Not compatible with Object Versioning, soft delete, cross-bucket
        replication, resumable uploads, object rewrite or compose,
        customer-supplied encryption keys (CSEK), HMAC keys, BigQuery,
        Autoclass, Bucket Lock, Object Retention Lock, object holds, or
        Requester Pays. In particular, a Rapid Bucket **cannot be fronted by
        Rapid Cache** — the two Cloud Storage Rapid products are alternatives,
        not a stack.

-   **Rapid Cache:**

    -   A read cache, not durable storage. Cached data can be evicted, and it
        does not accelerate writes.
    -   Delete a bucket's caches before deleting the bucket.

-   **Hierarchical namespace:** Set at creation and cannot be changed later, and
    requires uniform bucket-level access. Not compatible with Object Versioning,
    Bucket Lock, Object Retention Lock, object holds, cross-bucket replication,
    or bucket relocation. See [Core Concepts](core-concepts.md). Lifecycle rules
    act on objects only — empty folders persist until deleted explicitly — but
    as of **August 26, 2026**, the lifecycle Delete action also deletes an empty
    folder once it meets all of the rule's conditions, so folder-sweeper
    automation can be retired after that date.

## Enabling Each Feature

Hierarchical namespace and Rapid Bucket are configured at bucket creation and
cannot be turned on later. Both require uniform bucket-level access.

```bash
# Hierarchical namespace bucket (regional, dual-region, or multi-region):
gcloud storage buckets create gs://BUCKET_NAME \
    --location=LOCATION \
    --uniform-bucket-level-access --enable-hierarchical-namespace

# Rapid Bucket (zonal, Rapid storage class; HNS and UBLA are required):
gcloud storage buckets create gs://BUCKET_NAME \
    --location=REGION --placement=ZONE \
    --default-storage-class=RAPID \
    --enable-hierarchical-namespace --uniform-bucket-level-access
```

`ZONE` must be a zone within `REGION` (for example, `--location=us-east1
--placement=us-east1-b`), and the zone must be one where Rapid Bucket is
available, so check the linked docs first.

Rapid Cache is added to an *existing* bucket. Create it through the recommender
workflow below so you only cache where it saves cost.

## Workflow: Recommend and Create Cost-Optimal Rapid Caches

Rather than guess where caching pays off, use the **Rapid Cache recommender**.
It analyzes your bucket's read activity over the past seven days, simulates how
a cache would have performed, and only recommends a cache when it would be
cost-effective: the simulated cache exceeds 100 GiB and meets at least one of a
hit rate above 80%, net savings above $700 per week on multi-region
data-transfer-out fees (based on negotiated price), or peak throughput above 800
Gbps. Following its recommendations is therefore cost-optimal by design.

1.  **Enable the Recommender API:**

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

    Viewing recommendations also requires the Rapid Cache recommender
    permissions (`recommender.storageBucketAnywhereCacheRecommendations.get` and
    `.list`). See
    [Rapid Cache recommender](https://docs.cloud.google.com/storage/docs/rapid/rapid-cache-recommender)
    for the exact roles and permissions.

2.  **List recommendations** (`BUCKET_REGION` is the bucket's region, a single
    region such as `us-central1`):

    ```bash
    gcloud recommender recommendations list \
        --project=PROJECT_ID --location=BUCKET_REGION \
        --recommender=google.storage.bucket.AnywhereCacheRecommender \
        --format=json
    ```

    Each recommendation includes the target bucket, the zone to cache in, a
    suggested TTL, and the projected cost/performance impact. The recommender ID
    and the `recommender.storageBucketAnywhereCache*` permissions retain the
    legacy AnywhereCache name, so use them verbatim.

3.  **Create the recommended cache** in the suggested zone. The product is Rapid
    Cache, but the CLI command path still uses `anywhere-caches`:

    ```bash
    gcloud storage buckets anywhere-caches create gs://BUCKET_NAME CACHE_ZONE \
        --ttl=7d
    ```

    `--ttl` accepts a duration from 1 to 7 days (default 1 day). Add the
    optional `--enable-ingest-on-write` flag to also cache objects when they are
    written, not just on first read.

4.  **Verify the cache** is active:

    ```bash
    gcloud storage buckets anywhere-caches list gs://BUCKET_NAME
    ```

To monitor savings across many buckets continuously, export recommendations to
BigQuery with the BigQuery Data Transfer Service and review them on a schedule.

## Documentation

-   [Cloud Storage Rapid overview](https://docs.cloud.google.com/storage/docs/rapid/high-performance-storage)
-   [Rapid Bucket](https://docs.cloud.google.com/storage/docs/rapid/rapid-bucket)
-   [Rapid Cache](https://docs.cloud.google.com/storage/docs/rapid/rapid-cache)
-   [Rapid Cache recommender](https://docs.cloud.google.com/storage/docs/rapid/rapid-cache-recommender)
-   [Create and use a Rapid Cache](https://docs.cloud.google.com/storage/docs/rapid/use-rapid-cache)
-   [Hierarchical namespace](https://docs.cloud.google.com/storage/docs/hns-overview)
-   [Design storage for AI and ML workloads](https://docs.cloud.google.com/ai-hypercomputer/docs/storage)
iac-usage.md 9.4 KB
# Cloud Storage Infrastructure as Code (Terraform)

Terraform is an open-source Infrastructure as Code (IaC) tool created by
HashiCorp that allows you to define, provision, and manage cloud infrastructure
using a declarative configuration language (HashiCorp Configuration Language, or
HCL).

Instead of manual action via the Google Cloud Console or CLI commands, Terraform
lets you specify the desired state of your Google Cloud Storage (GCS) resources
in code, and automatically handles the API calls required to create, update, or
delete them.

## Advantages of Terraform

-   **Declarative Configuration:** You define the target state of your buckets,
    IAM policies, and lifecycle rules. Terraform determines what changes are
    necessary to achieve that state.
-   **Version Control and Collaboration:** Infrastructure configurations live
    alongside application code in version control systems (like Git), enabling
    peer code reviews, auditability, and rollback capabilities.
-   **Repeatability and Consistency:** You can reliably provision identical
    storage architectures across multiple environments (e.g., development,
    staging, production) without human error.
-   **Automated Drift Detection:** Running `terraform plan` compares your active
    cloud resources against your defined code, immediately highlighting
    unauthorized manual changes ("configuration drift").

> [!WARNING] **State Management & Immutability Limits:** Terraform tracks
> deployed infrastructure via state files (`terraform.tfstate`). In team
> environments, you **must** configure a secure remote state backend (e.g.
> through a GCS bucket) to prevent concurrent execution conflicts and protect
> sensitive metadata. Furthermore, certain core GCS bucket properties — such as
> `name` and `location` — are immutable after creation. Attempting to modify
> these fields in Terraform will force a destructive resource replacement
> (`destroy` followed by `create`), which will fail if the bucket contains
> objects or cause permanent data loss if safeguards like `lifecycle {
> prevent_destroy = true }` are omitted.

## Core Concepts in Terraform

In Terraform, Cloud Storage buckets are managed using the
`google_storage_bucket` resource from the official Google Cloud provider. The
configuration maps directly to GCS core concepts like location types, storage
classes, lifecycle policies, and data protection features.

Google recommends enabling **Uniform Bucket-Level Access**
(`uniform_bucket_level_access = true`) and **Public Access Prevention**
(`public_access_prevention = "enforced"`) on all new buckets to enforce secure,
IAM-only access control.

### Scenario 1: Single-Region Bucket with Standard Storage, Lifecycle Rules, and IP Filtering

This scenario provisions a regional bucket designed for active application data.
It uses the `STANDARD` storage class, implements Object Lifecycle Management
(OLM) to automatically transition older data to archive storage or clean up
expired versions, and restricts access to specific IP ranges using bucket IP
filtering.

```
resource "google_storage_bucket" "app_data" {
  name                        = "my-regional-app-data-bucket"
  location                    = "US-CENTRAL1"
  storage_class               = "STANDARD"
  uniform_bucket_level_access = true
  public_access_prevention    = "enforced"

  # Enable Object Versioning
  versioning {
    enabled = true
  }

  # Prevent accidental deletion of the bucket
  lifecycle {
    prevent_destroy = true
  }

  # Object Lifecycle Management (OLM)
  # Rule 1: Transition objects older than 365 days to ARCHIVE storage
  lifecycle_rule {
    condition {
      age = 365
    }
    action {
      type          = "SetStorageClass"
      storage_class = "ARCHIVE"
    }
  }

  # Rule 2: Delete non-current object versions when there are more than 3 newer versions
  lifecycle_rule {
    condition {
      num_newer_versions = 3
    }
    action {
      type = "Delete"
    }
  }

  # IP Filtering Configuration
  # Restricts bucket access strictly to the specified public IP ranges
  ip_filter {
    mode                           = "Enabled"
    allow_all_service_agent_access = true

    public_network_source {
      # Allow all public IPv4 and IPv6 traffic (effectively blocking private
      # traffic from a VPC network).
      allowed_ip_cidr_ranges = ["0.0.0.0/0", "::/0"]
    }
  }
}
```

### Scenario 2: Dual-Region Bucket with Public Access Prevention and Turbo Replication

This scenario demonstrates a highly available dual-region setup designed for
disaster recovery and continuity. It uses a predefined dual-region (`NAM4`),
enforces public access prevention, and enables Turbo Replication (`ASYNC_TURBO`)
for a backed 15-minute recovery point objective (RPO).

```
resource "google_storage_bucket" "mission_critical_dr" {
  name                        = "my-dual-region-dr-bucket"
  location                    = "NAM4"
  storage_class               = "STANDARD"
  uniform_bucket_level_access = true
  public_access_prevention    = "enforced"

  # Enable Turbo Replication for 15-minute RPO
  rpo = "ASYNC_TURBO"

  # Enable Object Versioning for point-in-time recovery
  versioning {
    enabled = true
  }

  # Retain soft-deleted objects for 14 days (1,209,600 seconds)
  soft_delete_policy {
    retention_duration_seconds = 1209600
  }
}
```

*Note: For predefined dual-regions like `NAM4` or `EUR4`, GCS automatically
manages the underlying region pairing. To create a **custom dual-region** (e.g.,
pairing `US-EAST1` and `US-WEST1`), set `location` to the parent continent
multi-region (e.g., `"US"`) and define the specific region pair inside a
`custom_placement_config` block:*

```
resource "google_storage_bucket" "custom_dual_region" {
  name                        = "my-custom-dual-region-bucket"
  location                    = "US" # Parent continent multi-region
  storage_class               = "STANDARD"
  uniform_bucket_level_access = true
  public_access_prevention    = "enforced"

  custom_placement_config {
    data_locations = ["US-EAST1", "US-WEST1"]
  }
}
```

### Scenario 3: Nearline Storage with Object Retention (WORM) and CMEK Encryption

This scenario provisions a compliance archive bucket designed for long-term,
tamper-proof record keeping (e.g., financial or healthcare audit logs). It uses
the `NEARLINE` storage class, enforces Customer-Managed Encryption Keys (CMEK),
and enables Object Retention to support Write-Once-Read-Many (WORM) compliance.

```
resource "google_storage_bucket" "compliance_vault" {
  name                        = "my-compliance-vault-bucket"
  location                    = "US-EAST1"
  storage_class               = "NEARLINE"
  uniform_bucket_level_access = true
  public_access_prevention    = "enforced"

  # Enable Object Retention Lock capability on the bucket
  enable_object_retention = true

  # Customer-Managed Encryption Key (CMEK) configuration
  # Note: The Cloud Storage service agent must be granted the CryptoKey Encrypter/Decrypter role on this key.
  encryption {
    default_kms_key_name = "projects/my-project/locations/us-east1/keyRings/my-keyring/cryptoKeys/my-key"
  }

  # Ensure audit trails are preserved by preventing accidental destruction
  lifecycle {
    prevent_destroy = true
  }
}
```

*Note: To apply specific retention periods to individual objects within a
retention-enabled bucket, use the `google_storage_bucket_object` resource or
SDKs to set object-level retention rules.*

### Scenario 4: Bucket IAM Policy and Service Account Access

This scenario provisions a bucket and grants an application service account read
and write access to stored objects. In Terraform, bucket IAM permissions can be
managed using `google_storage_bucket_iam_member` (non-authoritative, additive),
`google_storage_bucket_iam_binding` (authoritative for a specific role), or
`google_storage_bucket_iam_policy` (authoritative for all roles on the bucket).

Here, we use `google_storage_bucket_iam_member` to grant the
`roles/storage.objectViewer` role to a service account without overwriting other
existing permissions on the bucket:

```
resource "google_storage_bucket" "secure_assets" {
  name                        = "my-secure-assets-bucket"
  location                    = "US-CENTRAL1"
  storage_class               = "STANDARD"
  uniform_bucket_level_access = true
  public_access_prevention    = "enforced"
}

# Grant Storage Object Viewer permissions to an application service account
resource "google_storage_bucket_iam_member" "sa_object_viewer" {
  bucket = google_storage_bucket.secure_assets.name
  role   = "roles/storage.objectViewer"
  member = "serviceAccount:my-app-sa@my-project.iam.gserviceaccount.com"
}
```

## Documentation and References

-   [Cloud Storage Overview](https://docs.cloud.google.com/storage/docs/introduction)
-   [Terraform Google Provider Documentation: google_storage_bucket](https://registry.terraform.io/providers/hashicorp/google/latest/docs/resources/storage_bucket)
-   [Terraform Google Provider Documentation: google_storage_bucket_object](https://registry.terraform.io/providers/hashicorp/google/latest/docs/resources/storage_bucket_object)
-   [Terraform Google Provider Documentation: google_storage_bucket_iam](https://registry.terraform.io/providers/hashicorp/google/latest/docs/resources/storage_bucket_iam)
-   [Google Cloud Terraform Best Practices](https://docs.cloud.google.com/docs/terraform/best-practices/general-style-structure)
-   [Sample for Creating a Bucket to Store Terraform State](https://docs.cloud.google.com/storage/docs/samples/storage-bucket-tf-with-versioning?hl=en)
mcp-usage.md 13.7 KB
# Cloud Storage MCP Usage

The Cloud Storage Model Context Protocol (MCP) server lets an agent perform
storage operations through structured tool calls instead of shelling out to the
CLI or building HTTP requests. It comes in two forms:

-   **Remote server (managed):** A Google-hosted HTTP endpoint. No installation;
    authenticates with OAuth 2.0 and IAM. Best for inspecting buckets and
    objects, small text reads and writes, and remote management.

-   **Local server (MCP Toolbox):** The open-source
    [MCP Toolbox](https://github.com/googleapis/mcp-toolbox) running its
    prebuilt `cloud-storage` tools on your machine over stdio. Best when you
    need local filesystem integration (upload, download), copy/move operations,
    or larger payloads.

> [!IMPORTANT] **Check what is already connected before setting anything up.**
> Installing this repository as a plugin (rather than as skills alone) already
> configures the local MCP Toolbox server, named `cloud-storage`. If those tools
> are available to you, skip the setup below and just call them. The only
> setting is `CLOUD_STORAGE_PROJECT`, and it is required: if the plugin's
> `cloud-storage` server fails to connect, the project ID is most likely unset.

## Choosing a Server

Your need                                                                                              | Use
:----------------------------------------------------------------------------------------------------- | :--
Zero setup: inspect buckets, read small text/PDF/image objects                                         | Remote server
Small text writes from a managed endpoint                                                              | Remote server
Enterprise guardrails: Model Armor screening of tool calls, IAM deny policies (e.g. enforce read-only) | Remote server
Upload/download local files, binary content, or objects over 8 MiB                                     | Local MCP Toolbox
Copy, move, or rename objects; bucket IAM inspection                                                   | Local MCP Toolbox

When requirements conflict, the hard limits win: the remote server cannot write
binary content, exceed 8 MiB per read or write, or touch the local filesystem —
those workloads need the Toolbox (or the [CLI](cli-api-usage.md)). Model Armor
and IAM deny policies protect only the Google-hosted remote server, so
security-sensitive deployments that fit within its limits should prefer remote.

## Remote Server (Managed)

The remote server runs on Google's infrastructure at a single global endpoint:

-   **Endpoint:** `https://storage.googleapis.com/storage/mcp`
-   **Transport:** HTTP
-   **Auth:** OAuth 2.0 with IAM. API keys are not accepted; every request
    requires IAM authorization. Callers need `roles/mcp.toolUser` plus the
    relevant `roles/storage.*` roles (for example, `roles/storage.objectViewer`
    to read, `roles/storage.objectCreator` to write).

Add it to your MCP client as an HTTP server. Because Google Cloud's remote MCP
servers require IAM authentication, you must configure client-side credentials
or headers (such as an OAuth 2.0 access token). Follow the
[Configure MCP in an AI application](https://docs.cloud.google.com/mcp/configure-mcp-ai-application)
guide for client-specific setup instructions (such as Claude Desktop, Claude
Code, or Gemini CLI).

For example, to manually configure Claude Code using a temporary access token,
place this in your client configuration (e.g. `.mcp.json` or
`~/.claude/mcp_servers.json`):

```json
{
  "mcpServers": {
    "cloud-storage": {
      "type": "http",
      "url": "https://storage.googleapis.com/storage/mcp",
      "headers": {
        "Authorization": "Bearer ACCESS_TOKEN",
        "User-Agent": "gcs-skills/1.0 (skill:google-cloud-storage-basics)"
      }
    }
  }
}
```

Tool calls follow standard JSON-RPC, for example:

```
POST /storage/mcp HTTP/1.1
Host: storage.googleapis.com
Content-Type: application/json
Authorization: Bearer OAUTH2_TOKEN

{
  "jsonrpc": "2.0",
  "method": "tools/call",
  "id": "1",
  "params": {
    "name": "list_buckets",
    "arguments": {"projectId": "my-project"}
  }
}
```

**Limits:** Read and write operations are capped at 8 MiB. Reads are restricted
to text, PDF, and image content; writes are restricted to text. For larger
objects or binary writes, use the local MCP Toolbox, the
[CLI](cli-api-usage.md), or a [client library](client-library-usage.md).

### Defend Against Prompt Injection with Model Armor

Because the remote server is Google-hosted, you can protect it with
[Model Armor](https://docs.cloud.google.com/model-armor/model-armor-mcp-google-cloud-integration),
a service that screens MCP tool calls and responses to mitigate prompt
injection, malicious URLs, and sensitive-data disclosure. This server-side
protection applies only to the remote server, not the local Toolbox. Enable it
once per project with a Model Armor floor setting:

```bash
gcloud model-armor floorsettings update \
  --full-uri='projects/PROJECT_ID/locations/global/floorSetting' \
  --enable-floor-setting-enforcement=TRUE \
  --add-integrated-services=GOOGLE_MCP_SERVER \
  --google-mcp-server-enforcement-type=INSPECT_AND_BLOCK \
  --malicious-uri-filter-settings-enforcement=ENABLED
```

Floor settings apply project-wide and also affect other integrated services
(such as Vertex AI), not just MCP. Enable the prompt injection and jailbreak
filter only if your MCP traffic carries natural-language data.

### Restrict Tool Access with IAM Deny Policies

You can further lock down the remote server with
[IAM deny policies](https://docs.cloud.google.com/mcp/control-mcp-use-iam) that
block unwanted tool calls at the organization, folder, or project level. Deny
rules can match on the principal, the OAuth client ID, or tool properties — for
example, denying any tool that is not read-only (`tool.isReadOnly`) to prevent
an agent from creating, modifying, or deleting data.

## Local Server (MCP Toolbox)

MCP Toolbox is Google's open-source MCP server (formerly Gen AI Toolbox for
Databases). It ships a prebuilt `cloud-storage` tool source that exposes the
full set of bucket and object operations.

If you installed these skills individually (for example via `npx skills add` or
from a skills-only collection), you can either install the full
[Google Cloud Storage plugin](https://github.com/GoogleCloudPlatform/google-cloud-storage-plugin)
(which registers the `cloud-storage` MCP Toolbox server automatically) or add
the server directly to your MCP client using `npx` (Option A) or the standalone
binary (Option B).

1.  **Configure credentials.** The Toolbox uses Application Default Credentials
    (ADC) in every environment: locally via the command below, on GCP compute
    via the attached service account, and elsewhere (CI, on-prem) via workload
    identity federation. **Never download a service-account key file or set
    `GOOGLE_APPLICATION_CREDENTIALS` to one** — key files are a security
    liability and are never needed for the Toolbox.

    ```bash
    gcloud auth application-default login
    ```

2.  **Option A — Add via `npx` (no binary download; requires Node.js).** For
    **Antigravity**, add the server to `~/.gemini/config/mcp_config.json`. For
    **Claude Code**, add it to `.mcp.json` at your project root. Merge the
    `cloud-storage` entry into any existing `mcpServers` object, and replace
    `PROJECT_ID` with your project:

    ```json
    {
      "mcpServers": {
        "cloud-storage": {
          "command": "npx",
          "args": [
            "-y",
            "@toolbox-sdk/server@1.13.1",
            "--prebuilt",
            "cloud-storage",
            "--stdio",
            "--user-agent-metadata",
            "gcs-skills/1.0 (skill:gcs-skills-mcp-traffic)"
          ],
          "env": {"CLOUD_STORAGE_PROJECT": "PROJECT_ID"}
        }
      }
    }
    ```

    For **Codex**, add the equivalent server to `~/.codex/config.toml` (or a
    trusted project's `.codex/config.toml`):

    ```toml
    [mcp_servers.cloud-storage]
    command = "npx"
    args = [
      "-y",
      "@toolbox-sdk/server@1.13.1",
      "--prebuilt",
      "cloud-storage",
      "--stdio",
      "--user-agent-metadata",
      "gcs-skills/1.0 (skill:gcs-skills-mcp-traffic)",
    ]

    [mcp_servers.cloud-storage.env]
    CLOUD_STORAGE_PROJECT = "PROJECT_ID"
    ```

3.  **Option B — Add via standalone binary (no Node.js dependency).** Download
    the standalone binary (or container image), replacing `VERSION` with the
    [latest release](https://github.com/googleapis/mcp-toolbox/releases) and
    picking your OS/architecture path:

    ```bash
    curl -L -o toolbox \
      https://storage.googleapis.com/mcp-toolbox-for-databases/VERSION/linux/amd64/toolbox
    chmod +x toolbox
    ```

    Then point `command` at the downloaded binary:

    ```json
    {
      "mcpServers": {
        "cloud-storage": {
          "command": "./PATH/TO/toolbox",
          "args": [
            "--prebuilt",
            "cloud-storage",
            "--stdio",
            "--user-agent-metadata",
            "gcs-skills/1.0 (skill:gcs-skills-mcp-traffic)"
          ],
          "env": {"CLOUD_STORAGE_PROJECT": "PROJECT_ID"}
        }
      }
    }
    ```

    Always include `"--user-agent-metadata", "gcs-skills/1.0
    (skill:gcs-skills-mcp-traffic)"` in `args` as shown so local MCP Toolbox
    requests carry the required attribution header.

`CLOUD_STORAGE_PROJECT` is required for both options. If it is unset or empty,
the Toolbox exits at startup with `Field validation for 'Project' failed on the
'required' tag`, which MCP clients typically surface only as a generic
connection failure (for example, `Connection closed`). The Toolbox does not fall
back to `GOOGLE_CLOUD_PROJECT` or the gcloud default project. With the plugin,
set the **Project ID** option in Claude Code, Gemini CLI, or Antigravity; in
Codex, `export CLOUD_STORAGE_PROJECT=PROJECT_ID` in the shell before launching
Codex. Then reconnect the server.

The identity behind ADC needs the `roles/storage.*` roles for the operations you
intend to call (for example, `roles/storage.objectAdmin` for copy, move, and
delete; `roles/storage.admin` to create or delete buckets).

## Available Tools

The two servers expose **different** tool sets. Tool names do not always match
across them: the remote server has `write_text` (which the Toolbox does not),
and the Toolbox has `write_object`, `download_object`, `upload_object`, and the
copy/move tools (which the remote server does not). Call only the tools that
exist on the server you are connected to.

**Remote server (9 tools):**

Tool                  | Description
:-------------------- | :----------
`list_buckets`        | List buckets in a project.
`list_objects`        | List objects in a bucket.
`get_bucket_metadata` | Get a bucket's metadata.
`get_object_metadata` | Get an object's metadata.
`read_object`         | Read object content, including images and PDFs (up to 8 MiB).
`create_bucket`       | Create a bucket.
`delete_bucket`       | Delete a bucket.
`write_text`          | Write text to an object (overwrites existing content).
`delete_object`       | Delete an object.

**Local MCP Toolbox (14 tools):**

| Tool                    | Description                                      |
| :---------------------- | :----------------------------------------------- |
| `list_buckets`          | List buckets in a project.                       |
| `list_objects`          | List objects in a bucket.                        |
| `get_bucket_metadata`   | Get a bucket's metadata.                         |
| `get_bucket_iam_policy` | Get a bucket's IAM policy.                       |
| `get_object_metadata`   | Get an object's metadata.                        |
| `read_object`           | Read UTF-8 text content (up to 8 MiB); binary is |
:                         : rejected — use `download_object`.                :
| `download_object`       | Download an object (including binary) to a local |
:                         : file.                                            :
| `create_bucket`         | Create a bucket.                                 |
| `delete_bucket`         | Delete a bucket.                                 |
| `write_object`          | Write text content to an object (overwrites).    |
| `upload_object`         | Upload a local file (including binary) to an     |
:                         : object.                                          :
| `copy_object`           | Copy an object.                                  |
| `move_object`           | Move (rename) an object; deletes the source.     |
| `delete_object`         | Delete an object.                                |

On the Toolbox, `read_object`/`write_object` handle UTF-8 text only and are
capped at 8 MiB; use `download_object`/`upload_object` for binary or large
files.

> [!CAUTION]
>
> **CRITICAL: You MUST stop and ask the user for explicit permission before
> calling any tool that deletes a bucket or object (`delete_bucket`,
> `delete_object`, `move_object` — which deletes the source) or overwrites
> existing content (`write_text`, `write_object`, `upload_object`).**

## Documentation

-   [Use the Cloud Storage MCP server](https://docs.cloud.google.com/storage/docs/use-cloud-storage-mcp)
-   [Cloud Storage MCP reference (tools)](https://docs.cloud.google.com/storage/docs/reference/mcp)
-   [Connect LLMs to Cloud Storage with MCP Toolbox](https://docs.cloud.google.com/storage/docs/pre-built-tools-with-mcp-toolbox)
-   [Google Cloud MCP servers overview](https://docs.cloud.google.com/mcp/overview)
-   [Configure MCP in an AI application](https://docs.cloud.google.com/mcp/configure-mcp-ai-application)
-   [Protect MCP servers with Model Armor](https://docs.cloud.google.com/model-armor/model-armor-mcp-google-cloud-integration)
-   [Control MCP use with IAM deny policies](https://docs.cloud.google.com/mcp/control-mcp-use-iam)
storage-intelligence.md 15.3 KB
# Storage Intelligence

Storage Intelligence is a subscription for analyzing and acting on Cloud Storage
data at scale.

-   **Analysis features:** Storage Insights datasets, data insights with Gemini
    Cloud Assist, inventory reports.
-   **Action features:** storage batch operations, bucket relocation.

Use it for organization-wide visibility (cost, security, governance) and for
operations too large to script (billions of objects, whole-bucket moves).

> [!NOTE]
>
> Datasets, batch operations, and bucket relocation **require** the
> subscription. Inventory reports work without it (the subscription covers their
> scan fees). Gemini Cloud Assist answers general GCS questions without it, but
> prompts about *your* buckets need a subscription plus a dataset.

## Choosing the Right Feature

| Goal                                 | Use                              |
| ------------------------------------ | -------------------------------- |
| Org/folder/project-wide metadata &   | Storage Insights datasets        |
: activity analysis, trends, security  :                                  :
: posture                              :                                  :
| Natural-language questions about     | Gemini Cloud Assist (backed by a |
: bucket/object metadata               : dataset)                         :
| Scheduled per-bucket object listing, | Inventory reports                |
: transfer validation                  :                                  :
| Bulk delete / metadata / holds /     | Batch operations (often fed by a |
: CMEK rotation on many objects        : dataset-generated manifest)      :
| Move a bucket to another location,   | Bucket relocation                |
: keeping its name                     :                                  :
| One-off small-scale changes          | Plain `gcloud storage` (no       |
:                                      : subscription needed)             :

--------------------------------------------------------------------------------

## 1. Configuration

Configure on a **project, folder, or organization**. Children inherit the
configuration, and you can override it at lower levels. Each resource has one
edition configuration: `INHERIT` (default when unset), `STANDARD` (all features,
set by `enable`), `DISABLED`, or `TRIAL`. Bucket filters scope by location or
name regex. Requires `roles/storage.admin`
(`storage.intelligenceConfigs.update`). See
[Configure and manage Storage Intelligence](https://cloud.google.com/storage/docs/storage-intelligence/configure-and-manage-storage-intelligence).

```bash
# Exactly one of --project, --sub-folder, --organization:
gcloud storage intelligence-configs enable --project=my-project

# Org-wide with filters:
gcloud storage intelligence-configs enable --organization=123456789 \
    --exclude-bucket-id-regexes="colddata.*" --include-locations=us-east1

gcloud storage intelligence-configs describe --project=my-project
gcloud storage intelligence-configs disable  --project=my-project

# update takes exactly one settings flag:
gcloud storage intelligence-configs update --project=my-project \
    --include-locations=us-east1
```

**30-day trial:** enables all `STANDARD` features and waives the object
management fee (other charges, e.g. BigQuery, still apply). Eligible **once**
per org/folder/project. **Auto-converts to paid `STANDARD` after 30 days**, so
disable within the window to avoid charges. Datasets created during the trial
persist (and keep billing BigQuery storage) until deleted.

--------------------------------------------------------------------------------

## 2. Storage Insights Datasets

A queryable index of **metadata and activity** for buckets/objects in scope,
delivered as a **BigQuery linked dataset**: metadata snapshots (projects,
buckets, objects), activity views (mutations, errors, bucket/project/regional
activity), and processing events/errors. See
[Configure datasets](https://cloud.google.com/storage/docs/insights/configure-datasets).

Key properties and limits:

-   **Scope:** one org, or up to 10,000 projects/folders, with bucket name-regex
    and location filters. `--auto-add-new-buckets` covers future buckets.
-   **Retention:** a rolling window of up to **90 days** for metadata. Activity
    data can be set separately, up to **365 days** (`0` excludes it).
-   **Locations:** BigQuery locations `EU`, `US`, `asia-south1`, `asia-south2`,
    `asia-southeast1`, `europe-west1`, `us-central1`, `us-east1`, `us-east4`
    only.
-   **Freshness:** the initial load takes 24–48h, activity data lands in ~4h,
    and metadata snapshots refresh every 24h.

```bash
gcloud storage insights dataset-configs create my_dataset \
    --location=us-central1 --organization=123456789 \
    --retention-period-days=30 --source-projects=987654321,123123123

# Must link to BigQuery before querying:
gcloud storage insights dataset-configs create-link my_dataset --location=us-central1
```

After creation, grant the Storage Insights service agent
(`service-PROJECT_NUMBER@gcp-sa-storageinsights.iam.gserviceaccount.com`) the
required permissions. Without them, no data flows. Service agents can be
per-config (default) or per-project (`--identity=IDENTITY_TYPE_PER_PROJECT`).

Use cases:

-   **Estate analysis:** find duplicates, temp data, and data in unexpected
    regions, or extract prefix lists to feed batch operations.
-   **Activity:** identify inactive buckets and map the hottest
    projects/prefixes. The regional activity view (request/response bytes per
    region) informs bucket relocation decisions.
-   **Security:** object `securityInsights` computes **public access status**
    (evaluates PAP, UBLA, ACLs, IAM, org policies, and shows where the grant
    originates). Audit encryption (`encryptionType`) and retention
    (`retentionExpirationTime`, `softDeletePolicy`).
-   **Troubleshooting:** `object_events_view` records errored operations with
    reasons (e.g., find buckets with high 429 rates).
-   **Content analysis:** join metadata to object data via BigQuery `ObjectRef`
    functions (`ref` column).

**Dashboards:** connect the linked dataset to Looker Studio, or start from the
[dashboard template](https://lookerstudio.google.com/reporting/670eee3f-ad6d-45ea-a169-853ab023dc84).
Dashboard queries consume BigQuery compute, so evaluate on a small dataset
first.

Limitations: public access status skips objects in managed folders and ignores
VPC-SC and IP filtering. CRC32C/MD5 checksums are missing for CMEK objects, and
renaming an HNS folder makes its objects reappear as new entries.

--------------------------------------------------------------------------------

## 3. Data Insights with Gemini Cloud Assist (Preview)

With a linked dataset, the Cloud Assist panel on the console's Storage Insights
page answers natural-language prompts about your metadata and returns the
underlying SQL. Examples: "5 largest buckets without Autoclass enabled",
"objects with a retention expiration date within the next 30 days", "buckets
with a high volume of small files". Including "Cloud Storage" in the prompt
improves quality.

Setup: enable Gemini Cloud Assist and Storage Intelligence, create and link a
dataset, grant the service agent `roles/bigquery.dataViewer`, and give users
`roles/bigquery.jobUser`, `roles/bigquery.dataViewer`,
`roles/storageinsights.viewer`.

Quotas and limits:

-   Prompts needing **≥ 800 GB** of processing return SQL only, for you to run
    yourself. Processing is capped at **50 TiB/month/org**.
-   Returns at most the **top 5** matching resources per prompt.
-   Reads only the **latest snapshot**, so no time-series ("how much did my
    bucket grow"). Cost data, activity data ("last access time"), and some
    configs (e.g., soft delete) aren't in the dataset at all.
-   Still in Preview, so validate responses before acting.

--------------------------------------------------------------------------------

## 4. Inventory Reports

Scheduled per-bucket object listings (CSV or Apache Parquet) written to a
destination bucket, as a faster alternative to paginated `Objects: list`. The
report config lives on the source bucket (max 100 per bucket) and defines the
frequency (daily/weekly), the metadata fields (always `project`, `bucket`, and
`name`, plus optional fields like `size`, `timeCreated`, `updated`,
`storageClass`, `etag`, checksums, `generation`, `contentType`, and
`retentionExpirationTime`), and the destination bucket (same project and
location as the source, or the source bucket itself). Reports over 1M objects
are sharded, with a `*_manifest.json` written when all shards are complete.

**Use for:** quick single-bucket analysis, transfer validation, per-bucket
audits. **Use datasets instead for:** multi-bucket/org-wide analysis, trends,
activity data.

> [!NOTE]
>
> Delivery is best-effort, so reports may skip days or miss objects. For
> complete daily coverage, use datasets instead. Not compatible with bucket IP
> filtering, and unavailable in a few locations (e.g., `me-central1`,
> `me-central2`, dual-regions `eur5`/`eur7`/`eur8`).

--------------------------------------------------------------------------------

## 5. Storage Batch Operations

Serverless jobs that run **one transformation** across objects in **one
bucket**, scaling to ~1B objects in ~3 hours with concurrent jobs. Jobs are LROs
with progress tracking and automatic retries.

Job types:

-   **delete**
-   **metadata update**: custom metadata, or fixed fields like `Content-Type`,
    `Cache-Control`, `Custom-Time`, and retention config
-   **object hold** set/release
-   **object rewrite**: CMEK key or storage class
-   **object context updates**

Objects are selected either by a **manifest** (a CSV in GCS with the header
`bucket,name,generation`, where generation is optional and rows for other
buckets are ignored) or by up to 1,000 **object prefixes** (an empty list means
the whole bucket). A common pattern is to query a dataset to generate the
manifest.

```bash
# Bulk metadata update from a manifest:
gcloud storage batch-operations jobs create my-job \
    --bucket=my-bucket \
    --manifest-location=gs://my-bucket/manifest.csv \
    --put-metadata=Content-Language=en

# Always dry-run large deletes first (counts affected objects, no changes):
gcloud storage batch-operations jobs create my-dry-run \
    --bucket=my-bucket --included-object-prefixes=tmp/,staging/ \
    --delete-object --dry-run

gcloud storage batch-operations jobs describe my-job   # also: cancel, delete
```

> [!CAUTION]
>
> Batch deletes are recoverable only via soft delete (7-day default). If soft
> delete is disabled on the bucket, deleted objects are unrecoverable.

Limits: jobs auto-cancel after **14 days**, at most 1,000 prefixes per job, at
most ~20 concurrent jobs per bucket recommended, and **Requester Pays buckets
are unsupported**. Pricing adds no fee beyond the subscription, but normal
per-operation charges apply: transformations are Class A (skipped if the object
is already in the desired state), deletes are free, and listing during jobs and
dry runs is Class A.

--------------------------------------------------------------------------------

## 6. Bucket Relocation

Moves a bucket to a different location **without renaming it or manual data
copying**, preserving object metadata and storage classes, including Autoclass
(legacy classes convert to Standard). Reads stay available throughout. Typical
drivers: cut inter-region transfer costs, colocate with compute, or move from a
region to a dual/multi-region for resilience (use the dataset regional activity
view to find candidates).

Two types, determined by source/destination locations:

-   **With write downtime** (most moves: region↔region, region↔dual-region,
    across multi-region codes): writes are blocked only during the final
    synchronization step, which **you** initiate.
-   **Without write downtime** (locations sharing a multi-region code, e.g.
    configurable dual-region ↔ multi-region): no finalize step, but takes a
    **minimum of 7 days** regardless of size, and latency may increase.

```bash
# 1. Dry run first to catch incompatibilities early:
gcloud storage buckets relocate gs://my-bucket --location=us-central1 --dry-run

# 2. Initiate. Bucket metadata is write-locked, object reads/writes continue:
gcloud storage buckets relocate gs://my-bucket --location=us-central1

# 3. Finalize (write-downtime moves only). Object writes fail with HTTP 412
#    until complete, then the lock lifts automatically:
gcloud storage buckets relocate --finalize \
    --operation=projects/_/buckets/my-bucket/operations/OPERATION_ID
```

Copy duration scales with object count, churn, and size (objects over 10 GB move
slowly, at roughly a day per TB-sized object). Check the compatibility list
before starting: Firebase and appspot buckets can't be relocated at all,
multipart uploads and retention policies have restrictions, and with-downtime
moves support fewer features. `ME-CENTRAL1` and `ME-WEST1` aren't supported.

--------------------------------------------------------------------------------

## 7. Pricing

-   **Subscription:** $2.50 per million objects/month, amortized daily, billed
    to the bucket's project, only for objects older than 24h. Early termination
    fee if a bucket leaves `STANDARD` tier within 30 days (deletions exempt).
-   **Datasets:** no extra SI fee (multiple configs over the same buckets pay
    once), but BigQuery storage and query charges apply (~300 MB metadata per TB
    of data daily). Disabling SI stops snapshots but does **not** delete
    BigQuery data, so delete dataset configs to stop charges.
-   **Batch operations:** standard Class A/B operation charges per object
    (deletes free).
-   **Bucket relocation:** **$0.04/GB** moved, plus inter-region transfer, one
    Class A op per object, and storage billed in **both** locations during the
    move. There are no retrieval or early-deletion fees, and transfer is waived
    if source and destination overlap in a region.
-   **Trial:** waives the object management fee and the early termination fee.

Details: https://cloud.google.com/storage/pricing#storage-intelligence

--------------------------------------------------------------------------------

## Documentation

-   [Storage Intelligence Overview](https://cloud.google.com/storage/docs/storage-intelligence/overview)
-   [Configure and Manage Storage Intelligence](https://cloud.google.com/storage/docs/storage-intelligence/configure-and-manage-storage-intelligence)
-   [30-Day Introductory Trial](https://cloud.google.com/storage/docs/storage-intelligence/30-day-introductory-trial/overview)
-   [Storage Insights Datasets](https://cloud.google.com/storage/docs/insights/datasets)
    /
    [Configure Datasets](https://cloud.google.com/storage/docs/insights/configure-datasets)
    /
    [Tables and Schemas](https://cloud.google.com/storage/docs/insights/dataset-tables-and-schemas)
-   [Analyze Data with Gemini Cloud Assist](https://cloud.google.com/storage/docs/analyze-data-gemini-cloud-assist)
-   [Inventory Reports](https://cloud.google.com/storage/docs/insights/inventory-reports)
-   [Batch Operations](https://cloud.google.com/storage/docs/batch-operations/overview)
    /
    [Create and Manage Jobs](https://cloud.google.com/storage/docs/batch-operations/create-manage-batch-operation-jobs)
-   [Bucket Relocation](https://cloud.google.com/storage/docs/bucket-relocation/overview)
    /
    [Plan a Relocation](https://cloud.google.com/storage/docs/bucket-relocation/plan-bucket-relocation)

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