我正在尝试使用 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。
我希望得到任何形式的帮助。
答案 0 :(得分:1)
作为 GCP 文档中的 described:
<块引用>当您使用 Cloud Console 或 Cloud SDK创建 Cloud 项目时,默认启用以下 API 和服务...
就您而言,您正在创建一个带有 Client Library 的项目。该文档需要改进,因为当它提到 Cloud SDK 时,它们实际上是指 CLI 工具,而不是客户端库。
澄清一下,当前使用客户端库或 REST 创建的项目默认没有启用任何 API。
您不能调用 Service Usage 来在项目上启用 Service Usage,因为进行调用需要已在资源项目上启用 Service Usage。
我的建议是遵循以下流程:
或者:
在某种 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 的一部分。