how to identify gcloud errors in scripts

2019-08-23 18:34发布

问题:

Suppose I want to delete some of my GCP project resources using gcloud. If I have a record of their names, I can delete them all in a single bash/node/python script. The problem is I need to be able to distinguish "OK" errors from those that aren't. For example, if I delete a resource that doesn't exist, gcloud reports an error and my code has no reliable way of determining this was a 404. In this case a 404 is good. I wanted the resource to be gone and it's gone. How do I reliably determine the kind of error gcloud emits?

I've looked into --log-http and while this does output the http error response body, I'm assuming there is no future proof way to parse it out.

gcloud compute instance-templates delete trash -q --log-http
...
== body start ==
...
{
 "error": {
  "errors": [
   {
    "domain": "global",
    "reason": "notFound",
    "message": "The resource 'projects/mine/global/instanceTemplates/trash' was not found"
   }
  ],
  "code": 404,
  "message": "The resource 'projects/mine/global/instanceTemplates/trash' was not found"
 }
}
----------------------
ERROR: (gcloud.compute.instance-templates.delete) Could not fetch resource:
 - The resource 'projects/mine/global/instanceTemplates/trash' was not found

I've also tried setting the show_structured_logs property in my gcloud config. The output this yields is still not detailed enough.

gcloud config set show_structured_logs always
gcloud compute instance-templates delete trash -q
{
  "version": "0.0.1", 
  "verbosity": "ERROR", 
  "timestamp": "2018-11-12T07:00:51.505Z", 
  "message": "(gcloud.compute.instance-templates.delete) Could not fetch resource:\n - The resource 'projects/mine/global/instanceTemplates/trash' was not found\n"
}

My current solution is to just look for key phrases in the output. For this example, I'd look for was not found. This works but its hacky and is not reliable as confirmed here.

回答1:

Get a list of your resources before deleting anything and delete an item from the list. This way you will know for sure it exists

You can parse the output of this command:

gcloud compute instance-templates list


回答2:

If you need that kind of control over the replies coming in from the API server, I wholeheartedly recommend you to perform the RESTful calls yourself. gcloud is just a wrapper, it's meant for CLI use, so I hazard that's the reason why what you're looking for is not offered to you by it.