Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/google-cloud-platform/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
无法加载默认凭据?(Node.js谷歌计算引擎)_Node.js_Google Cloud Platform_Google Api_Google Compute Engine_Google Api Nodejs Client - Fatal编程技术网

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

无法加载默认凭据?(Node.js谷歌计算引擎),node.js,google-cloud-platform,google-api,google-compute-engine,google-api-nodejs-client,Node.js,Google Cloud Platform,Google Api,Google Compute Engine,Google Api Nodejs Client,我正在尝试使用GCP的Nodejs客户端库创建一个新的vm,我遵循以下链接, 下面是我的代码 const Compute = require('@google-cloud/compute'); const {auth} = require('google-auth-library'); const compute = new Compute(); var cred = "<<<credential json content as string>>>

我正在尝试使用GCP的Nodejs客户端库创建一个新的vm,我遵循以下链接,

下面是我的代码

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();
我的场景是从字符串变量中获取服务帐户凭据,而不是从env var或其他东西获取服务帐户凭据
我可以看到,它正在尝试获取默认凭据,而在我的示例中不存在该凭据。

我能够用java实现这一点,但在这里我无法做到。任何帮助都将不胜感激。

要使用自己的API访问用户凭据临时执行本地应用程序,您可以运行:

gcloud auth application-default login
  • 你必须输入你的计算机,这样你才能运行代码
  • 然后登录到你关联的gmail帐户,你就可以准备好了
  • 您可以检查以下内容,以获取更多信息
另一个选项是设置
GOOGLE\u APPLICATION\u凭据
,为应用程序代码提供身份验证凭据。它应该指向定义凭据的文件

要获取此文件,请执行以下步骤:

  • 导航到云控制台中的面板
  • 选择创建凭证,然后从下拉菜单中选择API键
  • 创建的API密钥对话框显示新创建的密钥
  • 您可能希望复制您的密钥并确保其安全。除非您使用的是稍后要删除的测试密钥
  • 将刚下载的*.json文件放在您选择的目录中
  • 此目录必须是私有的(您不能让任何人访问此目录),但可以由您的web服务器代码访问。 您可以编写自己的代码,将服务帐户密钥传递到客户端库,或者将环境变量GOOGLE_APPLICATION_CREDENTIALS设置为下载的JSON文件的路径
  • 我发现以下内容解释了如何使用Google云客户端库对Google云平台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));
    }
    
    你可以在这篇文章中获得更多关于这方面的信息,你也可以在这篇文章的另一篇指南中查看

    编辑1 要从本地文件加载凭据,可以使用以下方法:

    const Compute = require('@google-cloud/compute');
    const compute = new Compute({
      projectId: 'your-project-id',
      keyFilename: '/path/to/keyfile.json'
    });
    
    您可以查看此项以获取更多示例和信息。
    另一个包含另一个可能有用的示例。

    感谢您的回复,我只想知道,有没有办法在不将凭据存储在存储桶中的情况下使用凭据。没有必要,只要您先进行身份验证,就像我在第一个解决方法中提到的那样,暂时使用您自己的API访问用户凭据。您好@Jose,我已经更新了上面的场景,请查看that@smootherbug我已经更新了我的原始答案,请检查最后一次编辑。GoogleAuth{checkIsGCE:undefined,jsonContent:null,cachedCredential:null,_CachedProject:'proj id',keyFilename:'',作用域:['',clientOptions:未定义}在这个关键文件中,name可以正常工作,但当我尝试传递scopes或jsonContent时,它不会接受它们。它是否仅以这种方式工作,或者我遗漏了什么注意,由于将此服务帐户检查到代码中的风险,强烈建议您不要将其作为字符串放入代码中。环境变量是最好的做法谢谢。JeNeNo。我理解关心。考虑我有3个用户,我已经把证书存储在一个保险箱或一个安全的位置,并且基于用户,我将从服务器中检索这些文件夹并执行操作。我怎样才能做到这一点以及哪些选项。P.S:我不想把它们存储在谷歌存储桶中。
    const Compute = require('@google-cloud/compute');
    const compute = new Compute({
      projectId: 'your-project-id',
      keyFilename: '/path/to/keyfile.json'
    });