将禁止公开访问设置为继承

从项目或组织政策配置继承阻止公开访问这一机制。

深入探索

如需查看包含此代码示例的详细文档,请参阅以下内容:

代码示例

C++

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

如需向 Cloud Storage 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name) {
  gcs::BucketIamConfiguration configuration;
  configuration.public_access_prevention =
      gcs::PublicAccessPreventionInherited();
  auto updated = client.PatchBucket(
      bucket_name, gcs::BucketMetadataPatchBuilder().SetIamConfiguration(
                       std::move(configuration)));
  if (!updated) throw std::move(updated).status();

  std::cout << "Public Access Prevention is set to 'inherited' for "
            << updated->name() << "\n";
}

C#

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

如需向 Cloud Storage 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证


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

public class SetPublicAccessPreventionInheritedSample
{
    public Bucket SetPublicAccessPreventionInherited(string bucketName = "your-unique-bucket-name")
    {
        var storage = StorageClient.Create();
        var bucket = storage.GetBucket(bucketName);

        // Sets public access prevention to "inherited" for the bucket.
        bucket.IamConfiguration.PublicAccessPrevention = "inherited";
        bucket = storage.UpdateBucket(bucket);

        Console.WriteLine($"Public access prevention is 'inherited' for {bucketName}.");
        return bucket;
    }
}

Go

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

如需向 Cloud Storage 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

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

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

// setPublicAccessPreventionInherited sets public access prevention to
// "inherited" for the bucket.
func setPublicAccessPreventionInherited(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)
	setPublicAccessPrevention := storage.BucketAttrsToUpdate{
		PublicAccessPrevention: storage.PublicAccessPreventionInherited,
	}
	if _, err := bucket.Update(ctx, setPublicAccessPrevention); err != nil {
		return fmt.Errorf("Bucket(%q).Update: %w", bucketName, err)
	}
	fmt.Fprintf(w, "Public access prevention is 'inherited' for %v", bucketName)
	return nil
}

Java

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

如需向 Cloud Storage 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

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

public class SetPublicAccessPreventionInherited {
  public static void setPublicAccessPreventionInherited(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);

    // Sets public access prevention to 'inherited' for the bucket
    bucket
        .toBuilder()
        .setIamConfiguration(
            BucketInfo.IamConfiguration.newBuilder()
                .setPublicAccessPrevention(BucketInfo.PublicAccessPrevention.INHERITED)
                .build())
        .build()
        .update();

    System.out.println("Public access prevention is set to 'inherited' for " + bucketName);
  }
}

Node.js

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

如需向 Cloud Storage 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// The name of your GCS bucket
// const bucketName = 'Name of a bucket, e.g. my-bucket';
// Imports the Google Cloud client library
const {Storage} = require('@google-cloud/storage');

// Creates a client
const storage = new Storage();
async function setPublicAccessPreventionInherited() {
  // Sets public access prevention to 'inherited' for the bucket
  await storage.bucket(bucketName).setMetadata({
    iamConfiguration: {
      publicAccessPrevention: 'inherited',
    },
  });

  console.log(`Public access prevention is 'inherited' for ${bucketName}.`);
}

setPublicAccessPreventionInherited();

PHP

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

如需向 Cloud Storage 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

use Google\Cloud\Storage\StorageClient;

/**
 * Set the bucket Public Access Prevention to inherited.
 *
 * @param string $bucketName the name of your Cloud Storage bucket.
 *        (e.g. 'my-bucket')
 */
function set_public_access_prevention_inherited(string $bucketName): void
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);

    $bucket->update([
        'iamConfiguration' => [
            'publicAccessPrevention' => 'inherited'
        ]
    ]);

    printf(
        'Public Access Prevention has been set to inherited for %s.' . PHP_EOL,
        $bucketName
    );
}

Python

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

如需向 Cloud Storage 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证


from google.cloud import storage
from google.cloud.storage.constants import PUBLIC_ACCESS_PREVENTION_INHERITED

def set_public_access_prevention_inherited(bucket_name):
    """Sets the public access prevention status to inherited, so that the bucket inherits its setting from its parent project."""
    # The ID of your GCS bucket
    # bucket_name = "my-bucket"

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

    bucket.iam_configuration.public_access_prevention = (
        PUBLIC_ACCESS_PREVENTION_INHERITED
    )
    bucket.patch()

    print(f"Public access prevention is 'inherited' for {bucket.name}.")

Ruby

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

如需向 Cloud Storage 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

def set_public_access_prevention_inherited 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

  bucket.public_access_prevention = :inherited

  puts "Public access prevention is 'inherited' for #{bucket_name}."
end

后续步骤

如需搜索和过滤其他 Google Cloud 产品的代码示例,请参阅 Google Cloud 示例浏览器