Skip to content

Instantly share code, notes, and snippets.

@lmayorga1980
Created April 12, 2023 13:02
Show Gist options
  • Save lmayorga1980/fad7aa2447bd8bb45910ffeaf16885df to your computer and use it in GitHub Desktop.
Save lmayorga1980/fad7aa2447bd8bb45910ffeaf16885df to your computer and use it in GitHub Desktop.
GCloud Update Labels
import subprocess
import json
lb1 = "label1"
lb2 = "label2"
gcloud_instances_command = "gcloud compute instances list --filter=\"labels.lb1:*\" --format json"
gcloud_disks_command = "gcloud compute disks list --filter=\"-labels:lb1 AND -labels:lb2\" --format json"
result = subprocess.run(gcloud_instances_command, shell=True, text=True, capture_output=True)
if result.returncode == 0:
instances = json.loads(result.stdout)
print(str(len(instances)))
for instance in instances:
print("Set Labels for Instance: " + instance['name'])
#NOTE: RUN gcloud and set the label values
setcmd1 = "gcloud compute instances add-labels {} --labels=lb1={}".format(instance['name'],lb1)
setcmd2 = "gcloud compute instances add-labels {} --labels=lb2={}".format(instance['name'],lb2)
subprocess.run(setcmd1, shell=True, text=True, capture_output=True)
subprocess.run(setcmd2, shell=True, text=True, capture_output=True)
gcloud_gcs_command = "gcloud storage buckets list --filter=\"-labels:lb1 AND -labels:lb2\" --format json"
result = subprocess.run(gcloud_gcs_command, shell=True, text=True, capture_output=True)
if result.returncode == 0:
buckets = json.loads(result.stdout)
print(str(len(buckets)))
for bucket in buckets:
print("Fixing Bucket Label ->" + bucket['name'] )
setcmd1 = "gcloud storage buckets update gs://{} --update-labels=lb1={}".format(bucket['name'],lb1)
setcmd2 = "gcloud storage buckets update gs://{} --update-labels=lb2={}".format(bucket['name'], lb2)
subprocess.run(setcmd1, shell=True, text=True, capture_output=False)
subprocess.run(setcmd2, shell=True, text=True, capture_output=False)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment