Add an owner ACL to an object

Add an owner access control list (ACL) to an object in a Cloud Storage bucket.

Explore further

For detailed documentation that includes this code sample, see the following:

Code sample

C++

For more information, see the Cloud Storage C++ API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name,
   std::string const& object_name, std::string const& entity) {
  StatusOr<gcs::ObjectAccessControl> patched_acl =
      client.CreateObjectAcl(bucket_name, object_name, entity,
                             gcs::ObjectAccessControl::ROLE_OWNER());

  if (!patched_acl) throw std::move(patched_acl).status();
  std::cout << "ACL entry for " << patched_acl->entity() << " in object "
            << patched_acl->object() << " in bucket " << patched_acl->bucket()
            << " is now " << *patched_acl << "\n";
}

C#

For more information, see the Cloud Storage C# API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.


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

public class AddFileOwnerSample
{
    public Google.Apis.Storage.v1.Data.Object AddFileOwner(
        string bucketName = "your-unique-bucket-name",
        string objectName = "my-file-name",
        string userEmail = "dev@iam.gserviceaccount.com")
    {
        var storage = StorageClient.Create();
        var storageObject = storage.GetObject(bucketName, objectName, new GetObjectOptions
        {
            Projection = Projection.Full
        });

        storageObject.Acl.Add(new ObjectAccessControl
        {
            Bucket = bucketName,
            Entity = $"user-{userEmail}",
            Role = "OWNER",
        });
        var updatedObject = storage.UpdateObject(storageObject);
        Console.WriteLine($"Added user { userEmail} as an owner on file { objectName}.");
        return updatedObject;
    }
}

Go

For more information, see the Cloud Storage Go API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

import (
	"context"
	"fmt"

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

// addFileOwner adds ACL to the specified object.
func addFileOwner(bucket, object string, entity storage.ACLEntity) error {
	// bucket := "bucket-name"
	// object := "object-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).Object(object).ACL()
	if err := acl.Set(ctx, entity, role); err != nil {
		return fmt.Errorf("ACLHandle.Set: %w", err)
	}
	return nil
}

Java

For more information, see the Cloud Storage Java API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.


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.Blob;
import com.google.cloud.storage.BlobId;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;

public class AddFileOwner {

  public static void addFileOwner(
      String projectId, String bucketName, String userEmail, String blobName) {
    // 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 a file owner
    // String userEmail = "someuser@domain.com"

    // The name of the blob/file that you wish to modify permissions on
    // String blobName = "your-blob-name";

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

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

Node.js

For more information, see the Cloud Storage Node.js API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

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

// The name of the file to access
// const fileName = 'file.txt';

// 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 addFileOwner() {
  await storage
    .bucket(bucketName)
    .file(fileName)
    .acl.owners.addUser(userEmail);

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

addFileOwner().catch(console.error);

PHP

For more information, see the Cloud Storage PHP API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

use Google\Cloud\Storage\StorageClient;

/**
 * Add an entity and role to an object's ACL.
 *
 * @param string $bucketName The name of your Cloud Storage bucket.
 *        (e.g. 'my-bucket')
 * @param string $objectName The name of your Cloud Storage object.
 *        (e.g. 'my-object')
 * @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_object_acl(string $bucketName, string $objectName, string $entity, string $role): void
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);
    $object = $bucket->object($objectName);
    $acl = $object->acl();
    $acl->add($entity, $role);
    printf('Added %s (%s) to gs://%s/%s ACL' . PHP_EOL, $entity, $role, $bucketName, $objectName);
}

Python

For more information, see the Cloud Storage Python API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

from google.cloud import storage


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

    storage_client = storage.Client()
    bucket = storage_client.bucket(bucket_name)
    blob = bucket.blob(blob_name)

    # Reload fetches the current ACL from Cloud Storage.
    blob.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.
    blob.acl.user(user_email).grant_owner()
    blob.acl.save()

    print(
        "Added user {} as an owner on blob {} in bucket {}.".format(
            user_email, blob_name, bucket_name
        )
    )

Ruby

For more information, see the Cloud Storage Ruby API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

# The ID of your GCS bucket
# bucket_name = "your-unique-bucket-name"
# file_name   = "Name of a file in the Storage bucket"
# email       = "Google Cloud Storage ACL Entity email"

require "google/cloud/storage"

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

file.acl.add_owner email

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

What's next

To search and filter code samples for other Google Cloud products, see the Google Cloud sample browser.