【发布时间】:2021-01-02 02:52:43
【问题描述】:
我正在尝试使用 GCP 的 Nodejs 客户端库创建一个新的虚拟机,我点击了以下链接, https://googleapis.dev/nodejs/compute/latest/VM.html#create
下面是我的代码
const Compute = require('@google-cloud/compute');
const {auth} = require('google-auth-library');
const compute = new Compute();
var cred = "<<<credential json content as string>>>";
auth.scopes = ['https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/compute'];
auth.jsonContent = JSON.parse(cred);
const config = {
machineType: 'n1-standard-1',
disks: [ {
boot: true,
initializeParams: { sourceImage: '<<<image url>>>' }
} ],
networkInterfaces: [ { network: 'global/networks/default' } ],
tags: [ { items: [ 'debian-server', 'http-server' ] } ],
auth: auth,
};
async function main() {
// [START gce_create_vm]
async function createVM() {
const zone = compute.zone('us-central1-c');
const vm = zone.vm('vm-name');
await vm.create(config).then(function(data) {
const vm = data[0];
const operation = data[1];
const apiResponse = data[2];
});
console.log(vm);
console.log('Virtual machine created!');
}
createVM().catch(function (err) {
console.log(err);
});
// [END gce_create_vm]
}
main();
当我运行它时,我得到的错误是
Error: Could not load the default credentials. Browse to https://cloud.google.com/docs/authentication/getting-started for more information.
at GoogleAuth.getApplicationDefaultAsync (D:\Click to deploy\src\c2dNodeGCP\node_modules\google-auth-library\build\src\auth\googleauth.js:155:19)
at processTicksAndRejections (internal/process/task_queues.js:97:5)
at async GoogleAuth.getClient (D:\Click to deploy\src\c2dNodeGCP\node_modules\google-auth-library\build\src\auth\googleauth.js:487:17)
at async GoogleAuth.authorizeRequest (D:\Click to deploy\src\c2dNodeGCP\node_modules\google-auth-library\build\src\auth\googleauth.js:528:24)
我的方案是从字符串变量而不是从 env var 或其他东西中获取服务帐户凭据。
我可以看到它正在尝试采用在我的情况下不存在的默认凭据。
我能够在java中实现这一点,但在这里我无法做到。任何帮助将不胜感激。
【问题讨论】:
-
请注意,由于将此服务帐户签入您的代码中存在风险,因此强烈建议您不要将其作为字符串放入您的代码中。环境变量是最佳实践。
-
谢谢@JenPerson。我理解这种担忧。考虑我有 3 个用户,并且我已将凭据存储在保险库或安全位置,并且基于用户,我将从服务器检索凭据并执行操作。我该怎么做以及有哪些选择。 ps:我不想将它们存储在谷歌存储桶中
标签: node.js google-cloud-platform google-api google-compute-engine google-api-nodejs-client