管理对象生命周期

转到概念

本页面介绍了如何启用对象生命周期管理并提供了生命周期配置的示例。生命周期配置是在存储分区级层进行管理的,并适用于存储分区中的所有当前和未来的对象。

在存储分区上设置生命周期管理

启用生命周期管理

如需为存储分区启用生命周期管理,请执行以下操作

控制台

  1. 在 Google Cloud Console 中,转到 Cloud Storage 浏览器页面。

    转到浏览器

  2. 在存储分区列表中,找到要启用的存储分区,然后点击存储分区的名称。

  3. 点击生命周期标签页。

    随即将显示生命周期规则页面。

  4. 点击添加规则

  5. 在出现的页面中,指定配置。

    1. 选择对象满足条件时要执行的操作

    2. 点击继续

    3. 选择执行操作的条件

    4. 点击继续

    5. 点击创建

如需了解如何获取有关 Cloud Storage 浏览器中失败操作的详细错误信息,请参阅问题排查

gsutil

  1. 使用您要应用的生命周期配置规则创建一个 .json 文件。如需查看示例 .json 文件,请参阅配置示例

  2. 使用 lifecycle set 命令应用配置:

    gsutil lifecycle set LIFECYCLE_CONFIG_FILE gs://BUCKET_NAME

    其中:

    • LIFECYCLE_CONFIG_FILE 是您在第 1 步中创建的文件的名称。
    • BUCKET_NAME 是相关存储分区的名称,例如 my-bucket

代码示例

C++

如需了解详情,请参阅 Cloud Storage C++ API 参考文档

namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name) {
  gcs::BucketLifecycle bucket_lifecycle_rules = gcs::BucketLifecycle{
      {gcs::LifecycleRule(gcs::LifecycleRule::ConditionConjunction(
                              gcs::LifecycleRule::MaxAge(30),
                              gcs::LifecycleRule::IsLive(true)),
                          gcs::LifecycleRule::Delete())}};

  StatusOr<gcs::BucketMetadata> updated_metadata = client.PatchBucket(
      bucket_name,
      gcs::BucketMetadataPatchBuilder().SetLifecycle(bucket_lifecycle_rules));

  if (!updated_metadata) {
    throw std::runtime_error(updated_metadata.status().message());
  }

  if (!updated_metadata->has_lifecycle() ||
      updated_metadata->lifecycle().rule.empty()) {
    std::cout << "Bucket lifecycle management is not enabled for bucket "
              << updated_metadata->name() << ".\n";
    return;
  }
  std::cout << "Successfully enabled bucket lifecycle management for bucket "
            << updated_metadata->name() << ".\n";
  std::cout << "The bucket lifecycle rules are";
  for (auto const& kv : updated_metadata->lifecycle().rule) {
    std::cout << "\n " << kv.condition() << ", " << kv.action();
  }
  std::cout << "\n";
}

C#

如需了解详情,请参阅 Cloud Storage C# API 参考文档


using Google.Apis.Storage.v1.Data;
using Google.Cloud.Storage.V1;
using System;
using System.Collections.Generic;

public class EnableBucketLifecycleManagementSample
{
    public Bucket EnableBucketLifecycleManagement(string bucketName = "your-unique-bucket-name")
    {
        var storage = StorageClient.Create();
        var bucket = storage.GetBucket(bucketName);
        bucket.Lifecycle = new Bucket.LifecycleData
        {
            Rule = new List<Bucket.LifecycleData.RuleData>
            {
                new Bucket.LifecycleData.RuleData
                {
                    Condition = new Bucket.LifecycleData.RuleData.ConditionData { Age = 100 },
                    Action = new Bucket.LifecycleData.RuleData.ActionData { Type = "Delete" }
                }
            }
        };
        bucket = storage.UpdateBucket(bucket);

        Console.WriteLine($"Lifecycle management is enabled for bucket {bucketName} and the rules are:");
        foreach (var rule in bucket.Lifecycle.Rule)
        {
            Console.WriteLine("Action:");
            Console.WriteLine($"Type: {rule.Action.Type}");
            Console.WriteLine($"Storage Class: {rule.Action.StorageClass}");

            Console.WriteLine("Condition:");
            Console.WriteLine($"Age: \t{rule.Condition.Age}");
            Console.WriteLine($"Created Before: \t{rule.Condition.CreatedBefore}");
            Console.WriteLine($"Time Before: \t{rule.Condition.CustomTimeBefore}");
            Console.WriteLine($"Days Since Custom Time: \t{rule.Condition.DaysSinceCustomTime}");
            Console.WriteLine($"Days Since Non-current Time: \t{rule.Condition.DaysSinceNoncurrentTime}");
            Console.WriteLine($"IsLive: \t{rule.Condition.IsLive}");
            Console.WriteLine($"Pattern: \t{rule.Condition.MatchesPattern}");
            Console.WriteLine($"Storage Class: \t{rule.Condition.MatchesStorageClass}");
            Console.WriteLine($"Noncurrent Time Before: \t{rule.Condition.NoncurrentTimeBefore}");
            Console.WriteLine($"Newer Versions: \t{rule.Condition.NumNewerVersions}");
        }
        return bucket;
    }
}

Go

如需了解详情,请参阅 Cloud Storage Go API 参考文档

import (
	"context"
	"fmt"
	"io"
	"time"

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

// enableBucketLifecycleManagement adds a lifecycle delete rule with the
// condition that the object is 100 days old.
func enableBucketLifecycleManagement(w io.Writer, bucketName string) error {
	// bucketName := "bucket-name"
	ctx := context.Background()
	client, err := storage.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("storage.NewClient: %v", err)
	}
	defer client.Close()

	ctx, cancel := context.WithTimeout(ctx, time.Second*10)
	defer cancel()

	bucket := client.Bucket(bucketName)
	bucketAttrsToUpdate := storage.BucketAttrsToUpdate{
		Lifecycle: &storage.Lifecycle{
			Rules: []storage.LifecycleRule{
				{
					Action: storage.LifecycleAction{Type: "Delete"},
					Condition: storage.LifecycleCondition{
						AgeInDays: 100,
					},
				},
			},
		},
	}

	attrs, err := bucket.Update(ctx, bucketAttrsToUpdate)
	if err != nil {
		return fmt.Errorf("Bucket(%q).Update: %v", bucketName, err)
	}
	fmt.Fprintf(w, "Lifecycle management is enabled for bucket %v\n and the rules are:\n", bucketName)
	for _, rule := range attrs.Lifecycle.Rules {
		fmt.Fprintf(w, "Action: %v\n", rule.Action)
		fmt.Fprintf(w, "Condition: %v\n", rule.Condition)
	}

	return nil
}

Java

如需了解详情,请参阅 Cloud Storage Java API 参考文档

import com.google.cloud.storage.Bucket;
import com.google.cloud.storage.BucketInfo.LifecycleRule;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;
import com.google.common.collect.ImmutableList;

public class EnableLifecycleManagement {
  public static void enableLifecycleManagement(String projectId, String bucketName) {
    // The ID of your GCP project
    // String projectId = "your-project-id";

    // The ID of your GCS bucket
    // String bucketName = "your-unique-bucket-name";

    Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();
    Bucket bucket = storage.get(bucketName);

    // See the LifecycleRule documentation for additional info on what you can do with lifecycle
    // management rules. This one deletes objects that are over 100 days old.
    // https://googleapis.dev/java/google-cloud-clients/latest/com/google/cloud/storage/BucketInfo.LifecycleRule.html
    bucket
        .toBuilder()
        .setLifecycleRules(
            ImmutableList.of(
                new LifecycleRule(
                    LifecycleRule.LifecycleAction.newDeleteAction(),
                    LifecycleRule.LifecycleCondition.newBuilder().setAge(100).build())))
        .build()
        .update();

    System.out.println("Lifecycle management was enabled and configured for bucket " + bucketName);
  }
}

Node.js

如需了解详情,请参阅 Cloud Storage Node.js API 参考文档

/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// The ID of your GCS bucket
// const bucketName = 'your-unique-bucket-name';

// Imports the Google Cloud client library
const {Storage} = require('@google-cloud/storage');

// Creates a client
const storage = new Storage();

async function enableBucketLifecycleManagement() {
  const [metadata] = await storage.bucket(bucketName).addLifecycleRule({
    action: 'delete',
    condition: {age: 100},
  });

  console.log(
    `Lifecycle management is enabled for bucket ${bucketName} and the rules are:`
  );

  console.log(metadata.lifecycle.rule);
}

enableBucketLifecycleManagement().catch(console.error);

PHP

如需了解详情,请参阅 Cloud Storage PHP API 参考文档

use Google\Cloud\Storage\StorageClient;
use Google\Cloud\Storage\Bucket;

/**
 * Enable bucket lifecycle management.
 *
 * @param string $bucketName The name of your Cloud Storage bucket.
 */
function enable_bucket_lifecycle_management($bucketName)
{
    // $bucketName = 'my-bucket';

    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);

    $lifecycle = Bucket::lifecycle()
        ->addDeleteRule([
            'age' => 100
        ]);

    $bucket->update([
        'lifecycle' => $lifecycle
    ]);

    $lifecycle = $bucket->currentLifecycle();

    printf('Lifecycle management is enabled for bucket %s and the rules are:' . PHP_EOL, $bucketName);
    foreach ($lifecycle as $rule) {
        print_r($rule);
        print(PHP_EOL);
    }
}

Python

如需了解详情,请参阅 Cloud Storage Python API 参考文档

from google.cloud import storage

def enable_bucket_lifecycle_management(bucket_name):
    """Enable lifecycle management for a bucket"""
    # bucket_name = "my-bucket"

    storage_client = storage.Client()

    bucket = storage_client.get_bucket(bucket_name)
    rules = bucket.lifecycle_rules

    print("Lifecycle management rules for bucket {} are {}".format(bucket_name, list(rules)))
    bucket.add_lifecycle_delete_rule(age=2)
    bucket.patch()

    rules = bucket.lifecycle_rules
    print("Lifecycle management is enable for bucket {} and the rules are {}".format(bucket_name, list(rules)))

    return bucket

Ruby

如需了解详情,请参阅 Cloud Storage Ruby API 参考文档

def enable_bucket_lifecycle_management bucket_name:
  # Enable lifecycle management for a bucket
  # The ID of your GCS bucket
  # bucket_name = "your-unique-bucket-name"

  require "google/cloud/storage"

  storage = Google::Cloud::Storage.new
  bucket = storage.bucket bucket_name

  rules = bucket.lifecycle do |l|
    l.add_delete_rule age: 2
  end

  puts "Lifecycle management is enabled for bucket #{bucket_name} and the rules are #{rules}"
end

REST API

JSON API

  1. OAuth 2.0 Playground 获取授权访问令牌。将 Playground 配置为使用您自己的 OAuth 凭据。
  2. 使用您要应用的生命周期配置规则创建一个 .json 文件。如需查看示例 .json 文件,请参阅配置示例

  3. 使用 cURL,通过 PATCH Bucket 请求调用 JSON API

    curl -X PATCH --data-binary @LIFECYCLE_CONFIG_FILE.json \
      -H "Authorization: Bearer OAUTH2_TOKEN" \
      -H "Content-Type: application/json" \
      "https://storage.googleapis.com/storage/v1/b/BUCKET_NAME?fields=lifecycle"

    其中:

    • LIFECYCLE_CONFIG_FILE 是您在第 2 步中创建的文件的名称。
    • OAUTH2_TOKEN 是您在第 1 步中生成的访问令牌。
    • BUCKET_NAME 是相关存储分区的名称,例如 my-bucket

XML API

  1. OAuth 2.0 Playground 获取授权访问令牌。将 Playground 配置为使用您自己的 OAuth 凭据。
  2. 使用您要应用的生命周期配置规则创建一个 .xml 文件。如需查看示例 .xml 文件,请参阅配置示例

  3. 使用 cURL,通过 PUT Bucket 请求调用 XML API

    curl -X PUT --data-binary @XML_FILE.xml \
      -H "Authorization: Bearer OAUTH2_TOKEN" \
      "https://storage.googleapis.com/BUCKET_NAME?lifecycle"

    其中:

    • XML_FILE 是您在第 2 步中创建的文件的名称。
    • OAUTH2_TOKEN 是您在第 1 步中生成的访问令牌。
    • BUCKET_NAME 是相关存储分区的名称,例如 my-bucket

停用生命周期管理

如需为存储分区停用生命周期管理,请执行以下操作

控制台

  1. 在 Google Cloud Console 中,转到 Cloud Storage 浏览器页面。

    转到浏览器

  2. 在存储分区列表中,找到要停用的存储分区,然后点击生命周期规则列中的条目。

    随即将显示生命周期规则页面。

  3. 点击全部删除

  4. 在出现的确认窗口中,点击确认

如需了解如何获取有关 Cloud Storage 浏览器中失败操作的详细错误信息,请参阅问题排查

gsutil

  1. 创建具有空生命周期配置的 .json 文件:

    {
      "lifecycle": {
        "rule": []
      }
    }
  2. 使用 lifecycle set 命令:

    gsutil lifecycle set LIFECYCLE_CONFIG_FILE gs://BUCKET_NAME

    其中:

    • LIFECYCLE_CONFIG_FILE 是您在第 1 步中创建的文件的名称。
    • BUCKET_NAME 是相关存储分区的名称,例如 my-bucket

代码示例

C++

如需了解详情,请参阅 Cloud Storage C++ API 参考文档

namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name) {
  StatusOr<gcs::BucketMetadata> updated_metadata = client.PatchBucket(
      bucket_name, gcs::BucketMetadataPatchBuilder().ResetLifecycle());

  if (!updated_metadata) {
    throw std::runtime_error(updated_metadata.status().message());
  }

  std::cout << "Successfully disabled bucket lifecycle management for bucket "
            << updated_metadata->name() << ".\n";
}

C#

如需了解详情,请参阅 Cloud Storage C# API 参考文档


using Google.Apis.Storage.v1.Data;
using Google.Cloud.Storage.V1;
using System;

public class DisableBucketLifecycleManagementSample
{
    public Bucket DisableBucketLifecycleManagement(string bucketName = "your-unique-bucket-name")
    {
        var storage = StorageClient.Create();
        var bucket = storage.GetBucket(bucketName);
        bucket.Lifecycle = null;
        bucket = storage.UpdateBucket(bucket);

        Console.WriteLine($"Lifecycle management is disabled for bucket {bucketName}.");
        return bucket;
    }
}

Go

如需了解详情,请参阅 Cloud Storage Go API 参考文档

import (
	"context"
	"fmt"
	"io"
	"time"

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

// disableBucketLifecycleManagement removes all existing lifecycle rules
// from the bucket.
func disableBucketLifecycleManagement(w io.Writer, bucketName string) error {
	// bucketName := "bucket-name"
	ctx := context.Background()
	client, err := storage.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("storage.NewClient: %v", err)
	}
	defer client.Close()

	ctx, cancel := context.WithTimeout(ctx, time.Second*10)
	defer cancel()

	bucket := client.Bucket(bucketName)
	bucketAttrsToUpdate := storage.BucketAttrsToUpdate{
		Lifecycle: &storage.Lifecycle{},
	}

	_, err = bucket.Update(ctx, bucketAttrsToUpdate)
	if err != nil {
		return fmt.Errorf("Bucket(%q).Update: %v", bucketName, err)
	}
	fmt.Fprintf(w, "Lifecycle management is disabled for bucket %v.\n", bucketName)

	return nil
}

Java

如需了解详情,请参阅 Cloud Storage Java API 参考文档

import com.google.cloud.storage.Bucket;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;

public class DisableLifecycleManagement {
  public static void disableLifecycleManagement(String projectId, String bucketName) {
    // The ID of your GCP project
    // String projectId = "your-project-id";

    // The ID of your GCS bucket
    // String bucketName = "your-unique-bucket-name";

    Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();
    Bucket bucket = storage.get(bucketName);
    bucket.toBuilder().deleteLifecycleRules().build().update();

    System.out.println("Lifecycle management was disabled for bucket " + bucketName);
  }
}

Node.js

如需了解详情,请参阅 Cloud Storage Node.js API 参考文档

/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// The ID of your GCS bucket
// const bucketName = 'your-unique-bucket-name';

// Imports the Google Cloud client library
const {Storage} = require('@google-cloud/storage');

// Creates a client
const storage = new Storage();

async function disableBucketLifecycleManagement() {
  await storage.bucket(bucketName).setMetadata({lifecycle: null});

  console.log(`Lifecycle management is disabled for bucket ${bucketName}`);
}

disableBucketLifecycleManagement().catch(console.error);

PHP

如需了解详情,请参阅 Cloud Storage PHP API 参考文档

use Google\Cloud\Storage\StorageClient;

/**
 * Disable bucket lifecycle management.
 *
 * @param string $bucketName The name of your Cloud Storage bucket.
 */
function disable_bucket_lifecycle_management($bucketName)
{
    // $bucketName = 'my-bucket';

    $storage = new StorageClient();

    $bucket = $storage->bucket($bucketName);

    $bucket->update([
        'lifecycle' => null
    ]);

    printf('Lifecycle management is disabled for bucket %s.' . PHP_EOL, $bucketName);
}

Python

如需了解详情,请参阅 Cloud Storage Python API 参考文档

from google.cloud import storage

def disable_bucket_lifecycle_management(bucket_name):
    """Disable lifecycle management for a bucket"""
    # bucket_name = "my-bucket"

    storage_client = storage.Client()

    bucket = storage_client.get_bucket(bucket_name)
    bucket.clear_lifecyle_rules()
    bucket.patch()
    rules = bucket.lifecycle_rules

    print("Lifecycle management is disable for bucket {} and the rules are {}".format(bucket_name, list(rules)))
    return bucket

Ruby

如需了解详情,请参阅 Cloud Storage Ruby API 参考文档

def disable_bucket_lifecycle_management bucket_name:
  # Disable lifecycle management for a bucket
  # The ID of your GCS bucket
  # bucket_name = "your-unique-bucket-name"

  require "google/cloud/storage"

  storage = Google::Cloud::Storage.new
  bucket = storage.bucket bucket_name

  bucket.lifecycle do |l|
    l.clear
  end

  puts "Lifecycle management is disabled for bucket #{bucket_name}"
end

REST API

JSON API

  1. OAuth 2.0 Playground 获取授权访问令牌。将 Playground 配置为使用您自己的 OAuth 凭据。
  2. 创建具有空生命周期配置的 .json 文件:

    {
      "lifecycle": {
        "rule": []
      }
    }
  3. 使用 cURL,通过 PATCH Bucket 请求调用 JSON API

    curl -X PATCH --data-binary @LIFECYCLE_CONFIG_FILE.json \
      -H "Authorization: Bearer OAUTH2_TOKEN" \
      -H "Content-Type: application/json" \
      "https://storage.googleapis.com/storage/v1/b/BUCKET_NAME?fields=lifecycle"

    其中:

    • LIFECYCLE_CONFIG_FILE 是您在第 2 步中创建的文件的名称。
    • OAUTH2_TOKEN 是您在第 1 步中生成的访问令牌。
    • BUCKET_NAME 是相关存储分区的名称,例如 my-bucket

XML API

  1. OAuth 2.0 Playground 获取授权访问令牌。将 Playground 配置为使用您自己的 OAuth 凭据。
  2. 创建具有空生命周期配置的 .xml 文件:

    <LifecycleConfiguration/>
  3. 使用 cURL,通过 PUT Bucket 请求调用 XML API

    curl -X PUT --data-binary @XML_FILE.xml \
      -H "Authorization: Bearer OAUTH2_TOKEN" \
      "https://storage.googleapis.com/BUCKET_NAME?lifecycle"

    其中:

    • XML_FILE 是您在第 2 步中创建的文件的名称。
    • OAUTH2_TOKEN 是您在第 1 步中生成的访问令牌。
    • BUCKET_NAME 是相关存储分区的名称,例如 my-bucket

检查生命周期配置

如需检查对存储分区设置的生命周期配置,请执行以下操作

控制台

  1. 在 Google Cloud Console 中,转到 Cloud Storage 浏览器页面。

    转到浏览器

  2. 在存储分区列表中,您可以在生命周期列中看到每个存储分区的生命周期状态。

    您可以点击此状态以添加、查看、修改和删除规则。

如需了解如何获取有关 Cloud Storage 浏览器中失败操作的详细错误信息,请参阅问题排查

gsutil

  1. 使用 lifecycle get 命令:

    gsutil lifecycle get gs://BUCKET_NAME

    其中 BUCKET_NAME 是相关存储分区的名称,例如 my-bucket

代码示例

C++

如需了解详情,请参阅 Cloud Storage C++ API 参考文档

namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name) {
  StatusOr<gcs::BucketMetadata> updated_metadata =
      client.GetBucketMetadata(bucket_name);

  if (!updated_metadata) {
    throw std::runtime_error(updated_metadata.status().message());
  }

  if (!updated_metadata->has_lifecycle() ||
      updated_metadata->lifecycle().rule.empty()) {
    std::cout << "Bucket lifecycle management is not enabled for bucket "
              << updated_metadata->name() << ".\n";
    return;
  }
  std::cout << "Bucket lifecycle management is enabled for bucket "
            << updated_metadata->name() << ".\n";
  std::cout << "The bucket lifecycle rules are";
  for (auto const& kv : updated_metadata->lifecycle().rule) {
    std::cout << "\n " << kv.condition() << ", " << kv.action();
  }
  std::cout << "\n";
}

C#

如需了解详情,请参阅 Cloud Storage C# API 参考文档

如需查看存储分区的生命周期政策,请按照显示存储分区的元数据中的说明操作,并在响应中查找生命周期政策字段。

using Google.Apis.Storage.v1.Data;
using Google.Cloud.Storage.V1;
using System;

public class GetBucketMetadataSample
{
    public Bucket GetBucketMetadata(string bucketName = "your-unique-bucket-name")
    {
        var storage = StorageClient.Create();
        var bucket = storage.GetBucket(bucketName, new GetBucketOptions { Projection = Projection.Full });
        Console.WriteLine($"Bucket:\t{bucket.Name}");
        Console.WriteLine($"Acl:\t{bucket.Acl}");
        Console.WriteLine($"Billing:\t{bucket.Billing}");
        Console.WriteLine($"Cors:\t{bucket.Cors}");
        Console.WriteLine($"DefaultEventBasedHold:\t{bucket.DefaultEventBasedHold}");
        Console.WriteLine($"DefaultObjectAcl:\t{bucket.DefaultObjectAcl}");
        Console.WriteLine($"Encryption:\t{bucket.Encryption}");
        if (bucket.Encryption != null)
        {
            Console.WriteLine($"KmsKeyName:\t{bucket.Encryption.DefaultKmsKeyName}");
        }
        Console.WriteLine($"Id:\t{bucket.Id}");
        Console.WriteLine($"Kind:\t{bucket.Kind}");
        Console.WriteLine($"Lifecycle:\t{bucket.Lifecycle}");
        Console.WriteLine($"Location:\t{bucket.Location}");
        Console.WriteLine($"LocationType:\t{bucket.LocationType}");
        Console.WriteLine($"Logging:\t{bucket.Logging}");
        Console.WriteLine($"Metageneration:\t{bucket.Metageneration}");
        Console.WriteLine($"Owner:\t{bucket.Owner}");
        Console.WriteLine($"ProjectNumber:\t{bucket.ProjectNumber}");
        Console.WriteLine($"RetentionPolicy:\t{bucket.RetentionPolicy}");
        Console.WriteLine($"SelfLink:\t{bucket.SelfLink}");
        Console.WriteLine($"StorageClass:\t{bucket.StorageClass}");
        Console.WriteLine($"TimeCreated:\t{bucket.TimeCreated}");
        Console.WriteLine($"Updated:\t{bucket.Updated}");
        Console.WriteLine($"Versioning:\t{bucket.Versioning}");
        Console.WriteLine($"Website:\t{bucket.Website}");
        if (bucket.Labels != null)
        {
            Console.WriteLine("Labels:");
            foreach (var label in bucket.Labels)
            {
                Console.WriteLine($"{label.Key}:\t{label.Value}");
            }
        }
        return bucket;
    }
}

Go

如需了解详情,请参阅 Cloud Storage Go API 参考文档

如需查看存储分区的生命周期政策,请按照显示存储分区的元数据中的说明操作,并在响应中查找生命周期政策字段。
import (
	"context"
	"fmt"
	"io"
	"time"

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

// getBucketMetadata gets the bucket metadata.
func getBucketMetadata(w io.Writer, bucketName string) (*storage.BucketAttrs, error) {
	// bucketName := "bucket-name"
	ctx := context.Background()
	client, err := storage.NewClient(ctx)
	if err != nil {
		return nil, fmt.Errorf("storage.NewClient: %v", err)
	}
	defer client.Close()

	ctx, cancel := context.WithTimeout(ctx, time.Second*10)
	defer cancel()
	attrs, err := client.Bucket(bucketName).Attrs(ctx)
	if err != nil {
		return nil, fmt.Errorf("Bucket(%q).Attrs: %v", bucketName, err)
	}
	fmt.Fprintf(w, "BucketName: %v\n", attrs.Name)
	fmt.Fprintf(w, "Location: %v\n", attrs.Location)
	fmt.Fprintf(w, "LocationType: %v\n", attrs.LocationType)
	fmt.Fprintf(w, "StorageClass: %v\n", attrs.StorageClass)
	fmt.Fprintf(w, "TimeCreated: %v\n", attrs.Created)
	fmt.Fprintf(w, "Metageneration: %v\n", attrs.MetaGeneration)
	fmt.Fprintf(w, "PredefinedACL: %v\n", attrs.PredefinedACL)
	if attrs.Encryption != nil {
		fmt.Fprintf(w, "DefaultKmsKeyName: %v\n", attrs.Encryption.DefaultKMSKeyName)
	}
	if attrs.Website != nil {
		fmt.Fprintf(w, "IndexPage: %v\n", attrs.Website.MainPageSuffix)
		fmt.Fprintf(w, "NotFoundPage: %v\n", attrs.Website.NotFoundPage)
	}
	fmt.Fprintf(w, "DefaultEventBasedHold: %v\n", attrs.DefaultEventBasedHold)
	if attrs.RetentionPolicy != nil {
		fmt.Fprintf(w, "RetentionEffectiveTime: %v\n", attrs.RetentionPolicy.EffectiveTime)
		fmt.Fprintf(w, "RetentionPeriod: %v\n", attrs.RetentionPolicy.RetentionPeriod)
		fmt.Fprintf(w, "RetentionPolicyIsLocked: %v\n", attrs.RetentionPolicy.IsLocked)
	}
	fmt.Fprintf(w, "RequesterPays: %v\n", attrs.RequesterPays)
	fmt.Fprintf(w, "VersioningEnabled: %v\n", attrs.VersioningEnabled)
	if attrs.Logging != nil {
		fmt.Fprintf(w, "LogBucket: %v\n", attrs.Logging.LogBucket)
		fmt.Fprintf(w, "LogObjectPrefix: %v\n", attrs.Logging.LogObjectPrefix)
	}
	if attrs.CORS != nil {
		fmt.Fprintln(w, "CORS:")
		for _, v := range attrs.CORS {
			fmt.Fprintf(w, "\tMaxAge: %v\n", v.MaxAge)
			fmt.Fprintf(w, "\tMethods: %v\n", v.Methods)
			fmt.Fprintf(w, "\tOrigins: %v\n", v.Origins)
			fmt.Fprintf(w, "\tResponseHeaders: %v\n", v.ResponseHeaders)
		}
	}
	if attrs.Labels != nil {
		fmt.Fprintf(w, "\n\n\nLabels:")
		for key, value := range attrs.Labels {
			fmt.Fprintf(w, "\t%v = %v\n", key, value)
		}
	}
	return attrs, nil
}

Java

如需了解详情,请参阅 Cloud Storage Java API 参考文档

如需查看存储分区的生命周期政策,请按照显示存储分区的元数据中的说明操作,并在响应中查找生命周期政策字段。
import com.google.cloud.storage.Bucket;
import com.google.cloud.storage.BucketInfo;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;
import java.util.Map;

public class GetBucketMetadata {
  public static void getBucketMetadata(String projectId, String bucketName) {
    // The ID of your GCP project
    // String projectId = "your-project-id";

    // The ID of your GCS bucket
    // String bucketName = "your-unique-bucket-name";

    Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();

    // Select all fields. Fields can be selected individually e.g. Storage.BucketField.NAME
    Bucket bucket =
        storage.get(bucketName, Storage.BucketGetOption.fields(Storage.BucketField.values()));

    // Print bucket metadata
    System.out.println("BucketName: " + bucket.getName());
    System.out.println("DefaultEventBasedHold: " + bucket.getDefaultEventBasedHold());
    System.out.println("DefaultKmsKeyName: " + bucket.getDefaultKmsKeyName());
    System.out.println("Id: " + bucket.getGeneratedId());
    System.out.println("IndexPage: " + bucket.getIndexPage());
    System.out.println("Location: " + bucket.getLocation());
    System.out.println("LocationType: " + bucket.getLocationType());
    System.out.println("Metageneration: " + bucket.getMetageneration());
    System.out.println("NotFoundPage: " + bucket.getNotFoundPage());
    System.out.println("RetentionEffectiveTime: " + bucket.getRetentionEffectiveTime());
    System.out.println("RetentionPeriod: " + bucket.getRetentionPeriod());
    System.out.println("RetentionPolicyIsLocked: " + bucket.retentionPolicyIsLocked());
    System.out.println("RequesterPays: " + bucket.requesterPays());
    System.out.println("SelfLink: " + bucket.getSelfLink());
    System.out.println("StorageClass: " + bucket.getStorageClass().name());
    System.out.println("TimeCreated: " + bucket.getCreateTime());
    System.out.println("VersioningEnabled: " + bucket.versioningEnabled());
    if (bucket.getLabels() != null) {
      System.out.println("\n\n\nLabels:");
      for (Map.Entry<String, String> label : bucket.getLabels().entrySet()) {
        System.out.println(label.getKey() + "=" + label.getValue());
      }
    }
    if (bucket.getLifecycleRules() != null) {
      System.out.println("\n\n\nLifecycle Rules:");
      for (BucketInfo.LifecycleRule rule : bucket.getLifecycleRules()) {
        System.out.println(rule);
      }
    }
  }
}

Node.js

如需了解详情,请参阅 Cloud Storage Node.js API 参考文档

如需查看存储分区的生命周期政策,请按照显示存储分区的元数据中的说明操作,并在响应中查找生命周期政策字段。
// Imports the Google Cloud client library
const {Storage} = require('@google-cloud/storage');

// Creates a client
const storage = new Storage();

async function getBucketMetadata() {
  /**
   * TODO(developer): Uncomment the following lines before running the sample.
   */
  // The ID of your GCS bucket
  // const bucketName = 'your-unique-bucket-name';

  // Get Bucket Metadata
  const [metadata] = await storage.bucket(bucketName).getMetadata();

  for (const [key, value] of Object.entries(metadata)) {
    console.log(`${key}: ${value}`);
  }
}

PHP

如需了解详情,请参阅 Cloud Storage PHP API 参考文档

如需查看存储分区的生命周期政策,请按照显示存储分区的元数据中的说明操作,并在响应中查找生命周期政策字段。
use Google\Cloud\Storage\StorageClient;

/**
 * Get bucket metadata.
 *
 * @param string $bucketName The name of your Cloud Storage bucket.
 */
function get_bucket_metadata($bucketName)
{
    // $bucketName = 'my-bucket';

    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);
    $info = $bucket->info();

    printf('Bucket Metadata: %s' . PHP_EOL, print_r($info));
}

Python

如需了解详情,请参阅 Cloud Storage Python API 参考文档

如需查看存储分区的生命周期政策,请按照显示存储分区的元数据中的说明操作,并在响应中查找生命周期政策字段。

from google.cloud import storage

def bucket_metadata(bucket_name):
    """Prints out a bucket's metadata."""
    # bucket_name = 'your-bucket-name'

    storage_client = storage.Client()
    bucket = storage_client.get_bucket(bucket_name)

    print(f"ID: {bucket.id}")
    print(f"Name: {bucket.name}")
    print(f"Storage Class: {bucket.storage_class}")
    print(f"Location: {bucket.location}")
    print(f"Location Type: {bucket.location_type}")
    print(f"Cors: {bucket.cors}")
    print(f"Default Event Based Hold: {bucket.default_event_based_hold}")
    print(f"Default KMS Key Name: {bucket.default_kms_key_name}")
    print(f"Metageneration: {bucket.metageneration}")
    print(
        f"Public Access Prevention: {bucket.iam_configuration.public_access_prevention}"
    )
    print(f"Retention Effective Time: {bucket.retention_policy_effective_time}")
    print(f"Retention Period: {bucket.retention_period}")
    print(f"Retention Policy Locked: {bucket.retention_policy_locked}")
    print(f"Requester Pays: {bucket.requester_pays}")
    print(f"Self Link: {bucket.self_link}")
    print(f"Time Created: {bucket.time_created}")
    print(f"Versioning Enabled: {bucket.versioning_enabled}")
    print(f"Labels: {bucket.labels}")

Ruby

如需了解详情,请参阅 Cloud Storage Ruby API 参考文档

如需查看存储分区的生命周期政策,请按照显示存储分区的元数据中的说明操作,并在响应中查找生命周期政策字段。
def get_bucket_metadata bucket_name:
  # The ID of your GCS bucket
  # bucket_name = "your-unique-bucket-name"

  require "google/cloud/storage"

  storage = Google::Cloud::Storage.new
  bucket  = storage.bucket bucket_name

  puts "ID:                       #{bucket.id}"
  puts "Name:                     #{bucket.name}"
  puts "Storage Class:            #{bucket.storage_class}"
  puts "Location:                 #{bucket.location}"
  puts "Location Type:            #{bucket.location_type}"
  puts "Cors:                     #{bucket.cors}"
  puts "Default Event Based Hold: #{bucket.default_event_based_hold?}"
  puts "Default KMS Key Name:     #{bucket.default_kms_key}"
  puts "Logging Bucket:           #{bucket.logging_bucket}"
  puts "Logging Prefix:           #{bucket.logging_prefix}"
  puts "Metageneration:           #{bucket.metageneration}"
  puts "Retention Effective Time: #{bucket.retention_effective_at}"
  puts "Retention Period:         #{bucket.retention_period}"
  puts "Retention Policy Locked:  #{bucket.retention_policy_locked?}"
  puts "Requester Pays:           #{bucket.requester_pays}"
  puts "Self Link:                #{bucket.api_url}"
  puts "Time Created:             #{bucket.created_at}"
  puts "Versioning Enabled:       #{bucket.versioning?}"
  puts "Index Page:               #{bucket.website_main}"
  puts "Not Found Page:           #{bucket.website_404}"
  puts "Labels:"
  bucket.labels.each do |key, value|
    puts " - #{key} = #{value}"
  end
  puts "Lifecycle Rules:"
  bucket.lifecycle.each do |rule|
    puts "#{rule.action} - #{rule.storage_class} - #{rule.age} - #{rule.matches_storage_class}"
  end
end

REST API

JSON API

  1. OAuth 2.0 Playground 获取授权访问令牌。将 Playground 配置为使用您自己的 OAuth 凭据。
  2. 使用 cURL,通过 GET Bucket 请求调用 JSON API

    curl -X GET \
      -H "Authorization: Bearer OAUTH2_TOKEN" \
      "https://storage.googleapis.com/storage/v1/b/BUCKET_NAME?fields=lifecycle"

    其中:

    • OAUTH2_TOKEN 是您在第 1 步中生成的访问令牌。
    • BUCKET_NAME 是相关存储分区的名称,例如 my-bucket

XML API

  1. OAuth 2.0 Playground 获取授权访问令牌。将 Playground 配置为使用您自己的 OAuth 凭据。
  2. 使用 cURL,通过 GET Bucket 请求调用 XML API

    curl -X GET \
      -H "Authorization: Bearer OAUTH2_TOKEN" \
      "https://storage.googleapis.com/BUCKET_NAME?lifecycle"

    其中:

    • OAUTH2_TOKEN 是您在第 1 步中生成的访问令牌。
    • BUCKET_NAME 是相关存储分区的名称,例如 my-bucket

对象生命周期配置示例

以下示例展示了特定的生命周期配置,该配置可在满足通用生命周期条件时执行生命周期操作。 这些配置适用于所配置存储分区中的所有当前和未来的对象。

删除旧对象版本

以下生命周期配置定义了两个规则。请注意,只有在存储桶上使用对象版本控制时,这些规则才适用:

  1. 如果存储分区中有 2 个较新版本的对象,请删除对象的非当前版本。受此规则约束的对象将被永久删除并且无法恢复。

  2. 删除以非当前版本状态保留 7 天的非当前版本对象。受此规则约束的对象将被永久删除并且无法恢复。

在使用对象版本控制的存储分区中,这两种规则的组合效果是,活跃对象具有时间范围,如果这些对象被覆盖或被删除,则可以在该时间范围内进行恢复:此类对象会在存储分区中以非当前版本状态保留七天,或者保留到存储分区中有 2 个较新版本的对象为止。

控制台

这里的设置遵循了启用部分中的说明。

  1. 如需在已有较新版本的情况下删除非当前版本对象,请执行以下操作:

    1. 选择删除对象操作。
    2. 选择有效状态条件,然后选择非当前单选按钮。
    3. 选择较新版本的数量条件,然后输入值 2
  2. 如需删除以非当前版本状态保留 7 天的非当前版本对象,请执行以下操作:

    1. 选择删除对象操作。
    2. 选择变为非当前版本后的天数条件,然后输入值 7

gsutil

通过启用生命周期管理,可以将以下生命周期配置应用于存储分区。

{
"lifecycle": {
  "rule": [
  {
    "action": {"type": "Delete"},
    "condition": {
      "numNewerVersions": 2,
      "isLive": false
    }
  },
  {
    "action": {"type": "Delete"},
    "condition": {
      "daysSinceNoncurrentTime": 7
    }
  }
]
}
}

如需了解生命周期配置文件的通用格式,请参阅适用于 JSON 的存储分区资源表示法

REST API

JSON API

通过启用生命周期管理,可以将以下生命周期配置应用于存储分区。

{
"lifecycle": {
  "rule": [
  {
    "action": {"type": "Delete"},
    "condition": {
      "numNewerVersions": 2,
      "isLive": false
    }
  },
  {
    "action": {"type": "Delete"},
    "condition": {
      "daysSinceNoncurrentTime": 7
    }
  }
]
}
}

如需了解生命周期配置文件的通用格式,请参阅适用于 JSON 的存储分区资源表示法

XML API

通过启用生命周期管理,可以将以下生命周期配置应用于存储分区。

<?xml version="1.0" encoding="UTF-8" ?>
<LifecycleConfiguration>
    <Rule>
        <Action>
            <Delete/>
        </Action>
        <Condition>
            <IsLive>false</IsLive>
            <NumberOfNewerVersions>2</Age>
        </Condition>
    </Rule>
    <Rule>
        <Action>
            <Delete/>
        </Action>
        <Condition>
            <DaysSinceNoncurrentTime>7</DaysSinceNoncurrentTime>
        </Condition>
    </Rule>
</LifecycleConfiguration>

如需了解生命周期配置文件的通用格式,请参阅适用于 XML 的生命周期配置格式

配置修改

根据您的目标,您可以对此示例配置进行多项修改:

  • 如果要保护数据免遭意外删除而非意外覆盖,请将较新版本的数量设置为 1,这样做也可以缩减存储费用,因为您可以保留较少的对象版本。

  • 如果您的数据以 Nearline Storage、Coldline Storage 或 Archive Storage 形式存储,请添加 Age 条件或使用更大的 DaysSinceNoncurrent 值以避免支付提前删除费用。请注意,即使发生此类更改,您也可能要支付提前删除费用,具体取决于您覆盖和删除对象的频率。

更改对象的存储类别

以下生命周期配置定义了两条规则:

  1. 如果对象的存在时间超过 365 天(一年)且其当前存储类别为 Standard 存储空间、Multi-Regional 存储空间或 Durable Reduced Availability (DRA) 存储空间,则将该对象的存储类别更改为 Nearline 存储空间。
  2. 如果对象的存储类别的存在时间大于 1095 天(三年)且其当前存储类别为 Nearline 存储空间,则将其更改为 Coldline 存储空间。

控制台

这里的设置遵循了启用部分中的说明。

  1. 如需在创建对象 365 天后将对象移动到 Cloud Storage Nearline,请执行以下操作:

    1. 选择将存储类别设置为 Nearline 操作。
    2. 选择存在时间条件,然后输入值 365
    3. 选择存储类别符合条件,然后选择 StandardMulti-RegionalDurable Reduced Availability 选项。
  2. 如需在创建对象 1095 天后将对象移动到 Cloud Storage Coldline,请执行以下操作:

    1. 选择将存储类别设置为 Coldline 操作。
    2. 选择存在时间条件,然后输入值 1095
    3. 选择存储类别符合条件,然后选择 Nearline 选项。

gsutil

通过启用生命周期管理,可以将以下生命周期配置应用于存储分区。

{
"lifecycle": {
  "rule": [
  {
    "action": {
      "type": "SetStorageClass",
      "storageClass": "NEARLINE"
    },
    "condition": {
      "age": 365,
      "matchesStorageClass": ["MULTI_REGIONAL", "STANDARD", "DURABLE_REDUCED_AVAILABILITY"]
    }
  },
  {
    "action": {
      "type": "SetStorageClass",
      "storageClass": "COLDLINE"
    },
    "condition": {
      "age": 1095,
      "matchesStorageClass": ["NEARLINE"]
    }
  }
]
}
}

如需了解生命周期配置文件的通用格式,请参阅适用于 JSON 的存储分区资源表示法

REST API

JSON API

通过启用生命周期管理,可以将以下生命周期配置应用于存储分区。

{
"lifecycle": {
  "rule": [
  {
    "action": {
      "type": "SetStorageClass",
      "storageClass": "NEARLINE"
    },
    "condition": {
      "age": 365,
      "matchesStorageClass": ["MULTI_REGIONAL", "STANDARD", "DURABLE_REDUCED_AVAILABILITY"]
    }
  },
  {
    "action": {
      "type": "SetStorageClass",
      "storageClass": "COLDLINE"
    },
    "condition": {
      "age": 1095,
      "matchesStorageClass": ["NEARLINE"]
    }
  }
]
}
}

如需了解生命周期配置文件的通用格式,请参阅适用于 JSON 的存储分区资源表示法

XML API

通过启用生命周期管理,可以将以下生命周期配置应用于存储分区。

<?xml version="1.0" encoding="UTF-8" ?>
<LifecycleConfiguration>
    <Rule>
        <Action>
            <SetStorageClass>NEARLINE</SetStorageClass>
        </Action>
        <Condition>
            <Age>365</Age>
            <MatchesStorageClass>MULTI_REGIONAL</MatchesStorageClass>
            <MatchesStorageClass>STANDARD</MatchesStorageClass>
            <MatchesStorageClass>DURABLE_REDUCED_AVAILABILITY</MatchesStorageClass>
        </Condition>
    </Rule>
    <Rule>
        <Action>
            <SetStorageClass>COLDLINE</SetStorageClass>
        </Action>
        <Condition>
            <Age>1095</Age>
            <MatchesStorageClass>NEARLINE</MatchesStorageClass>
        </Condition>
    </Rule>
</LifecycleConfiguration>

如需了解生命周期配置文件的通用格式,请参阅适用于 XML 的生命周期配置格式

后续步骤