根据documentation you linked,API 密钥的使用仅限于有限数量的 API:
有限数量的 GCP 服务仅允许使用 API 密钥进行访问:
- 谷歌云自然语言 API
- 谷歌云语音 API
- 谷歌云翻译 API
- 谷歌云视觉 API
- 谷歌云端点
- 谷歌云计费目录 API
- 云数据丢失防护 API
因此无法使用 API 密钥对 Compute Engine 资源进行 REST 调用。
但是,您可以选择使用Google APIs Node.js Client。
我做了一个小例子,它从实例模板创建 Compute Engine 实例,在 Node.js 8 中运行的云函数中(在 Node.js 6 中,您没有创建异步调用的选项,我相信,并且您可以从此调用中受益,因为您不必等待创建实例即可从 CF 获得响应):
index.js
const {google} = require('googleapis');
const compute = google.compute('v1');
exports.helloWorld = async data => {
const authClient = await google.auth.getClient({
scopes: [
'https://www.googleapis.com/auth/cloud-platform',
'https://www.googleapis.com/auth/compute',
],
});
const projectId = await google.auth.getProjectId();
const result = await compute.instances.insert({
auth: authClient,
project: projectId,
zone: "us-east1-c",
sourceInstanceTemplate: "projects/YOUR_PROJECT_NAME/global/instanceTemplates/YOUR_TEMPLATE_NAME-template",
resource: {
name: "example-vm-from-api-call",
},
});
console.log('done');
};
package.json
{
"name": "sample-http",
"version": "0.0.1",
"dependencies": {
"google-auth-library": "3.0.0",
"googleapis-common": "0.6.0",
"googleapis": "36.0.0"
}
}
我已将实例名称硬编码为始终example-vm-from-api-call,但在向云函数发出请求时,您可以在参数中传递实例名称,并使用它来创建实例。
另外,请注意,通过执行const authClient = await google.auth.getClient(...) 行来进行身份验证。这将采用应用程序默认经过身份验证的帐户,即执行 Cloud Function 的服务帐户。
此服务帐户默认具有project/editor 权限,足以创建 CE 虚拟机,但是如果您使用其他帐户执行这些功能,则必须为其提供正确的访问范围(参见参数前面提到的函数)。