0

我正在尝试使用适用于 Node.js 的官方 Google SDK 来自动化整个项目创建过程。对于项目创建,我使用资源管理器 SDK:

const resource = new Resource();
const project = resource.project(projectName);
const [, operation,] = await project.create();

我还必须启用一些服务才能在此过程中使用它们。当我运行时:

const client = new ServiceUsageClient();
const [operation] = await client.batchEnableServices({
  parent: `projects/${projectId}`,
  serviceIds: [
    "apigateway.googleapis.com",
    "servicecontrol.googleapis.com",
    "servicemanagement.googleapis.com",
  ]
});

我收到:

Service Usage API has not been used in project 1014682171642 before or it is disabled. Enable it by visiting https://console.developers.google.com/apis/api/serviceusage.googleapis.com/overview?project=1014682171642 then retry. If you enabled this API recently, wait a few minutes for the action to propagate to our systems and retry.

当我通过 API 创建项目时,我发现默认情况下未启用服务使用 API 很可疑。显然,如果我必须手动启用某些东西,那么使用 API 会带来好处。当我通过 Can Console 创建项目时,默认情况下会启用服务使用 API,因此此问题仅影响 API。也许还有其他方法可以以编程方式启用服务使用 API。

我将不胜感激任何形式的帮助。

4

2 回答 2

2

如GCP 文档中所述:

当您使用 Cloud Console 或 Cloud SDK创建 Cloud 项目时,默认启用以下 API 和服务...

在您的情况下,您正在创建一个带有Client Library的项目。该文档需要改进,因为当它提到 Cloud SDK 时,它们实际上是指 CLI 工具,而不是客户端库。

澄清一下,当前使用客户端库或 REST 创建的项目默认情况下没有启用任何 API。

您不能调用服务使用来启用项目的服务使用,因为进行调用需要已经在资源项目上启用服务使用。

我的建议是遵循以下流程:

  1. 某些进程使用应用程序项目 X(启用了服务使用 API)创建新项目 Y。
  2. 相同的过程,使用应用程序项目 X,在项目 Y 上批量启用 API 服务。

或者:

在某种 bash 脚本上自动化项目创建过程并使用gcloud projects create命令创建它们。

于 2021-07-09T04:54:26.620 回答
1

我写了一个完整的代码块,这对我有用。如果代码质量受到影响,我会提前道歉(我可能会毁掉它)——实际上我不知道任何 nodejs——我是从你的代码和互联网上的几个例子中编译出来的。

const {Resource} = require('@google-cloud/resource-manager');
const {ServiceUsageClient} = require('@google-cloud/service-usage');

const projectId = '<YOUR PROJECT ID>';
const orgId = '<YOUR ORG ID>'; // I had to use org for my project

const resource = new Resource();
async function create_project() {
    await resource
      .createProject(`${projectId}`, {
        name: `${projectId}`,
        parent: { type: "organization", id: `${orgId}` }
      })
      .then(data => {
        const operation = data[1];
        return operation.promise();
      })
      .then(data => {
        console.log("Project created successfully!");
        enable_apis();
      });
}

const client = new ServiceUsageClient();
async function enable_apis() {
  const [operation] = await client.batchEnableServices({
    parent: `projects/${projectId}`,
    serviceIds: [
      "serviceusage.googleapis.com",
      "servicecontrol.googleapis.com",
      "servicemanagement.googleapis.com",
    ]
  })
}

create_project();

这成功创建了项目并启用了三个 API。在尝试启用 api 之前,我会确保项目已完全创建(这只是一个理论)。

关于链接,您之前提到过,我在这里推测一下,但我认为 Cloud SDK 的意思是 gcloud CLI 工具,它是 Cloud SDK 的一部分。

于 2021-07-09T05:09:13.203 回答