简体   繁体   中英

Unable to list folders in GCP using go client library

I am going through the documentation of cloudresourcemanager package and trying to build a simple example to list the folders of my GCP project.

The following example however fails

package main

import (
    "context"
    "fmt"
    "log"

    cloudresourcemanager "google.golang.org/api/cloudresourcemanager/v2"
)

func main() {
    ctx := context.Background()
    svc, err := cloudresourcemanager.NewService(ctx)
    if err != nil {
        log.Fatal(err)
    }
    foldersService := cloudresourcemanager.NewFoldersService(svc)
    fmt.Println(foldersService)
    foldersListCall := foldersService.List()
    resp, err := foldersListCall.Do()
    if err != nil {
        fmt.Println("Here")
        log.Fatal(err)
    }
    for _, fld := range resp.Folders {
        fmt.Println(fld.Name)
    }
}

It fails in

resp, err := foldersListCall.Do()

and the error is

googleapi: Error 400: Request contains an invalid argument., badRequest

I have the following environment variables set

GOOGLE_CLOUD_PROJECT=my-project-id
GOOGLE_APPLICATION_CREDENTIALS=/path/to/application_default_credentials.json

and gcloud cli works fine.

Any suggestions what I might be missing?

The error message is not helpful at all...

The problem is I was not setting the Parent parameter in the request, ie the organization (switching to v3 helped a bit)

package main

import (
    "context"
    "fmt"
    "log"

    cloudresourcemanager "google.golang.org/api/cloudresourcemanager/v3"
)

func main() {
    ctx := context.Background()
    svc, err := cloudresourcemanager.NewService(ctx)
    if err != nil {
        log.Fatal(err)
    }
    foldersService := cloudresourcemanager.NewFoldersService(svc)
    foldersListCall := foldersService.List()
    foldersListCall.Parent("organizations/12345678910")
    resp, err := foldersListCall.Do()
    if err != nil {
        log.Fatal(err)
    }
    for _, fld := range resp.Folders {
        fmt.Println(fld.DisplayName)
    }
}


The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM