Skip to content

Instantly share code, notes, and snippets.

@Intelrunner
Last active April 24, 2024 16:45
Show Gist options
  • Save Intelrunner/40c88dd99366de95062990615f5cda48 to your computer and use it in GitHub Desktop.
Save Intelrunner/40c88dd99366de95062990615f5cda48 to your computer and use it in GitHub Desktop.
Loops through all projects a user has available in gcloud and updates all of their buckets to clear the soft delete policy
import subprocess
# Function to run shell commands
def run_command(command):
try:
output = subprocess.check_output(command, shell=True, text=True)
return output.strip() # Return output with whitespace stripped
except subprocess.CalledProcessError as e:
print(f"Command failed with error: {e}")
return None
# Check if gcloud is installed
if run_command("type gcloud") is None:
print("gcloud is not installed. Please install it and configure your account.")
exit(1)
# Get all projects
project_ids = run_command("gcloud projects list --format='value(projectId)'")
if project_ids:
project_ids = project_ids.split('\n') # Split output into list of project IDs
else:
print("Failed to fetch project IDs or no projects available.")
exit(1)
# Loop through all projects
for project_id in project_ids:
print(f"Updating buckets in project: {project_id}")
print(f"Setting current project to: {project_id}")
# REMOVE THE BELOW TWO LINES IF YOU WANT TO GO BUCKET/BUCKET
update_result = run_command(f"gcloud storage buckets update --clear-soft-delete gs://'*'")
print (update_result)
"""
Uncomment the bottom lines to loop through bucket by bucket and update the soft-delete duration
# List all buckets in the current project and update the soft-delete duration
bucket_names = run_command(f"gcloud storage buckets list --project {project_id} --format='value(name)'")
if bucket_names:
bucket_names = bucket_names.split('\n') # Split output into list of bucket names
for bucket_name in bucket_names:
print(f"Updating bucket: {bucket_name}")
# UNCOMMENT BELOW 4 LINES TO ACTUALLY UPDATE BUCKET
# Clear Soft Delete Policy
# update_result = run_command(f"gcloud storage buckets update --clear-soft-delete gs://'*'")
#if update_result is not None:
# print(f"Updated {bucket_name} bucket.")
#else:
# print(f"Failed to update {bucket_name}.")
else:
print("No buckets found or failed to retrieve bucket list.")
"""
print("All buckets updated successfully.")
@Intelrunner
Copy link
Author

There are 2 sets of comment-outs here in the lower part. Please make sure you remove both if you actually want the bucketbybucket change to take place.

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