Sandeep Mohanty
Sandeep Mohanty

Reputation: 1552

programmatic way to provide access to a object in GCS bucket for multiple users

I have a list of users whom I want to provide read access to an object stored in my GCS Bucket.

I am able to do this task manually by adding one one user, but I want to do this programmatically.

Please guide me if there is any such way to do it.

enter image description here

Upvotes: 0

Views: 291

Answers (2)

ianyoung
ianyoung

Reputation: 3035

If it's to one particular object in a bucket then it sounds like more of an ACL approach.

gsutil will make things easier. You have a couple of options depending on your specific needs. If those users already have authenticated Google accounts then you can use the authenticatedRead predefined ACL:

gsutil acl set authenticatedRead gs://BUCKET_NAME/OBJECT_NAME

This will gives the bucket or object owner OWNER permission, and gives all authenticated Google account holders READER permission.

Or, with ACL enabled, you can retrieve the ACL of that particular object, make some edits to the JSON file, and set the updated ACL back on the object.

Retrieve the ACL of the object:

sutil acl get gs://BUCKET_NAME/OBJECT_NAME > acl.txt

Then make the permission edits by adding the required users/groups, and apply the updated ACL back to the object:

gsutil acl set acl.txt gs://BUCKET_NAME/OBJECT_NAME

You can apply the updated ACL to a particular object, bucket, or pattern (all images, etc).

Upvotes: 0

Mazlum Tosun
Mazlum Tosun

Reputation: 6572

If you are comfortable with Terraform and it's possible for you to use it, you can use the dedicated resource :

You can configure the users access as a variable in a map :

variables.tf file

variable "users_object_access" {
  default = {
    user1 = {
      entity = "[email protected]"
      role = "READER"
    }

    user2 = {
      entity = "[email protected]"
      role = "OWNER"
    }
  }
}

Then in the Terraform resource, you can use a foreach in your users access list configured previously.

main.tf file :

resource "google_storage_object_access_control" "public_rule" {
  for_each = var.users_object_access
  object = google_storage_bucket_object.object.output_name
  bucket = google_storage_bucket.bucket.name
  role   = each.value["role"]
  entity = each.value["entity"]
}

resource "google_storage_bucket" "bucket" {
  name     = "static-content-bucket"
  location = "US"
}

resource "google_storage_bucket_object" "object" {
  name   = "public-object"
  bucket = google_storage_bucket.bucket.name
  source = "../static/img/header-logo.png"
}

Upvotes: 0

Related Questions