Search code examples
jsonbashjqgcloud

Gcloud json format get not the full url of machine tpye


Running a gcloud query and trying to get the output of the json to only include the actual machine type in stead of the full url.

gcloud compute instances list --project $projectname --format=json | jq -r '.[]| .name +","+.machineType'

Which prints out as

$instancename,https://www.googleapis.com/compute/v1/projects/$projectname/zones/europe-west2-a/machineTypes/n1-standard-4

It currently prints out the full machineType, wondering if anyone knows of a way to short the url to get just the machine type as the string instead of the full url.

I've got this sed as well to clear the format but how does one apply to only the second string without deleting the name sed 's@.*/@@'

Thanks in advance

edit: found some potential with split in jq

gcloud compute instances list --project $projectname --format=json | jq -r '.[]|(.machineType|split("https://www.googleapis.com/compute/v1/projects/"))'

Solution

  • See Cloud SDK (gcloud) topic formats:

    https://cloud.google.com/sdk/gcloud/reference/topic/formats https://cloud.google.com/sdk/gcloud/reference/topic/projections#scope

    gcloud compute instances list \
    --project=${PROJECT} \
    --format="value(machineType.scope(machineTypes))"
    

    NOTE You asked how to do this with gcloud and this is the way. @rsalinas' point is good. There's a philosophy that tech should "do one thing well" and gcloud's formatting|filtering break this. Personally, I prefer to gcloud ... --format=json | jq . and use jq to process gcloud output partly because I can use the same theory with kubectl, doctl etc. etc. etc. awk is another magical tool that is generally useful.