通过 API 创建 GCP 项目不会启用服务使用 API

时间:2021-07-08 20:13:32

标签: node.js google-cloud-platform google-cloud-sdk google-cloud-console google-cloud-resource-manager

我正在尝试使用 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 创建项目时,我发现默认情况下未启用 Service Usage API 很可疑。显然,如果我必须手动启用某些东西,它会受益于使用 API。当我通过Could Console创建项目时,服务使用API​​默认是启用的,所以这个问题只影响API。也许还有其他方法可以以编程方式启用 Service Usage API。

我希望得到任何形式的帮助。

2 个答案:

答案 0 :(得分:1)

作为 GCP 文档中的 described

<块引用>

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

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

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

您不能调用 Service Usage 来在项目上启用 Service Usage,因为进行调用需要已在资源项目上启用 Service Usage。

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

  1. 某个进程使用应用程序项目 X(其中启用了 Service Usage API)创建了新项目 Y。
  2. 同样的流程,使用应用项目 X,批量启用项目 Y 上的 API 服务。

或者:

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

答案 1 :(得分: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。在尝试启用 apis 之前,我会确保项目已完全创建(这只是一个理论)。

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