猿问

如何使用个人 (gcloud) 凭据发布到 PubSub

我正在尝试使用与gcloudCLI 相同的凭据向 GCP PubSub 发布消息,但没有取得很大成功。


我可以通过以下方式确认我可以发布到某个主题


gcloud pubsub topics publish myTopic --project "myProject" --message "Hello World!"


但是,当我使用下面的代码尝试使用与 gcloud 完全相同的凭据时


creds, err := google.FindDefaultCredentials(context.Background())

if err != nil {

    panic(fmt.Sprintf("Unable to retrieve default credentials: %v", err))

}

client, err := pubsub.NewClient(ctx, "myproject", option.WithCredentials(creds))

if err != nil {

    panic(fmt.Sprintf("unable to create GCP storage client: %v", err))

}

topic := client.Topic("myTopic")

r := topic.Publish(ctx, &pubsub.Message{

    Data: []byte("Hello World!"),

})

_, err = r.Get(ctx)

if err != nil {

    panic(fmt.Sprintf("failed to publish message: %v", err))

}

我收到以下错误消息


panic: failed to publish message: rpc error: code = Unauthenticated desc = transport: oauth2: cannot fetch token: 400 Bad Request

Response: {

  "error": "invalid_grant",

  "error_description": "Bad Request"

}

我还尝试直接加载 json 文件,以确保它没有在某处获取其他默认凭据,但出现相同的错误。


如何使用与 gcloud CLI 相同的凭据发布到我有权访问的 pubsub 主题?


拉丁的传说
浏览 192回答 3
3回答

子衿沉夜

您是否尝试过模拟服务帐户选项?[1] 也许这就是你要找的。希望对您有所帮助...[1] https://cloud.google.com/sdk/gcloud/reference#--impersonate-service-account

侃侃尔雅

当我配置我的本地环境时,我正在这样做运行命令:gcloud auth application-default login单击链接并分配 Google Auth Library命令的结果应该显示如下Credentials saved to file: [/path/to/application_default_credentials.json] These credentials will be used by any library that requests Application Default Credentials (ADC).复制/path/to/application_default_credentials.jsonGOOGLE_APPLICATION_CREDENTIALS使用此值创建环境变量。在 Linux 中:export GOOGLE_APPLICATION_CREDENTIALS=/path/to/application_default_credentials.json现在,您的个人凭据也被定义为在本地环境中运行的应用程序的默认凭据。

芜湖不芜

您需要在 Go 脚本中设置身份验证。默认情况下,它将使用与运行代码的环境中存在的凭据相同的凭据。这是在创建存储桶时使用默认凭据设置新客户端的示例:package mainimport (    "context"    "fmt"    "log"    "time"    "cloud.google.com/go/storage" func main() {    ctx := context.Background()    // Sets your Google Cloud Platform project ID.    projectID := "YOUR_PROJECT_ID"    // Creates a client.    client, err := storage.NewClient(ctx)    if err != nil {            log.Fatalf("Failed to create client: %v", err)    }因此,请在您的代码中尝试此操作:ctx := context.Background()client := pubsub.NewClient(ctx)
随时随地看视频慕课网APP

相关分类

Go
我要回答