Get GCP Bucket Metadata Using Python
In this tutorial, we will learn how to retrieve metadata for a Google Cloud Storage bucket using Python. Metadata includes information such as bucket location, storage class, creation date, and more.
Python Code to Get Bucket Metadata
We will use the get_bucket() method of the storage.Client.
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)
# Print bucket metadata
print(f"Bucket name: {bucket.name}")
print(f"Bucket id: {bucket.id}")
print(f"Bucket location: {bucket.location}")
print(f"Bucket location type: {bucket.location_type}")
print(f"Bucket data locations: {bucket.data_locations}")
print(f"Bucket self link: {bucket.self_link}")
print(f"Bucket storage class: {bucket.storage_class}")
print(f"Bucket time created: {bucket.time_created}")
print(f"Bucket updated: {bucket.updated}")
print(f"Bucket versioning enabled: {bucket.versioning_enabled}")
print(f"Bucket path: {bucket.path}")
# Run the main function
if __name__ == "__main__":
main() Key Metadata Properties
- bucket.storage_class: Default storage class for objects (e.g., STANDARD, NEARLINE).
- bucket.location: Region or dual-region where the data is stored.
- bucket.iam_configuration: IAM settings, including uniform bucket-level access.
Note: Metadata can be useful for auditing bucket settings and ensuring they comply with your security policies.