Inhaber zu einem Bucket hinzufügen

Einem Cloud Storage-Bucket die Inhabers-Zugriffssteuerung hinzufügen.

Weitere Informationen

Eine ausführliche Dokumentation, die dieses Codebeispiel enthält, finden Sie hier:

Codebeispiel

C++

Weitere Informationen finden Sie in der Referenzdokumentation zur Cloud Storage C++ API.

Richten Sie die Standardanmeldedaten für Anwendungen ein, um sich bei Cloud Storage zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name,
   std::string const& entity) {
  StatusOr<gcs::BucketAccessControl> patched_acl =
      client.PatchBucketAcl(bucket_name, entity,
                            gcs::BucketAccessControlPatchBuilder().set_role(
                                gcs::BucketAccessControl::ROLE_OWNER()));
  if (!patched_acl) throw std::move(patched_acl).status();
  std::cout << "ACL entry for " << patched_acl->entity() << " in bucket "
            << patched_acl->bucket() << " is now " << *patched_acl << "\n";
}

C#

Weitere Informationen finden Sie in der Referenzdokumentation zur Cloud Storage C# API.

Richten Sie die Standardanmeldedaten für Anwendungen ein, um sich bei Cloud Storage zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.


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

public class AddBucketOwnerSample
{
    public Bucket AddBucketOwner(
        string bucketName = "your-unique-bucket-name",
        string userEmail = "dev@iam.gserviceaccount.com")
    {
        var storage = StorageClient.Create();
        var bucket = storage.GetBucket(bucketName, new GetBucketOptions { Projection = Projection.Full });

        bucket.Acl ??= new List<BucketAccessControl>();

        bucket.Acl.Add(new BucketAccessControl
        {
            Bucket = bucketName,
            Entity = $"user-{userEmail}",
            Role = "OWNER",
        });
        var updatedBucket = storage.UpdateBucket(bucket);
        Console.WriteLine($"Added user { userEmail } as an owner on bucket { bucketName }.");
        return updatedBucket;
    }
}

Go

Weitere Informationen finden Sie in der Referenzdokumentation zur Cloud Storage Go API.

Richten Sie die Standardanmeldedaten für Anwendungen ein, um sich bei Cloud Storage zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

import (
	"context"
	"fmt"

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

// addBucketOwner adds ACL to the specified bucket.
func addBucketOwner(bucket string, entity storage.ACLEntity) error {
	// bucket := "bucket-name"
	// entity := storage.AllUsers
	role := storage.RoleOwner

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

	acl := client.Bucket(bucket).ACL()
	if err := acl.Set(ctx, entity, role); err != nil {
		return fmt.Errorf("ACLHandle.Set: %w", err)
	}
	return nil
}

Java

Weitere Informationen finden Sie in der Referenzdokumentation zur Cloud Storage Java API.

Richten Sie die Standardanmeldedaten für Anwendungen ein, um sich bei Cloud Storage zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.


import com.google.cloud.storage.Acl;
import com.google.cloud.storage.Acl.Role;
import com.google.cloud.storage.Acl.User;
import com.google.cloud.storage.Bucket;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;

public class AddBucketOwner {

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

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

    // Email of the user you wish to add as an owner
    // String userEmail = "someuser@domain.com"

    Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();
    Bucket bucket = storage.get(bucketName);
    Acl newOwner = Acl.of(new User(userEmail), Role.OWNER);

    bucket.createAcl(newOwner);
    System.out.println("Added user " + userEmail + " as an owner on " + bucketName);
  }
}

Node.js

Weitere Informationen finden Sie in der Referenzdokumentation zur Cloud Storage Node.js API.

Richten Sie die Standardanmeldedaten für Anwendungen ein, um sich bei Cloud Storage zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

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

// The email address of the user to add
// const userEmail = 'user-email-to-add';

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

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

async function addBucketOwner() {
  // Makes the user an owner of the bucket. You can use addAllUsers(),
  // addDomain(), addProject(), addGroup(), and addAllAuthenticatedUsers()
  // to grant access to different types of entities. You can also use "readers"
  // and "writers" to grant different roles.
  await storage.bucket(bucketName).acl.owners.addUser(userEmail);

  console.log(`Added user ${userEmail} as an owner on bucket ${bucketName}.`);
}

addBucketOwner().catch(console.error);

PHP

Weitere Informationen finden Sie in der Referenzdokumentation zur Cloud Storage PHP API.

Richten Sie die Standardanmeldedaten für Anwendungen ein, um sich bei Cloud Storage zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

use Google\Cloud\Storage\StorageClient;

/**
 * Add an entity and role to a bucket's ACL.
 *
 * @param string $bucketName The name of your Cloud Storage bucket.
 *        (e.g. 'my-bucket')
 * @param string $entity The entity for which to update access controls.
 *        (e.g. 'user-example@domain.com')
 * @param string $role The permissions to add for the specified entity.
 *        (e.g. 'OWNER')
 */
function add_bucket_acl(string $bucketName, string $entity, string $role): void
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);
    $acl = $bucket->acl();
    $acl->add($entity, $role);
    printf('Added %s (%s) to gs://%s ACL' . PHP_EOL, $entity, $role, $bucketName);
}

Python

Weitere Informationen finden Sie in der Referenzdokumentation zur Cloud Storage Python API.

Richten Sie die Standardanmeldedaten für Anwendungen ein, um sich bei Cloud Storage zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

from google.cloud import storage

def add_bucket_owner(bucket_name, user_email):
    """Adds a user as an owner on the given bucket."""
    # bucket_name = "your-bucket-name"
    # user_email = "name@example.com"

    storage_client = storage.Client()

    bucket = storage_client.bucket(bucket_name)

    # Reload fetches the current ACL from Cloud Storage.
    bucket.acl.reload()

    # You can also use `group()`, `domain()`, `all_authenticated()` and `all()`
    # to grant access to different types of entities.
    # You can also use `grant_read()` or `grant_write()` to grant different
    # roles.
    bucket.acl.user(user_email).grant_owner()
    bucket.acl.save()

    print(
        f"Added user {user_email} as an owner on bucket {bucket_name}."
    )

Ruby

Weitere Informationen finden Sie in der Referenzdokumentation zur Cloud Storage Ruby API.

Richten Sie die Standardanmeldedaten für Anwendungen ein, um sich bei Cloud Storage zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

# The ID of your GCS bucket
# bucket_name = "your-unique-bucket-name"
# email       = "Google Cloud Storage ACL Entity email"

require "google/cloud/storage"

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

bucket.acl.add_owner email

puts "Added OWNER permission for #{email} to #{bucket_name}"

Nächste Schritte

Informationen zum Suchen und Filtern von Codebeispielen für andere Google Cloud-Produkte finden Sie im Google Cloud-Beispielbrowser.