问题描述
我正在尝试使用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 @R_383_4045@ion.
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中实现此功能,但是在这里我无法做到这一点。任何帮助将不胜感激。
解决方法
为了使用您自己的用户凭证临时执行本地应用程序以进行API访问,您可以运行:
gcloud auth application-default login
- 您必须install sdk进入计算机,这将使您能够运行代码。
- 然后登录到关联的gmail帐户,您就可以准备就绪。
- 您可以检查以下documentation,以获取更多信息。
另一个选择是设置GOOGLE_APPLICATION_CREDENTIALS
为您的应用程序代码提供身份验证凭据。它应该指向定义凭据的文件。
要获取此文件,请按照以下步骤操作:
- 导航到Cloud Console中的APIs & Services→Credentials面板。
- 选择创建凭据,然后从下拉菜单中选择 API密钥。
- 创建的API密钥对话框显示您新创建的密钥。
- 您可能想要复制密钥并确保其安全。除非您使用测试密钥,否则打算以后删除。
- 将刚刚下载的* .json文件放在您选择的目录中。
- 该目录必须是私有的(您不能让任何人访问此目录),但是您的Web服务器代码可以访问。 您可以编写自己的代码,以将服务帐户密钥传递给客户端库,或者将环境变量GOOGLE_APPLICATION_CREDENTIALS设置为下载的JSON文件的路径。
我发现以下code说明了如何使用Google Cloud Client库向Google Cloud Platform API进行身份验证。
/**
* Demonstrates how to authenticate to Google Cloud Platform APIs using the
* Google Cloud Client Libraries.
*/
'use strict';
const authCloudImplicit = async () => {
// [START auth_cloud_implicit]
// Imports the Google Cloud client library.
const {Storage} = require('@google-cloud/storage');
// Instantiates a client. If you don't specify credentials when constructing
// the client,the client library will look for credentials in the
// environment.
const storage = new Storage();
// Makes an authenticated API request.
async function listBuckets() {
try {
const results = await storage.getBuckets();
const [buckets] = results;
console.log('Buckets:');
buckets.forEach((bucket) => {
console.log(bucket.name);
});
} catch (err) {
console.error('ERROR:',err);
}
}
listBuckets();
// [END auth_cloud_implicit]
};
const authCloudExplicit = async ({projectId,keyFilename}) => {
// [START auth_cloud_explicit]
// Imports the Google Cloud client library.
const {Storage} = require('@google-cloud/storage');
// Instantiates a client. Explicitly use service account credentials by
// specifying the private key file. All clients in google-cloud-node have this
// helper,see https://github.com/GoogleCloudPlatform/google-cloud-node/blob/master/docs/authentication.md
// const projectId = 'project-id'
// const keyFilename = '/path/to/keyfile.json'
const storage = new Storage({projectId,keyFilename});
// Makes an authenticated API request.
async function listBuckets() {
try {
const [buckets] = await storage.getBuckets();
console.log('Buckets:');
buckets.forEach((bucket) => {
console.log(bucket.name);
});
} catch (err) {
console.error('ERROR:',err);
}
}
listBuckets();
// [END auth_cloud_explicit]
};
const cli = require(`yargs`)
.demand(1)
.command(
`auth-cloud-implicit`,`Loads credentials implicitly.`,{},authCloudImplicit
)
.command(
`auth-cloud-explicit`,`Loads credentials explicitly.`,{
projectId: {
alias: 'p',default: process.env.GOOGLE_CLOUD_PROJECT,},keyFilename: {
alias: 'k',default: process.env.GOOGLE_APPLICATION_CREDENTIALS,authCloudExplicit
)
.example(`node $0 implicit`,`Loads credentials implicitly.`)
.example(`node $0 explicit`,`Loads credentials explicitly.`)
.wrap(120)
.recommendCommands()
.epilogue(
`For more information,see https://cloud.google.com/docs/authentication`
)
.help()
.strict();
if (module === require.main) {
cli.parse(process.argv.slice(2));
}
您可以在此link中获得有关此信息的更多信息,也可以查看Getting started with authentication的另一本指南。
编辑1
要从本地文件加载凭据,可以使用类似以下内容的
:const Compute = require('@google-cloud/compute');
const compute = new Compute({
projectId: 'your-project-id',keyFilename: '/path/to/keyfile.json'
});