Mengaktifkan pengelolaan siklus proses untuk bucket

Mengaktifkan pengelolaan siklus proses untuk bucket Cloud Storage.

Jelajahi lebih lanjut

Untuk dokumentasi mendetail yang menyertakan contoh kode ini, lihat artikel berikut:

Contoh kode

C++

Untuk informasi selengkapnya, lihat Dokumentasi referensi Cloud Storage C++ API.

Untuk melakukan autentikasi ke Cloud Storage, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, baca Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

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::move(updated_metadata).status();

  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#

Untuk mengetahui informasi selengkapnya, lihatDokumentasi referensi Cloud Storage C# API.

Untuk melakukan autentikasi ke Cloud Storage, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, baca Menyiapkan autentikasi untuk lingkungan pengembangan lokal.


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($"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

Untuk mengetahui informasi selengkapnya, lihatDokumentasi referensi Cloud Storage Go API.

Untuk melakukan autentikasi ke Cloud Storage, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, baca Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

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: %w", 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: %w", 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

Untuk mengetahui informasi selengkapnya, lihatDokumentasi referensi Cloud Storage Java API.

Untuk melakukan autentikasi ke Cloud Storage, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, baca Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

import static com.google.cloud.storage.BucketInfo.LifecycleRule.LifecycleAction;
import static com.google.cloud.storage.BucketInfo.LifecycleRule.LifecycleCondition;

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(
                    LifecycleAction.newDeleteAction(),
                    LifecycleCondition.newBuilder().setAge(100).build())))
        .build()
        .update();

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

Node.js

Untuk mengetahui informasi selengkapnya, lihatDokumentasi referensi Cloud Storage Node.js API.

Untuk melakukan autentikasi ke Cloud Storage, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, baca Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

/**
 * 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: {
      type: '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

Untuk mengetahui informasi selengkapnya, lihatDokumentasi referensi Cloud Storage PHP API.

Untuk melakukan autentikasi ke Cloud Storage, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, baca Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

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

/**
 * Enable bucket lifecycle management.
 *
 * @param string $bucketName The name of your Cloud Storage bucket.
 *        (e.g. 'my-bucket')
 */
function enable_bucket_lifecycle_management(string $bucketName): void
{
    $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

Untuk mengetahui informasi selengkapnya, lihatDokumentasi referensi Cloud Storage Python API.

Untuk melakukan autentikasi ke Cloud Storage, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, baca Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

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(f"Lifecycle management rules for bucket {bucket_name} are {list(rules)}")
    bucket.add_lifecycle_delete_rule(age=2)
    bucket.patch()

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

    return bucket

Ruby

Untuk mengetahui informasi selengkapnya, lihatDokumentasi referensi Cloud Storage Ruby API.

Untuk melakukan autentikasi ke Cloud Storage, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, baca Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

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

Langkah selanjutnya

Untuk menelusuri dan memfilter contoh kode untuk produk Google Cloud lainnya, lihat browser contoh Google Cloud.