简体   繁体   English

无法加载默认凭据? (Node.js 谷歌计算引擎)

[英]Could not load the default credentials? (Node.js Google Compute Engine)

I am trying to create a new vm using Nodejs client libraries of GCP, I followed the below link, https://googleapis.dev/nodejs/compute/latest/VM.html#create我正在尝试使用 GCP 的 Nodejs 客户端库创建一个新的虚拟机,我按照以下链接进行操作, https: //googleapis.dev/nodejs/compute/latest/VM.html#create

and below is my code下面是我的代码

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();

when i run this, the error I am getting is当我运行这个时,我得到的错误是

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)

My scenario is to take the service account credential from string variable rather than from env var or some other thing.我的方案是从字符串变量而不是 env var 或其他一些东西中获取服务帐户凭据。
I can see that it is trying to take the default credential which is not there in my case.我可以看到它正在尝试采用在我的情况下不存在的默认凭据。
I was able to achieve this in java, but here i am not able to do it.我能够在java中实现这一点,但在这里我无法做到。 Any help will be appreciated.任何帮助将不胜感激。

In order to execute your local application using your own user credentials for API access temporarily you can run:为了临时使用您自己的用户凭据进行 API 访问来执行您的本地应用程序,您可以运行:

gcloud auth application-default login
  • You have to install sdk into your computer, that will enable you to run the code.您必须将 sdk 安装到您的计算机中,这将使您能够运行代码。
  • Then log in to your associated gmail account and you will be ready.然后登录到您关联的 Gmail 帐户,您就可以准备好了。
  • You can check the following documentation , to get more information.您可以查看以下文档以获取更多信息。

Another option is to set GOOGLE_APPLICATION_CREDENTIALS to provide authentication credentials to your application code.另一种选择是设置GOOGLE_APPLICATION_CREDENTIALS以向您的应用程序代码提供身份验证凭据。 It should point to a file that defines the credentials.它应该指向定义凭据的文件。

To get this file please follow the steps:要获取此文件,请按照以下步骤操作:

  1. Navigate to the APIs & Services→Credentials panel in Cloud Console.导航到 Cloud Console 中的API 和服务→凭据面板。
  2. Select Create credentials , then select API key from the dropdown menu.选择创建凭据,然后从下拉菜单中选择API 密钥
  3. The API key created dialog box displays your newly created key. API 密钥创建对话框显示您新创建的密钥。
  4. You might want to copy your key and keep it secure.您可能想要复制您的密钥并确保其安全。 Unless you are using a testing key that you intend to delete later.除非您正在使用打算稍后删除的测试密钥。
  5. Put the *.json file you just downloaded in a directory of your choosing.将您刚刚下载的 *.json 文件放在您选择的目录中。
  6. This directory must be private (you can't let anyone get access to this), but accessible to your web server code.此目录必须是私有的(您不能让任何人访问此目录),但您的 Web 服务器代码可以访问该目录。 You can write your own code to pass the service account key to the client library or set the environment variable GOOGLE_APPLICATION_CREDENTIALS to the path of the JSON file downloaded.您可以编写自己的代码将服务帐户密钥传递给客户端库,也可以将环境变量 GOOGLE_APPLICATION_CREDENTIALS 设置为下载的 JSON 文件的路径。

I have found the following code that explains how you can authenticate to Google Cloud Platform APIs using the Google Cloud Client Libraries.我发现以下代码解释了如何使用 Google Cloud 客户端库对 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));
}

You could obtain more information about this in this link , also you can take a look at this other guide for Getting started with authentication .您可以在此链接中获得有关此的更多信息,也可以查看此其他身份验证入门指南。

Edit 1编辑 1

To load your credentials from a local file you can use something like:要从本地文件加载您的凭据,您可以使用以下内容:

const Compute = require('@google-cloud/compute');
const compute = new Compute({
  projectId: 'your-project-id',
  keyFilename: '/path/to/keyfile.json'
});

You can check this link for more examples and information.您可以查看此链接以获取更多示例和信息。 This other link contains another example that could be useful.此其他链接包含另一个可能有用的示例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 无法加载默认凭据? (Node.js 谷歌计算引擎教程) - Could not load the default credentials? (Node.js Google Compute Engine tutorial) Google Compute Engine上的Node.js - Node.js on Google Compute Engine “无法加载默认凭据”- 使用模拟器的 PubSub Node.js 模块 - "Could not load the default credentials" - PubSub Node.js module using the Emulator 在Google Compute Engine Debian服务器上运行Node.js - Run Node.js on a Google Compute Engine Debian server 如何在谷歌计算引擎上将 node.js 连接到 mysql? - How to connect node.js to mysql on google compute engine? 在Google Compute Engine上使用gcloud安装node.js - install node.js using gcloud on Google Compute Engine 从Google Compute Engine外部访问Node.js服务器 - Reaching Node.js server externally from Google Compute Engine AWS 凭证错误:无法从任何提供商加载凭证。 ElasticSearch 服务 node.js - AWS Credentials error: could not load credentials from any providers. ElasticSearch Service node.js Winston不会在Google Cloud Compute Engine上托管的Node.js应用程序的制作版本中记录事件 - Winston not logging events in productions version of a Node.js app hosted on Google Cloud Compute Engine 如何使用 Google Cloud Compute Engine 为 Node.JS 应用程序配置端口转发 - How to configure Port Forwarding with Google Cloud Compute Engine for a Node.JS application
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM