公開アクセス防止を使用する

概要

このページでは、公開アクセスを防止するバケットの設定と組織のポリシーの制約の使用方法について説明します。公開アクセスの防止により、バケットとオブジェクトへの公開アクセスを制限できます。

始める前に

Cloud Storage で公開アクセス防止を使用するには、公開アクセス防止を設定する階層レベルに関する適切な権限が必要です。

始める前に、公開アクセスをブロックしてもワークフローが中断されないことを確認することもおすすめします。詳細については、既存のリソースで適用する際の考慮事項をご覧ください。

バケット設定を使用する

このセクションでは、個々のバケットに対して公開アクセス防止を適用または削除する方法と、個々のバケットのステータスを確認する方法について説明します。

公開アクセスの防止を設定する

個々のバケットの公開アクセスの防止設定を変更するには:

コンソール

  1. Google Cloud コンソールで、Cloud Storage の [バケット] ページに移動します。

    [バケット] に移動

  2. バケットのリストで、公開アクセスの防止を適用または削除するバケットの名前をクリックします。

  3. [バケットの詳細] ページで、[権限] タブをクリックします。

  4. [公開アクセス] カードで、[公開アクセスの防止] をクリックして公開アクセスの防止を適用するか、[一般公開アクセスを許可] をクリックして公開アクセスの防止を削除します。

  5. [確認] をクリックします。

失敗した Cloud Storage オペレーションの詳細なエラー情報を Google Cloud コンソールで確認する方法については、トラブルシューティングをご覧ください。

コマンドライン

適切なフラグを指定して、gcloud storage buckets update コマンドを使用します。

gcloud storage buckets update gs://BUCKET_NAME FLAG

ここで

  • BUCKET_NAME は、関連するバケットの名前です。例: my-bucket

  • FLAG は、公開アクセスの防止を有効にする場合は --public-access-prevention、無効にする場合は --no-public-access-prevention です。

正常に終了すると、レスポンスは次の例のようになります。

Updating gs://my-bucket/...
  Completed 1  

クライアント ライブラリ

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::PublicAccessPreventionEnforced();
  StatusOr<gcs::BucketMetadata> 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 'enforced' for "
            << updated->name() << "\n";
}

次のサンプルでは、バケットに対して公開アクセスの防止を inherited に設定します。

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 SetPublicAccessPreventionEnforcedSample
{
    public Bucket SetPublicAccessPreventionEnforced(string bucketName = "your-unique-bucket-name")
    {
        var storage = StorageClient.Create();
        var bucket = storage.GetBucket(bucketName);

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

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

次のサンプルでは、バケットに対して公開アクセスの防止を inherited に設定します。


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"
)

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

次のサンプルでは、バケットに対して公開アクセスの防止を inherited に設定します。

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 SetPublicAccessPreventionEnforced {
  public static void setPublicAccessPreventionEnforced(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);

    // Enforces public access prevention for the bucket
    bucket
        .toBuilder()
        .setIamConfiguration(
            BucketInfo.IamConfiguration.newBuilder()
                .setPublicAccessPrevention(BucketInfo.PublicAccessPrevention.ENFORCED)
                .build())
        .build()
        .update();

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

次のサンプルでは、バケットに対して公開アクセスの防止を inherited に設定します。

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();

// Enforces public access prevention for the bucket
async function setPublicAccessPreventionEnforced() {
  await storage.bucket(bucketName).setMetadata({
    iamConfiguration: {
      publicAccessPrevention: 'enforced',
    },
  });

  console.log(
    `Public access prevention is set to enforced for ${bucketName}.`
  );
}

setPublicAccessPreventionEnforced();

次のサンプルでは、バケットに対して公開アクセスの防止を inherited に設定します。

/**
 * 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 enforced.
 *
 * @param string $bucketName the name of your Cloud Storage bucket.
 *        (e.g. 'my-bucket')
 */
function set_public_access_prevention_enforced(string $bucketName): void
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);

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

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

次のサンプルでは、バケットに対して公開アクセスの防止を inherited に設定します。

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_ENFORCED

def set_public_access_prevention_enforced(bucket_name):
    """Enforce public access prevention for a bucket."""
    # 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_ENFORCED
    )
    bucket.patch()

    print(f"Public access prevention is set to enforced for {bucket.name}.")

次のサンプルでは、バケットに対して公開アクセスの防止を inherited に設定します。


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_enforced 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 = :enforced

  puts "Public access prevention is set to enforced for #{bucket_name}."
end

次のサンプルでは、バケットに対して公開アクセスの防止を inherited に設定します。

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

REST API

JSON API

  1. OAuth 2.0 Playground から認可アクセス トークンを取得します。固有の OAuth 認証情報を使用するように Playground を構成します。手順については、API 認証をご覧ください。
  2. 次の情報が含まれる JSON ファイルを作成します。

     {
        "iamConfiguration": {
          "publicAccessPrevention": "STATE",
        }
      }
    

    ここで、<var>STATE</var>enforced または inherited です。

  3. cURL を使用して、目的の fields を含む PATCH Bucket リクエストで JSON API を呼び出します。

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

    ここで

    • JSON_FILE_NAME は、前の手順で作成した JSON ファイルのパスです。
    • OAUTH2_TOKEN は、前の手順で生成したアクセス トークンです。
    • BUCKET_NAME は、関連するバケットの名前です。例: my-bucket

XML API

XML API を使用して公開アクセスの防止を管理することはできません。代わりに、Google Cloud コンソールなどの他の Cloud Storage ツールを使用してください。

公開アクセス防止のステータスを表示する

個々のバケットの公開アクセス防止のステータスを表示するには:

コンソール

  1. Google Cloud コンソールで、Cloud Storage の [バケット] ページに移動します。

    [バケット] に移動

  2. 公開アクセスの防止のステータスを表示するバケットの名前をクリックします。

  3. [権限] タブをクリックします。

  4. [公開アクセス] カードにバケットのステータスが表示されます。

失敗した Cloud Storage オペレーションの詳細なエラー情報を Google Cloud コンソールで確認する方法については、トラブルシューティングをご覧ください。

コマンドライン

gcloud storage buckets describe コマンドを使用し、--format フラグを指定します。

gcloud storage buckets describe gs://BUCKET_NAME --format="default(public_access_prevention)"

ここで、BUCKET_NAME はステータスを表示するバケットの名前です。例: my-bucket

正常に終了すると、レスポンスは次の例のようになります。

public_access_prevention:inherited

クライアント ライブラリ

C++

詳細については、Cloud Storage C++ API のリファレンス ドキュメントをご覧ください。

Cloud Storage に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。

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

  if (bucket_metadata->has_iam_configuration() &&
      bucket_metadata->iam_configuration()
          .public_access_prevention.has_value()) {
    std::cout
        << "Public Access Prevention is "
        << *bucket_metadata->iam_configuration().public_access_prevention
        << " for bucket " << bucket_metadata->name() << "\n";
  } else {
    std::cout << "Public Access Prevention is not set for "
              << bucket_metadata->name() << "\n";
  }
}

C#

詳細については、Cloud Storage C# API のリファレンス ドキュメントをご覧ください。

Cloud Storage に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。


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

public class GetPublicAccessPreventionSample
{
    public string GetPublicAccessPrevention(string bucketName = "your-unique-bucket-name")
    {
        // Gets Bucket Metadata and prints publicAccessPrevention value (either "unspecified" or "enforced").
        var storage = StorageClient.Create();
        var bucket = storage.GetBucket(bucketName);
        var publicAccessPrevention = bucket.IamConfiguration.PublicAccessPrevention;

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

Go

詳細については、Cloud Storage Go API のリファレンス ドキュメントをご覧ください。

Cloud Storage に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。

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

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

// getPublicAccessPrevention gets the current public access prevention setting
// for the bucket, either "enforced" or "inherited".
func getPublicAccessPrevention(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()

	attrs, err := client.Bucket(bucketName).Attrs(ctx)
	if err != nil {
		return fmt.Errorf("Bucket(%q).Attrs: %w", bucketName, err)
	}
	fmt.Fprintf(w, "Public access prevention is %s for %v", attrs.PublicAccessPrevention, 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 GetPublicAccessPrevention {
  public static void getPublicAccessPrevention(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);

    // Gets Bucket Metadata and prints publicAccessPrevention value (either 'inherited' or
    // 'enforced').
    BucketInfo.PublicAccessPrevention publicAccessPrevention =
        bucket.getIamConfiguration().getPublicAccessPrevention();

    System.out.println(
        "Public access prevention is set to "
            + publicAccessPrevention.getValue()
            + " 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 getPublicAccessPrevention() {
  // Gets Bucket Metadata and prints publicAccessPrevention value (either 'inherited' or 'enforced').
  const [metadata] = await storage.bucket(bucketName).getMetadata();
  console.log(
    `Public access prevention is ${metadata.iamConfiguration.publicAccessPrevention} for ${bucketName}.`
  );
}

getPublicAccessPrevention();

PHP

詳細については、Cloud Storage PHP API のリファレンス ドキュメントをご覧ください。

Cloud Storage に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。

use Google\Cloud\Storage\StorageClient;

/**
 * Get the Public Access Prevention setting for a bucket
 *
 * @param string $bucketName the name of your Cloud Storage bucket.
 *        (e.g. 'my-bucket')
 */
function get_public_access_prevention(string $bucketName): void
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);

    $iamConfiguration = $bucket->info()['iamConfiguration'];

    printf(
        'The bucket public access prevention is %s for %s.' . PHP_EOL,
        $iamConfiguration['publicAccessPrevention'],
        $bucketName
    );
}

Python

詳細については、Cloud Storage Python API のリファレンス ドキュメントをご覧ください。

Cloud Storage に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。

from google.cloud import storage

def get_public_access_prevention(bucket_name):
    """Gets the public access prevention setting (either 'inherited' or 'enforced') for a bucket."""
    # The ID of your GCS bucket
    # bucket_name = "my-bucket"

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

    print(
        f"Public access prevention is {iam_configuration.public_access_prevention} for {bucket.name}."
    )

Ruby

詳細については、Cloud Storage Ruby API のリファレンス ドキュメントをご覧ください。

Cloud Storage に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。

def get_public_access_prevention 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 "Public access prevention is '#{bucket.public_access_prevention}' for #{bucket_name}."
end

REST API

JSON API

  1. OAuth 2.0 Playground から認可アクセス トークンを取得します。固有の OAuth 認証情報を使用するように Playground を構成します。手順については、API 認証をご覧ください。
  2. cURL を使用して、目的の fields を含む GET Bucket リクエストで JSON API を呼び出します。

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

    ここで

    • OAUTH2_TOKEN は、前の手順で生成したアクセス トークンです。
    • BUCKET_NAME は、関連するバケットの名前です。例: my-bucket

    次の例のようなレスポンスになります。

     {
      "iamConfiguration": {
          ...
          "publicAccessPrevention": "FLAG"
        }
      }

    ここで、FLAGinherited または enforced です。

XML API

XML API を使用して公開アクセスの防止を管理することはできません。代わりに、Google Cloud コンソールなどの他の Cloud Storage ツールを使用してください。

組織のポリシーを使用する

このセクションでは、公開アクセスを防止する組織のポリシーを適用する方法と、ポリシーのステータスを確認する方法を説明します。

公開アクセスの防止を設定する

プロジェクト、フォルダ、組織レベルで公開アクセスの防止を無効にするには:

コンソール

storage.publicAccessPrevention 制約を使用して、組織のポリシーの作成と管理の手順に沿って操作します。

失敗した Cloud Storage オペレーションの詳細なエラー情報を Google Cloud コンソールで確認する方法については、トラブルシューティングをご覧ください。

コマンドライン

gcloud beta resource-manager org-policies コマンドを使用します。

gcloud beta resource-manager org-policies STATE \
  constraints/storage.publicAccessPrevention \
  --RESOURCE RESOURCE_ID

ここで

  • STATE は次のいずれかの値を取ります。

    • enable-enforce: リソースに対する公開アクセスの防止を適用します。
    • disable-enforce: リソースに対する公開アクセスの防止を無効にします。
    • delete: リソースが親リソースの値を継承できるように、リソースから組織のポリシーの制約を削除します。
  • RESOURCE は、公開アクセスの防止を無効にするリソースです。たとえば、organizationprojectfolder です。

  • RESOURCE_ID はリソースの ID です。たとえば、組織 ID123456789012フォルダ ID245321プロジェクト IDmy-pet-project を使用します。

詳しくは、制約の使用をご覧ください。

disable-enforce 使用時の出力の例を次に示します。

etag: BwVJi0OOESU=
booleanPolicy: {}
constraint: constraints/storage.publicAccessPrevention

公開アクセス防止のステータスを表示する

プロジェクト、フォルダ、組織レベルで公開アクセス防止のステータスを表示するには:

コンソール

storage.publicAccessPrevention 制約を使用して、組織のポリシーの作成と管理の手順に沿って操作します。

失敗した Cloud Storage オペレーションの詳細なエラー情報を Google Cloud コンソールで確認する方法については、トラブルシューティングをご覧ください。

コマンドライン

describe --effective コマンドを使用します。

gcloud beta resource-manager org-policies describe \
  constraints/storage.publicAccessPrevention --effective \
  --RESOURCE RESOURCE_ID

ここで

  • RESOURCE は、公開アクセス防止のステータスを表示するリソースです。たとえば、organizationprojectfolder です。

  • RESOURCE_ID は、リソースの ID です。たとえば、組織 ID には 123456789012フォルダ ID には 245321プロジェクト ID には my-pet-project などです。

詳しくは、制約の使用をご覧ください。

次のステップ