Skip to content

Instantly share code, notes, and snippets.

@mikesparr
Created December 23, 2020 22:53
Show Gist options
  • Save mikesparr/b57932151f477a8d20934c5302d3d32c to your computer and use it in GitHub Desktop.
Save mikesparr/b57932151f477a8d20934c5302d3d32c to your computer and use it in GitHub Desktop.
Google Cloud Platform example to add IAM role restricting user to specific storage buckets with conditions
#!/usr/bin/env bash
export PROJECT_ID=$(gcloud config get-value project)
export PROJECT_USER=$(gcloud config get-value core/account) # set current user
export PROJECT_NUMBER=$(gcloud projects describe $PROJECT_ID --format="value(projectNumber)")
export IDNS=${PROJECT_ID}.svc.id.goog # workload identity domain
export GCP_REGION="us-central1"
export GCP_ZONE="us-central1-a"
export SHARED_BUCKET="mike-test-team-bucket1" # CHANGEME
export PRIVATE_BUCKET="mike-test-private-bucket1" # CHANGEME
export RESTRICTED_USER="CHANGEME"
# enable apis
gcloud services enable compute.googleapis.com \
storage.googleapis.com
# create two storage buckets
gsutil mb -b on gs://${SHARED_BUCKET}
gsutil mb -b on gs://${PRIVATE_BUCKET}
# copy files to respective buckets
gsutil cp clouds.jpg gs://${SHARED_BUCKET}/
gsutil cp questions.jpg gs://${PRIVATE_BUCKET}/
# add IAM member to project, but restrict access to private bucket
gcloud beta projects add-iam-policy-binding $PROJECT_ID \
--member="user:${RESTRICTED_USER}" \
--role='roles/storage.objectViewer' \
--condition="expression=resource.name.startsWith(\"projects/$PROJECT_ID/buckets/$SHARED_BUCKET\"),title=no-private-bucket"
@mikesparr
Copy link
Author

Properly allows access to one bucket, but denies for others:

Allow

Screen Shot 2020-12-23 at 4 05 26 PM

Deny

Screen Shot 2020-12-23 at 4 05 32 PM

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment