Set Object Versioning in GCP Bucket using Python

Object Versioning in Google Cloud Storage allows you to retain non-current versions of objects when they are overwritten or deleted. This provides protection against accidental deletion or modification.

Python Code to Set Object Versioning

We will use the versioning_enabled property of the bucket object to enable versioning.

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 versioning for the bucket
    bucket.versioning_enabled = True

    # Patch the bucket metadata to apply changes
    bucket.patch()

    # Print confirmation message
    print(f"Versioning was enabled for bucket: {bucket.name}")

# Run the main function
if __name__ == "__main__":
    main()    

Key Steps Explained

Note: Enabling versioning increases storage costs because multiple versions of the same file are retained. Consider using lifecycle management policies to automatically delete older versions.