Set Uniform Bucket-Level Access in GCP Bucket using Python
Uniform Bucket-Level Access (UBLA) allows you to manage access to Cloud Storage objects exclusively through IAM policies, disabling object-level ACLs. This simplifies permission management and improves security auditing.
Python Code to Set Uniform Access
We will use the iam_configuration.uniform_bucket_level_access_enabled property of the bucket object.
Python
# Import the packages
from dotenv import load_dotenv
import os
from google.oauth2 import service_account
from google.cloud import storage
def main():
# Loads environment variables from a .env file
load_dotenv()
# Use environment variables from .env file
credentials_path = os.getenv("GOOGLE_APPLICATION_CREDENTIALS")
project_name = os.getenv("project_id")
# Get the service account credentials
credentials = service_account.Credentials.from_service_account_file(credentials_path)
# Create the Storage client
client = storage.Client(credentials=credentials, project=project_name)
# Define the bucket name
bucket_name = "new-bucket-via-python-sdk"
# Get the GCP bucket object
bucket = client.get_bucket(bucket_name)
# Enable Uniform bucket-level access
bucket.iam_configuration.uniform_bucket_level_access_enabled = True
# Patch the bucket metadata to apply changes
bucket.patch()
# Print confirmation message
print(f"Uniform bucket level access was enabled for bucket: {bucket.name}")
# Run the main function
if __name__ == "__main__":
main() Key Steps Explained
- bucket.iam_configuration.uniform_bucket_level_access_enabled = True sets the desired access control mode in the local bucket metadata.
- bucket.patch() sends the update request to Google Cloud Storage to apply the change.
Note: Enabling Uniform Bucket-Level Access disables all existing object ACLs. Ensure your IAM policies are correctly configured before enabling this feature.