我正在嘗試學習更多 Go,我的第一個程式是列出我們 GCP 組織中的所有專案(API 等效于gcloud projects list
)。稍后我想以此為跳板,在更新 Compute Engine 標簽時創建機器映像。
我正在使用 Google API 檔案中的這個樣板:
“ListProjects 列出了作為指定檔案夾或組織資源的直接子項的專案。”
package main
import (
resourcemanager "cloud.google.com/go/resourcemanager/apiv3"
"context"
"google.golang.org/api/iterator"
resourcemanagerpb "google.golang.org/genproto/googleapis/cloud/resourcemanager/v3"
)
func main() {
ctx := context.Background()
c, err := resourcemanager.NewProjectsClient(ctx)
if err != nil {
// TODO: Handle error.
}
defer c.Close()
req := &resourcemanagerpb.ListProjectsRequest{
// TODO: Fill request struct fields.
// See https://pkg.go.dev/google.golang.org/genproto/googleapis/cloud/resourcemanager/v3#ListProjectsRequest.
}
it := c.ListProjects(ctx, req)
for {
resp, err := it.Next()
if err == iterator.Done {
break
}
if err != nil {
// TODO: Handle error.
}
// TODO: Use resp.
_ = resp
}
}
我意識到這里有我沒有完成的“TODO”部分。有人可以幫助建議我如何使用這個樣板并獲得一個簡單的專案串列嗎?感覺好像我缺乏某種形式來識別我的組織或專案,但是由于我想要整個專案串列,所以我似乎沒有在 API 呼叫中傳達我的組織 ID?
現在我得到“PermissionDenied desc = 呼叫者沒有權限”。但是,我知道我設定了 Google 應用程式默認憑據,因為我可以在 go 中執行另一個 API 呼叫來列出計算實體。
uj5u.com熱心網友回復:
為 Cloud Resource Manager API v3使用APIs Explorerprojects.search
ORGANIZATION=[[YOUR-ORG]]
PROJECT=[[YOUR-PROJECT]] # Service Accounts are owned by Projects
ACCOUNT="tester"
# Enable Cloud Resource Manager API in a Project
# This Project will own the Service Account too
gcloud services enable cloudresourcemanager.googleapis.com \
--project=${PROJECT}
# Create the Service Account
gcloud iam service-accounts create ${ACCOUNT} \
--project=${PROJECT}
EMAIL=${ACCOUNT}@${PROJECT}.iam.gserviceaccount.com
# Create a Service Account Key locally
# For testing purposes only
gcloud iam service-accounts keys create ${PWD}/${ACCOUNT}.json \
--iam-account=${EMAIL} \
--project=${PROJECT}
# Ensure the Service Account can browse the Organization's resources
gcloud organizations add-iam-policy-binding ${ORGANIZATION} \
--role=roles/browser \
--member=serviceAccount:${EMAIL}
export GOOGLE_APPLICATION_CREDENTIALS=${PWD}/${ACCOUNT}.json
export ORGANIZATION
go run .
并且
main.go
:
package main
import (
"context"
"fmt"
"log"
"os"
resourcemanager "cloud.google.com/go/resourcemanager/apiv3"
resourcemanagerpb "google.golang.org/genproto/googleapis/cloud/resourcemanager/v3"
"google.golang.org/api/iterator"
)
func main() {
organization := os.Getenv("ORGANIZATION")
if organization == "" {
log.Fatalf("unable to obtain ORGANIZATION from the environment")
}
ctx := context.Background()
c, err := resourcemanager.NewProjectsClient(ctx)
if err != nil {
log.Fatal(err)
}
defer c.Close()
rqst := &resourcemanagerpb.SearchProjectsRequest{
Query: fmt.Sprintf("parent:organizations/%s", organization),
}
it := c.SearchProjects(ctx, rqst)
for {
resp, err := it.Next()
if err == iterator.Done {
break
}
if err != nil {
log.Fatal(err)
}
log.Println(resp.DisplayName)
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/508336.html