1

I am trying to add label in k8s cluster, but unfortunately it delete all the add new one.

gcloud container clusters update example-cluster --zone us-west1-a --update-labels env=dev

I want to add label(preserve previous labels) in existing cluster. Is there any way to do that?

Thanks

GRVPrasad
  • 1,228
  • 1
  • 9
  • 24
Shubham Sharma
  • 313
  • 3
  • 10

3 Answers3

2

So, I have added few lines of python code in my automation create to solve above problem.

cmd = "gcloud container clusters list --format='json(name,status,zone,resourceLabels)'"
a = { "container" :  json.loads(subprocess.check_output(shlex.split(cmd)))}
labels = a['container'][0]['resourceLabels']
labels["name"]= a['container'][0]['name']  #Adding new label
new_labels = (str(labels).replace("{","").replace("}", "").replace(" ", "").replace(":", "=").replace("'", ""))
CMD = "gcloud container clusters update {0} --zone {1} --project {2} --update-labels {3} ".format(rname, zone, PROJECTID, labels)
subprocess.call(CMD, shell=True) 
Shubham Sharma
  • 313
  • 3
  • 10
1

Another easy way to add labels is through restAPI

Check this link https://cloud.google.com/healthcare/docs/how-tos/labeling-resources

Anshuman
  • 80
  • 8
0

As you can see in this documentation:

The label update will overwrite any pre-existing labels. If the cluster has existing labels you want to keep, you must include those labels along with any new labels that you want to add.

So if you want to keep the labels you need to copy them into your gcloud command and separate all the labels by a comma, as showned in the example in the same documentation

Ralemos
  • 5,571
  • 2
  • 9
  • 18